: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 SparkPost webhook ingestion (#77484)
Tom Owers7017ff9bd4fa
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 11182762f0f1..ded53f12bd4c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -581,7 +581,7 @@ the row lists both.| sonatype_nexus | HTTP | requests | ✅ || sourcegraph | HTTP (GraphQL) | requests | ✅ || spacelift | HTTP (GraphQL) | requests | ✅ |-| sparkpost | HTTP | requests | ✅ |+| sparkpost | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || split_io | HTTP | requests | ✅ || spot_io | HTTP | requests + `rest_source.RESTClient` | ✅ || spotlercrm | HTTP | requests + `rest_source.RESTClient` | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/settings.pyindex b4687ae5f38a..a8af70e6b07e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/settings.py@@ -118,3 +118,52 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {# SparkPost retains message events for only 10 days, so the first sync of ``events`` can reach back# at most that far.LIMITED_RETENTION_ENDPOINTS = {"events"}++# --- Event webhooks ---------------------------------------------------------------------------+#+# Only ``events`` can be fed by webhooks. It is the append-only message-event stream, keyed on an+# immutable ``event_id``, and it is the only endpoint SparkPost pushes at all — the management+# lists (templates, sending domains, suppression list, ...) have no webhook events. Push delivery+# also outlives the 10-day retention window the poll path is bounded by, so events pushed today+# stay in the warehouse long after SparkPost stops returning them.+WEBHOOK_SCHEMA_NAMES = {"events"}++# Every element of a SparkPost delivery is ``{"msys": {"<grouping>": {...}}}``. We only subscribe+# to message-event types, so the only grouping we ever see is ``message_event``.+WEBHOOK_EVENT_GROUPING = "message_event"++# Our schema name -> the grouping the Hog template routes on.+WEBHOOK_RESOURCE_MAP = {"events": WEBHOOK_EVENT_GROUPING}++# The event types the webhook subscribes to. Deliberately the same set the Events Search API+# (``/api/v1/events/message``) returns, so a pushed row and a polled row are the same object with+# the same field names and merge cleanly on ``event_id``. Relay events (``relay_*``) and the A/B+# test events are excluded on purpose: they are separate groupings the Events Search API does not+# return, so they would land differently-shaped rows in the same table.+WEBHOOK_EVENT_TYPES = [+ "amp_click",+ "amp_initial_open",+ "amp_open",+ "bounce",+ "click",+ "delay",+ "delivery",+ "generation_failure",+ "generation_rejection",+ "initial_open",+ "injection",+ "link_unsubscribe",+ "list_unsubscribe",+ "open",+ "out_of_band",+ "policy_rejection",+ "spam_complaint",+]++# Name given to the webhook we register, so it is recognisable in the SparkPost UI.+WEBHOOK_NAME = "PostHog data warehouse"++# SparkPost POSTs a *batch* of events per delivery, but a Hog function may only produce one+# payload per request. The template therefore hands the whole batch over as a JSON string under+# this key and the source's table transformer explodes it into one row per event.+WEBHOOK_BATCH_KEY = "sparkpost_webhook_batch"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/source.pyindex d34e4cc47db5..efad91227a9f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/source.py@@ -1,4 +1,4 @@-from typing import Optional, cast+from typing import TYPE_CHECKING, Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,@@ -11,7 +11,15 @@ from posthog.schema import (SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ FieldType,+ ResumableSource,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,+ WebhookSyncResult,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)@@ -19,14 +27,19 @@ 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.sparkpost import (SparkPostSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost import sparkpost as api_clientfrom products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.settings import (ENDPOINTS,INCREMENTAL_FIELDS,LIMITED_RETENTION_ENDPOINTS,SPARKPOST_ENDPOINTS,+ WEBHOOK_EVENT_TYPES,+ WEBHOOK_RESOURCE_MAP,+ WEBHOOK_SCHEMA_NAMES,)from products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.sparkpost import (SparkPostResumeConfig,@@ -35,9 +48,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.)from products.warehouse_sources.backend.types import ExternalDataSourceType+if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC+@SourceRegistry.register-class SparkPostSource(ResumableSource[SparkPostSourceConfig, SparkPostResumeConfig]):+class SparkPostSource(+ ResumableSource[SparkPostSourceConfig, SparkPostResumeConfig],+ WebhookSource[SparkPostSourceConfig],+):api_docs_url = "https://developers.sparkpost.com/api/"@property@@ -96,6 +115,38 @@ SparkPost runs independent US and EU stacks that do not share data — pick the),],),+ webhookSetupCaption=(+ "PostHog registers an event webhook on your SparkPost account and subscribes it to the "+ "message events the Events API also returns, so pushed events land in the same table as "+ "the backfill. The API key needs the `Webhooks: Read/Write` permission.\n\n"+ "Because SparkPost only keeps message events for 10 days, the webhook is the only way to "+ "keep them for longer.\n\n"+ "**Manual setup** (only needed if automatic registration failed):\n\n"+ "1. Go to **Webhooks** in your SparkPost account and create a webhook pointing at the URL "+ "shown below\n"+ "2. Subscribe it to the message events you want, for example `delivery`, `bounce`, `open` "+ "and `click`\n"+ "3. Set authentication to **Basic auth** and choose a username and password\n\n"+ "Then paste the matching `Basic ...` header value into the field below so PostHog can "+ "verify each delivery."+ ),+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="authorization_header",+ label="Authorization header value",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Basic dXNlcjpwYXNz",+ caption=(+ "The exact value SparkPost sends in the Authorization header. PostHog fills "+ "this in when it registers the webhook for you."+ ),+ secret=True,+ ),+ ],+ ),)def get_canonical_descriptions(self) -> CanonicalDescriptions:@@ -127,6 +178,7 @@ SparkPost runs independent US and EU stacks that do not share data — pick thesupports_append=SPARKPOST_ENDPOINTS[endpoint].supports_incremental,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),should_sync_default=SPARKPOST_ENDPOINTS[endpoint].should_sync_default,+ supports_webhooks=endpoint in WEBHOOK_SCHEMA_NAMES,description=("Only the last 10 days are available on initial sync (SparkPost event retention)"if endpoint in LIMITED_RETENTION_ENDPOINTS@@ -152,6 +204,54 @@ SparkPost runs independent US and EU stacks that do not share data — pick thedef get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SparkPostResumeConfig]:return ResumableSourceManager[SparkPostResumeConfig](inputs, SparkPostResumeConfig)+ 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.sparkpost.webhook_template import ( # noqa: PLC0415+ template,+ )++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return WEBHOOK_RESOURCE_MAP++ def create_webhook(+ self, config: SparkPostSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookCreationResult:+ return api_client.create_webhook(config.region, config.api_key, webhook_url)++ def get_desired_webhook_events(+ self, config: SparkPostSourceConfig, 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(WEBHOOK_EVENT_TYPES)++ def sync_webhook_events(+ self,+ config: SparkPostSourceConfig,+ 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.region, config.api_key, webhook_url, desired_events)++ def get_external_webhook_info(+ self, config: SparkPostSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> ExternalWebhookInfo | None:+ return api_client.get_external_webhook_info(config.region, config.api_key, webhook_url)++ def delete_webhook(+ self, config: SparkPostSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookDeletionResult:+ return api_client.delete_webhook(config.region, config.api_key, webhook_url)+def source_for_pipeline(self,config: SparkPostSourceConfig,@@ -165,6 +265,7 @@ SparkPost runs independent US and EU stacks that do not share data — pick theteam_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/sparkpost/sparkpost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/sparkpost.pyindex 68954a43dd36..1ea495dec174 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/sparkpost.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/sparkpost.py@@ -1,10 +1,24 @@+import base64+import secretsimport dataclasses+from collections.abc import Iteratorfrom datetime import UTC, date, datetime, timedeltafrom typing import Any, Optionalfrom urllib.parse import urljoin, urlparse-from requests import Response-+import orjson+import pyarrow as pa+import structlog+from asgiref.sync import async_to_sync+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,+ 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,@@ -17,7 +31,20 @@ 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.sparkpost.settings import SPARKPOST_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.settings import (+ SPARKPOST_ENDPOINTS,+ WEBHOOK_BATCH_KEY,+ WEBHOOK_EVENT_GROUPING,+ WEBHOOK_EVENT_TYPES,+ WEBHOOK_NAME,+ WEBHOOK_SCHEMA_NAMES,+)++LOGGER = structlog.get_logger(__name__)++WEBHOOKS_PATH = "/api/v1/webhooks"+REQUEST_TIMEOUT_SECONDS = 30# SparkPost runs fully independent US and EU stacks that do not share data; the user picks which one# their account lives on. The set is a fixed allow-list, so the host can't be retargeted at an@@ -119,6 +146,75 @@ class SparkPostLinksPaginator(BaseNextUrlPaginator):return None+def _iter_batch_events(batch: Any) -> Iterator[dict[str, Any]]:+ """Yield the message events in one SparkPost delivery.++ A delivery is a JSON array of ``{"msys": {"<grouping>": {...}}}`` entries. Anything that isn't+ a ``message_event`` is skipped: the webhook only subscribes to message-event types, and other+ groupings (relay, A/B test) carry a different shape that can't merge into this table.+ """+ if not isinstance(batch, list):+ return+ for entry in batch:+ msys = entry.get("msys") if isinstance(entry, dict) else None+ if not isinstance(msys, dict):+ continue+ event = msys.get(WEBHOOK_EVENT_GROUPING)+ if isinstance(event, dict):+ yield event+++def _normalize_webhook_timestamp(value: Any) -> Any:+ """Restate a pushed ``timestamp`` in the format the Events Search API returns.++ Webhook payloads carry a Unix epoch in seconds (``"1460989507"``) where the REST endpoint+ returns ISO 8601 (``"2016-04-18T14:25:07.000Z"``). ``timestamp`` is both the incremental+ cursor and the datetime partition key, so leaving the epoch form in place would drop pushed+ rows into the unknown-date partition and corrupt the watermark against polled rows.+ """+ if isinstance(value, bool):+ return value+ if isinstance(value, int):+ seconds = value+ elif isinstance(value, str) and value.isdigit():+ seconds = int(value)+ else:+ return value+ return datetime.fromtimestamp(seconds, UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")+++def _webhook_table_transformer(table: pa.Table) -> pa.Table:+ """Explode the batched webhook payloads into one row per SparkPost event.++ Delta merge only dedupes across syncs, and SparkPost delivers at least once — the same+ ``event_id`` can arrive twice inside a single batch, either as a retried delivery or across+ two files read into the same batch. SparkPost events are immutable, so any repeat is a copy+ of the same event and last-one-wins keeps exactly one row per id.+ """+ if WEBHOOK_BATCH_KEY not in table.column_names:+ return table++ rows_by_event_id: dict[str, dict[str, Any]] = {}+ for raw_batch in table.column(WEBHOOK_BATCH_KEY).to_pylist():+ if not raw_batch:+ continue+ try:+ batch = orjson.loads(raw_batch)+ except orjson.JSONDecodeError:+ LOGGER.warning("Skipping unparseable SparkPost webhook batch")+ continue++ for event in _iter_batch_events(batch):+ event_id = event.get("event_id")+ if event_id is None:+ continue+ row = dict(event)+ row["timestamp"] = _normalize_webhook_timestamp(row.get("timestamp"))+ rows_by_event_id[str(event_id)] = row++ return table_from_py_list(list(rows_by_event_id.values()))++def sparkpost_source(region: Optional[str],api_key: str,@@ -126,6 +222,7 @@ def sparkpost_source(team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[SparkPostResumeConfig],+ webhook_source_manager: Optional[WebhookSourceManager] = None,should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:@@ -205,9 +302,20 @@ def sparkpost_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)()++ def items():+ # Webhooks supplement the backfill: the poll runs until the initial sync completes, then+ # the manager takes over and delivers the pushed events.+ 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_keys,sort_mode="asc",partition_count=1,@@ -236,3 +344,139 @@ def validate_credentials(region: Optional[str], api_key: str) -> tuple[bool, strif status == 401:return False, "Invalid SparkPost API key. Check the API key and selected region, then try again."return False, f"SparkPost credential validation failed (status {status})."+++def _webhook_session(api_key: str, *extra_redactions: str) -> Session:+ return make_tracked_session(+ headers={"Authorization": api_key, "Accept": "application/json"},+ redact_values=(api_key, *extra_redactions),+ # Webhook responses can echo the delivery credentials, so keep them out of sample capture.+ capture=False,+ )+++def _permission_error(status_code: int | None) -> str | None:+ if status_code in (401, 403):+ return (+ "SparkPost rejected the API key while managing the webhook. The key needs the "+ "`Webhooks: Read/Write` permission."+ )+ return None+++def _list_webhooks(session: Session, host: str) -> list[dict[str, Any]]:+ """Return every webhook on the account. ``GET /api/v1/webhooks`` is not paginated."""+ response = session.get(f"{host}{WEBHOOKS_PATH}", timeout=REQUEST_TIMEOUT_SECONDS)+ response.raise_for_status()+ body = response.json() or {}+ results = body.get("results")+ return [item for item in results if isinstance(item, dict)] if isinstance(results, list) else []+++def _webhooks_matching(session: Session, host: str, webhook_url: str) -> list[dict[str, Any]]:+ return [item for item in _list_webhooks(session, host) if item.get("target") == webhook_url]+++def create_webhook(region: Optional[str], api_key: str, webhook_url: str) -> WebhookCreationResult:+ """Register an event webhook pointing at ``webhook_url``.++ SparkPost authenticates deliveries with credentials we choose at registration time+ (``auth_type: "basic"``), so PostHog generates a random password and stores the exact+ ``Authorization`` header SparkPost will send. The Hog template rejects any delivery whose+ header doesn't match, which is what keeps the ingest endpoint from being open to the world.+ """+ host = base_url(region)+ username = "posthog"+ password = secrets.token_urlsafe(32)+ header_value = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()++ try:+ response = _webhook_session(api_key, password, header_value).post(+ f"{host}{WEBHOOKS_PATH}",+ json={+ "name": WEBHOOK_NAME,+ "target": webhook_url,+ "events": WEBHOOK_EVENT_TYPES,+ "auth_type": "basic",+ "auth_credentials": {"username": username, "password": password},+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except Exception as e:+ LOGGER.warning("Could not reach SparkPost to register webhook", error=str(e))+ return WebhookCreationResult(success=False, error=f"Could not reach SparkPost: {e}")++ if response.status_code not in (200, 201):+ LOGGER.warning("Failed to register SparkPost webhook", status_code=response.status_code)+ error = _permission_error(response.status_code) or (+ f"SparkPost rejected the webhook registration (HTTP {response.status_code})."+ )+ return WebhookCreationResult(success=False, error=error)++ return WebhookCreationResult(success=True, extra_inputs={"authorization_header": header_value})+++def sync_webhook_events(+ region: Optional[str], api_key: str, webhook_url: str, desired_events: list[str]+) -> WebhookSyncResult:+ """Add any missing ``desired_events`` to the webhooks targeting ``webhook_url``.++ Events are merged, never removed, so a manually broadened webhook keeps its extra events.+ SparkPost's ``PUT`` only updates the fields it is given, so the delivery credentials set at+ registration are left untouched.+ """+ host = base_url(region)+ try:+ session = _webhook_session(api_key)+ for webhook in _webhooks_matching(session, host, webhook_url):+ current = [event for event in (webhook.get("events") or []) if isinstance(event, str)]+ merged = sorted(set(current) | set(desired_events))+ if merged == sorted(current):+ continue+ response = session.put(+ f"{host}{WEBHOOKS_PATH}/{webhook.get('id')}",+ json={"events": merged},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ return WebhookSyncResult(success=True)+ except Exception as e:+ LOGGER.warning("Failed to update SparkPost webhook events", error=str(e))+ return WebhookSyncResult(success=False, error=f"Failed to update the SparkPost webhook events: {e}")+++def get_external_webhook_info(region: Optional[str], api_key: str, webhook_url: str) -> ExternalWebhookInfo:+ try:+ matching = _webhooks_matching(_webhook_session(api_key), base_url(region), webhook_url)+ except Exception as e:+ return ExternalWebhookInfo(exists=False, error=str(e))++ if not matching:+ return ExternalWebhookInfo(exists=False)++ webhook = matching[0]+ return ExternalWebhookInfo(+ exists=True,+ url=webhook.get("target"),+ enabled_events=webhook.get("events"),+ # SparkPost omits `active` on older webhooks, where it defaults to true.+ status="enabled" if webhook.get("active", True) else "disabled",+ description=webhook.get("name"),+ )+++def delete_webhook(region: Optional[str], api_key: str, webhook_url: str) -> WebhookDeletionResult:+ host = base_url(region)+ try:+ session = _webhook_session(api_key)+ errors: list[str] = []+ for webhook in _webhooks_matching(session, host, webhook_url):+ response = session.delete(f"{host}{WEBHOOKS_PATH}/{webhook.get('id')}", timeout=REQUEST_TIMEOUT_SECONDS)+ if response.status_code not in (200, 202, 204):+ errors.append(f"webhook {webhook.get('id')}: HTTP {response.status_code}")+ if errors:+ return WebhookDeletionResult(success=False, error="; ".join(errors))+ return WebhookDeletionResult(success=True)+ except Exception as e:+ LOGGER.warning("Failed to delete SparkPost webhook", error=str(e))+ return WebhookDeletionResult(success=False, error=f"Failed to delete the SparkPost webhook: {e}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost.pyindex aad6d7958ed5..719936c90de9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost.py@@ -1,4 +1,5 @@import json+import base64from collections.abc import Iterablefrom datetime import UTC, date, datetimefrom typing import Any, cast@@ -6,16 +7,26 @@ from typing import Any, castimport pytestfrom unittest import mock+import pyarrow as paimport requestsfrom requests import Response+from products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.settings import (+ WEBHOOK_BATCH_KEY,+ WEBHOOK_EVENT_TYPES,+)from products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.sparkpost import (DEFAULT_REGION,SparkPostLinksPaginator,SparkPostResumeConfig,_format_from,+ _webhook_table_transformer,base_url,+ create_webhook,+ delete_webhook,+ get_external_webhook_info,sparkpost_source,+ sync_webhook_events,validate_credentials,)@@ -360,3 +371,362 @@ class TestPaginationAndResume:job_id="j",resumable_source_manager=manager,)+++def _msys(event: dict[str, Any], grouping: str = "message_event") -> dict[str, Any]:+ return {"msys": {grouping: event}}+++def _batch_table(*batches: list[dict[str, Any]]) -> pa.Table:+ return pa.table({WEBHOOK_BATCH_KEY: [json.dumps(batch) for batch in batches]})+++class TestWebhookTableTransformer:+ """SparkPost POSTs a batch of events per delivery, but a Hog function may only produce one+ payload per request — so the template hands over the whole batch and this transformer explodes+ it into the per-event rows the ``events`` table is built from."""++ def test_batch_is_exploded_into_one_row_per_event(self) -> None:+ table = _batch_table(+ [_msys({"event_id": "1", "type": "delivery", "timestamp": "1460989507"})],+ [+ _msys({"event_id": "2", "type": "open", "timestamp": "1460989600"}),+ _msys({"event_id": "3", "type": "click", "timestamp": "1460989700"}),+ ],+ )++ rows = _webhook_table_transformer(table).to_pylist()++ assert [row["event_id"] for row in rows] == ["1", "2", "3"]+ assert [row["type"] for row in rows] == ["delivery", "open", "click"]++ def test_repeated_event_id_within_a_batch_yields_one_row(self) -> None:+ # SparkPost delivers at least once, so a retried batch (or two S3 files read into the same+ # batch) can repeat an event. Delta merge only dedupes across syncs, so duplicates left in+ # here would seed multi-matching rows in the table.+ table = _batch_table(+ [_msys({"event_id": "1", "type": "delivery", "timestamp": "1460989507"})],+ [_msys({"event_id": "1", "type": "delivery", "timestamp": "1460989507"})],+ )++ rows = _webhook_table_transformer(table).to_pylist()++ assert len(rows) == 1+ assert rows[0]["event_id"] == "1"++ @pytest.mark.parametrize(+ ("pushed", "expected"),+ [+ # SparkPost pushes unix seconds; the Events Search API returns ISO 8601. `timestamp` is+ # both the incremental cursor and the datetime partition key, so an unconverted epoch+ # would drop pushed rows into the unknown-date partition and corrupt the watermark.+ ("1460989507", "2016-04-18T14:25:07.000Z"),+ (1460989507, "2016-04-18T14:25:07.000Z"),+ # A value already in the polled format is left alone.+ ("2016-04-18T14:25:07.000Z", "2016-04-18T14:25:07.000Z"),+ ],+ )+ def test_timestamp_is_restated_in_the_polled_format(self, pushed: Any, expected: str) -> None:+ table = _batch_table([_msys({"event_id": "1", "timestamp": pushed})])++ assert _webhook_table_transformer(table).to_pylist()[0]["timestamp"] == expected++ @pytest.mark.parametrize("grouping", ["relay_event", "ab_test_event"])+ def test_non_message_groupings_are_dropped(self, grouping: str) -> None:+ # Relay and A/B test events are a different shape that the Events Search API never returns,+ # so letting them through would pollute the table the poll path builds.+ table = _batch_table([_msys({"event_id": "1", "type": "relay_delivery"}, grouping=grouping)])++ assert _webhook_table_transformer(table).num_rows == 0++ @pytest.mark.parametrize(+ "batch",+ [+ # An event with no id can't be merged on the table's primary key.+ [{"msys": {"message_event": {"type": "delivery"}}}],+ # Shapes SparkPost shouldn't send, but which must not crash the sync.+ [{"msys": {}}],+ [{"not_msys": {"message_event": {"event_id": "1"}}}],+ ["not-an-object"],+ [],+ ],+ )+ def test_unusable_payloads_yield_no_rows(self, batch: Any) -> None:+ assert _webhook_table_transformer(_batch_table(batch)).num_rows == 0++ def test_unparseable_batch_is_skipped_without_losing_the_rest(self) -> None:+ table = pa.table(+ {+ WEBHOOK_BATCH_KEY: [+ "{not json",+ json.dumps([_msys({"event_id": "1", "timestamp": "1460989507"})]),+ ]+ }+ )++ rows = _webhook_table_transformer(table).to_pylist()++ assert [row["event_id"] for row in rows] == ["1"]+++class TestWebhookItems:+ """The poll path must keep running until the webhook is live, and must hand over afterwards."""++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_poll_path_is_used_when_the_webhook_is_not_live(self, MockSession: mock.MagicMock) -> None:+ _wire(MockSession.return_value, [_response([{"event_id": "1"}], links=[])])+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=False)++ rows = _rows("events", _make_manager(), webhook_source_manager=webhook_manager)++ assert rows == [{"event_id": "1"}]+ webhook_manager.get_items.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_webhook_rows_are_read_with_the_dedup_transformer(self, MockSession: mock.MagicMock) -> None:+ _wire(MockSession.return_value, [_response([], links=[])])+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)++ sparkpost_source(+ region="us",+ api_key="key",+ endpoint="events",+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ webhook_source_manager=webhook_manager,+ ).items()++ webhook_manager.get_items.assert_called_once_with(table_transformer=_webhook_table_transformer)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_non_webhook_endpoints_never_consult_the_webhook_manager(self, MockSession: mock.MagicMock) -> None:+ # Only `events` has webhook coverage; the management lists must keep polling unconditionally.+ _wire(MockSession.return_value, [_response([{"id": "t1"}])])+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)++ rows = _rows("templates", _make_manager(), webhook_source_manager=webhook_manager)++ assert rows == [{"id": "t1"}]+ webhook_manager.webhook_enabled.assert_not_called()+ webhook_manager.get_items.assert_not_called()+++def _json_response(body: Any, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ return resp+++def _webhook_object(**overrides: Any) -> dict[str, Any]:+ webhook = {+ "id": "wh_1",+ "name": "PostHog data warehouse",+ "target": WEBHOOK_URL,+ "events": ["delivery", "bounce"],+ "active": True,+ }+ webhook.update(overrides)+ return webhook+++WEBHOOK_URL = "https://app.posthog.com/public/webhooks/abc"+++class TestCreateWebhook:+ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_registers_a_webhook_authenticated_with_credentials_we_generate(self, MockSession: mock.MagicMock) -> None:+ # The whole safety story for the ingest endpoint rests on this: SparkPost signs nothing, so+ # if the registration ever stopped setting basic-auth credentials the endpoint would accept+ # anything the internet POSTs at it.+ session = MockSession.return_value+ session.post.return_value = _json_response({"results": {"id": "wh_1"}}, status_code=200)++ result = create_webhook("us", "key", WEBHOOK_URL)++ assert result.success is True+ url, kwargs = session.post.call_args[0][0], session.post.call_args[1]+ assert url == f"{HOST}/api/v1/webhooks"+ assert kwargs["json"]["target"] == WEBHOOK_URL+ assert kwargs["json"]["auth_type"] == "basic"++ credentials = kwargs["json"]["auth_credentials"]+ expected_header = (+ "Basic " + base64.b64encode(f"{credentials['username']}:{credentials['password']}".encode()).decode()+ )+ assert result.extra_inputs == {"authorization_header": expected_header}++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_generated_password_is_not_reused_between_registrations(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.post.return_value = _json_response({"results": {"id": "wh_1"}})++ first = create_webhook("us", "key", WEBHOOK_URL)+ second = create_webhook("us", "key", WEBHOOK_URL)++ assert first.extra_inputs["authorization_header"] != second.extra_inputs["authorization_header"]++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_subscribes_to_the_events_the_search_api_also_returns(self, MockSession: mock.MagicMock) -> None:+ # Subscribing to relay or A/B test events would push differently-shaped rows into the table+ # the poll path builds.+ session = MockSession.return_value+ session.post.return_value = _json_response({"results": {"id": "wh_1"}})++ create_webhook("us", "key", WEBHOOK_URL)++ events = session.post.call_args[1]["json"]["events"]+ assert events == WEBHOOK_EVENT_TYPES+ assert not [event for event in events if event.startswith("relay_") or event.startswith("ab_test")]++ @mock.patch(SPARKPOST_SESSION_PATCH)+ @pytest.mark.parametrize(+ ("status_code", "expected_fragment"),+ [+ (401, "Webhooks: Read/Write"),+ (403, "Webhooks: Read/Write"),+ (500, "HTTP 500"),+ ],+ )+ def test_rejected_registration_reports_an_actionable_error(+ self, MockSession: mock.MagicMock, status_code: int, expected_fragment: str+ ) -> None:+ MockSession.return_value.post.return_value = _json_response({}, status_code=status_code)++ result = create_webhook("us", "key", WEBHOOK_URL)++ assert result.success is False+ assert result.error is not None+ assert expected_fragment in result.error+ # A failed registration must not hand back credentials the template would then trust.+ assert result.extra_inputs == {}++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_unreachable_api_is_reported_not_raised(self, MockSession: mock.MagicMock) -> None:+ MockSession.return_value.post.side_effect = requests.ConnectionError("boom")++ result = create_webhook("us", "key", WEBHOOK_URL)++ assert result.success is False+ assert result.extra_inputs == {}++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_registers_against_the_selected_region(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.post.return_value = _json_response({"results": {"id": "wh_1"}})++ create_webhook("eu", "key", WEBHOOK_URL)++ assert session.post.call_args[0][0] == "https://api.eu.sparkpost.com/api/v1/webhooks"+++class TestExternalWebhookInfo:+ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_reports_the_webhook_targeting_our_url(self, MockSession: mock.MagicMock) -> None:+ MockSession.return_value.get.return_value = _json_response(+ {"results": [_webhook_object(target="https://elsewhere.example/hook"), _webhook_object()]}+ )++ info = get_external_webhook_info("us", "key", WEBHOOK_URL)++ assert info.exists is True+ assert info.url == WEBHOOK_URL+ assert info.enabled_events == ["delivery", "bounce"]+ assert info.status == "enabled"++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_disabled_webhook_is_reported_as_disabled(self, MockSession: mock.MagicMock) -> None:+ MockSession.return_value.get.return_value = _json_response({"results": [_webhook_object(active=False)]})++ assert get_external_webhook_info("us", "key", WEBHOOK_URL).status == "disabled"++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_no_matching_webhook_reports_absent(self, MockSession: mock.MagicMock) -> None:+ MockSession.return_value.get.return_value = _json_response(+ {"results": [_webhook_object(target="https://elsewhere.example/hook")]}+ )++ assert get_external_webhook_info("us", "key", WEBHOOK_URL).exists is False++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_api_failure_is_surfaced_not_raised(self, MockSession: mock.MagicMock) -> None:+ MockSession.return_value.get.return_value = _json_response({}, status_code=403)++ info = get_external_webhook_info("us", "key", WEBHOOK_URL)++ assert info.exists is False+ assert info.error is not None+++class TestSyncWebhookEvents:+ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_missing_events_are_added_without_removing_existing_ones(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _json_response({"results": [_webhook_object(events=["delivery", "relay_delivery"])]})+ session.put.return_value = _json_response({"results": {"message": "Updated"}})++ result = sync_webhook_events("us", "key", WEBHOOK_URL, ["delivery", "open"])++ assert result.success is True+ assert session.put.call_args[0][0] == f"{HOST}/api/v1/webhooks/wh_1"+ # A manually broadened webhook keeps the extra event it was given.+ assert session.put.call_args[1]["json"] == {"events": ["delivery", "open", "relay_delivery"]}++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_no_write_when_every_desired_event_is_already_subscribed(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _json_response({"results": [_webhook_object(events=["delivery", "open"])]})++ assert sync_webhook_events("us", "key", WEBHOOK_URL, ["open", "delivery"]).success is True+ session.put.assert_not_called()++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_failure_is_reported_not_raised(self, MockSession: mock.MagicMock) -> None:+ MockSession.return_value.get.side_effect = requests.ConnectionError("boom")++ assert sync_webhook_events("us", "key", WEBHOOK_URL, ["open"]).success is False+++class TestDeleteWebhook:+ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_only_deletes_webhooks_pointing_at_our_url(self, MockSession: mock.MagicMock) -> None:+ # The account's own webhooks live alongside ours; deleting by anything looser than an exact+ # target match would tear down the customer's integrations.+ session = MockSession.return_value+ session.get.return_value = _json_response(+ {+ "results": [+ _webhook_object(id="wh_theirs", target="https://elsewhere.example/hook"),+ _webhook_object(id="wh_ours"),+ ]+ }+ )+ session.delete.return_value = _json_response({"results": {"message": "Deleted"}}, status_code=200)++ result = delete_webhook("us", "key", WEBHOOK_URL)++ assert result.success is True+ assert [call[0][0] for call in session.delete.call_args_list] == [f"{HOST}/api/v1/webhooks/wh_ours"]++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_nothing_to_delete_is_a_success(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _json_response({"results": []})++ assert delete_webhook("us", "key", WEBHOOK_URL).success is True+ session.delete.assert_not_called()++ @mock.patch(SPARKPOST_SESSION_PATCH)+ def test_rejected_delete_is_reported(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _json_response({"results": [_webhook_object()]})+ session.delete.return_value = _json_response({}, status_code=403)++ result = delete_webhook("us", "key", WEBHOOK_URL)++ assert result.success is False+ assert result.error is not None and "wh_1" in result.errordiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost_source.pyindex 4f6484a0d4f8..dcd6215d310f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost_source.py@@ -7,12 +7,15 @@ from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInpfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sparkpost import (SparkPostSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.settings import (ENDPOINTS,LIMITED_RETENTION_ENDPOINTS,+ WEBHOOK_EVENT_TYPES,+ WEBHOOK_SCHEMA_NAMES,)from products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.source import SparkPostSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.sparkpost import SparkPostResumeConfig@@ -166,6 +169,7 @@ class TestSparkPostSource:team_id=99,job_id="job-xyz",resumable_source_manager=manager,+ webhook_source_manager=mock.ANY,should_use_incremental_field=False,db_incremental_field_last_value=None,)@@ -201,3 +205,88 @@ class TestSparkPostSource:_, kwargs = mock_source.call_argsassert kwargs["should_use_incremental_field"] is Falseassert kwargs["db_incremental_field_last_value"] is None+++API_CLIENT = "products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.source.api_client"+WEBHOOK_URL = "https://app.posthog.com/public/webhooks/abc"+++class TestSparkPostSourceWebhooks:+ def setup_method(self) -> None:+ self.source = SparkPostSource()+ self.team_id = 123+ self.config = SparkPostSourceConfig(api_key="sp-key", region="us")++ def test_only_the_events_table_supports_webhooks(self) -> None:+ # The management lists have no SparkPost webhook events at all. Enabling webhooks on one+ # would swap its poll out for a feed that never delivers, emptying the table.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ assert {name for name, schema in schemas.items() if schema.supports_webhooks} == WEBHOOK_SCHEMA_NAMES++ def test_webhook_resource_map_matches_the_grouping_the_template_routes_on(self) -> None:+ assert self.source.webhook_resource_map == {"events": "message_event"}+ assert self.source.webhook_mapping_key("events") == "message_event"++ def test_webhook_template_is_a_warehouse_source_webhook(self) -> None:+ template = self.source.webhook_template++ assert template is not None+ assert template.type == "warehouse_source_webhook"+ assert {field["key"] for field in template.inputs_schema} >= {+ "authorization_header",+ "schema_mapping",+ "source_id",+ }++ def test_webhook_field_is_offered_for_manual_setup(self) -> None:+ webhook_fields = self.source.get_source_config.webhookFields or []++ assert [f.name for f in webhook_fields] == ["authorization_header"]+ assert all(getattr(f, "secret", False) for f in webhook_fields)++ def test_get_webhook_source_manager_is_bound_to_the_schema(self) -> None:+ inputs = _make_inputs()++ manager = self.source.get_webhook_source_manager(inputs)++ assert isinstance(manager, WebhookSourceManager)+ assert manager._inputs is inputs++ @pytest.mark.parametrize(+ ("eligible", "expects_events"),+ [+ (["events"], True),+ (["events", "templates"], True),+ # Nothing webhook-capable selected, so there is nothing to reconcile.+ (["templates"], False),+ ([], False),+ ],+ )+ def test_desired_webhook_events(self, eligible: list[str], expects_events: bool) -> None:+ desired = self.source.get_desired_webhook_events(self.config, eligible)++ assert (desired == WEBHOOK_EVENT_TYPES) is expects_events++ @mock.patch(API_CLIENT)+ def test_webhook_calls_are_routed_to_the_selected_region(self, mock_api: mock.MagicMock) -> None:+ # Region and key travel together: SparkPost's US and EU stacks are separate accounts, so a+ # webhook registered against the wrong host silently never fires.+ config = SparkPostSourceConfig(api_key="sp-key", region="eu")++ self.source.create_webhook(config, WEBHOOK_URL, self.team_id)+ self.source.get_external_webhook_info(config, WEBHOOK_URL, self.team_id)+ self.source.delete_webhook(config, WEBHOOK_URL, self.team_id)+ self.source.sync_webhook_events(config, WEBHOOK_URL, self.team_id, ["events"])++ mock_api.create_webhook.assert_called_once_with("eu", "sp-key", WEBHOOK_URL)+ mock_api.get_external_webhook_info.assert_called_once_with("eu", "sp-key", WEBHOOK_URL)+ mock_api.delete_webhook.assert_called_once_with("eu", "sp-key", WEBHOOK_URL)+ mock_api.sync_webhook_events.assert_called_once_with("eu", "sp-key", WEBHOOK_URL, WEBHOOK_EVENT_TYPES)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.source.sparkpost_source")+ def test_source_for_pipeline_passes_a_webhook_manager(self, mock_source: mock.MagicMock) -> None:+ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), _make_inputs())++ _, kwargs = mock_source.call_args+ assert isinstance(kwargs["webhook_source_manager"], WebhookSourceManager)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost_webhook_template.pynew file mode 100644index 000000000000..f311b842caac--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/tests/test_sparkpost_webhook_template.py@@ -0,0 +1,126 @@+import json+import base64++from parameterized import parameterized++from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest++from products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.settings import WEBHOOK_BATCH_KEY+from products.warehouse_sources.backend.temporal.data_imports.sources.sparkpost.webhook_template import template++SOURCE_ID = "source_test_123"+AUTH_HEADER = "Basic " + base64.b64encode(b"posthog:s3cr3t").decode()+SCHEMA_MAPPING = {"message_event": "schema_events"}+++class TestSparkPostWarehouseWebhookTemplate(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 _batch(self, *events) -> list:+ return [{"msys": {"message_event": event}} for event in events] or [+ {"msys": {"message_event": {"event_id": "1", "type": "delivery", "timestamp": "1460989507"}}}+ ]++ def _request(self, body, header=AUTH_HEADER, method: str = "POST") -> dict:+ payload = json.dumps(body)+ return {+ "request": {+ "method": method,+ "headers": {"authorization": header} if header is not None else {},+ "body": json.loads(payload),+ "stringBody": payload,+ "query": {},+ }+ }++ def _inputs(self, **overrides) -> dict:+ return {+ "authorization_header": AUTH_HEADER,+ "bypass_authorization_check": False,+ "schema_mapping": SCHEMA_MAPPING,+ "source_id": SOURCE_ID,+ **overrides,+ }++ def test_authenticated_batch_is_handed_over_whole(self):+ # SparkPost POSTs a batch per delivery but only one payload may be produced per request, so+ # the entire batch has to survive the handover for the source transformer to explode.+ body = self._batch(+ {"event_id": "1", "type": "delivery", "timestamp": "1460989507"},+ {"event_id": "2", "type": "open", "timestamp": "1460989600"},+ )++ self.run_function(self._inputs(), globals=self._request(body))++ payload, schema_id = self.mock_produce_to_warehouse_webhooks.call_args[0]+ assert schema_id == "schema_events"+ assert json.loads(payload[WEBHOOK_BATCH_KEY]) == body++ @parameterized.expand(+ [+ ("wrong_credentials", "Basic " + base64.b64encode(b"posthog:guessed").decode(), 401),+ ("empty_header", "", 401),+ ("no_header_at_all", None, 401),+ ]+ )+ def test_unauthenticated_delivery_is_rejected(self, _name, header, expected_status):+ # SparkPost signs nothing, so this header comparison is the only thing standing between the+ # ingest endpoint and anyone who guesses its URL.+ res = self.run_function(self._inputs(), globals=self._request(self._batch(), header=header))++ assert res.result["httpResponse"]["status"] == expected_status+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_delivery_is_rejected_when_no_credentials_are_configured(self):+ res = self.run_function(+ self._inputs(authorization_header=""), globals=self._request(self._batch(), header="Basic anything")+ )++ assert res.result == {"httpResponse": {"status": 400, "body": "Authorization header value not configured"}}+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_events_table_not_enabled_is_acknowledged_and_dropped(self):+ # SparkPost retries on a non-2xx, so an unmapped delivery must be acknowledged rather than+ # turned into a retry storm.+ res = self.run_function(self._inputs(schema_mapping={}), globals=self._request(self._batch()))++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_empty_batch_is_acknowledged_without_producing(self):+ res = self.run_function(self._inputs(), globals=self._request([]))++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_non_post_request_returns_405(self):+ res = self.run_function(self._inputs(), globals=self._request(self._batch(), method="GET"))++ assert res.result == {"httpResponse": {"status": 405, "body": "Method not allowed"}}++ def test_bypass_authorization_check_still_routes(self):+ body = self._batch()++ self.run_function(+ self._inputs(authorization_header="", bypass_authorization_check=True),+ globals=self._request(body, header=None),+ )++ payload, schema_id = self.mock_produce_to_warehouse_webhooks.call_args[0]+ assert schema_id == "schema_events"+ assert json.loads(payload[WEBHOOK_BATCH_KEY]) == bodydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/webhook_template.pynew file mode 100644index 000000000000..22a8bc1dada9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sparkpost/webhook_template.py@@ -0,0 +1,122 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-sparkpost",+ name="SparkPost warehouse source webhook",+ description="Receive SparkPost event webhook batches for data warehouse ingestion",+ icon_url="/static/services/sparkpost.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',+ }+ }+ }++ // SparkPost authenticates every delivery with the basic-auth credentials set on the webhook+ // (`auth_type: "basic"`). PostHog generates those credentials at registration time and stores+ // the exact header value SparkPost will send, so verifying is a string comparison.+ 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',+ }+ }+ }+}++// A delivery is a JSON array of `{"msys": {"message_event": {...}}}` entries. Only one payload+// may be produced per request, so the whole batch is handed over as a string and the source's+// table transformer explodes it into one row per event.+let schemaId := inputs.schema_mapping?.['message_event']++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No schema mapping for message events, skipping'+ }+ }+}++if (empty(request.body)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'Empty batch, skipping'+ }+ }+}++produceToWarehouseWebhooks({'sparkpost_webhook_batch': jsonStringify(request.body)}, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "authorization_header",+ "label": "Authorization header value",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": (+ "The exact value SparkPost sends in the Authorization header on each delivery "+ "(e.g. `Basic dXNlcjpwYXNz`). PostHog rejects deliveries whose header does not match."+ ),+ },+ {+ "type": "boolean",+ "key": "bypass_authorization_check",+ "label": "Bypass authorization header 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 SparkPost event groupings 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,+ },+ ],+)