Skip to content

: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.

feat(data-warehouse): add Hookdeck source (#77133)

Tom Owersb10101725461
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index dcb0ceb4d739..7cbe7d83c9ba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -318,6 +318,7 @@ the row lists both.
| hightouch | HTTP | requests + `rest_source.RESTClient` | ✅ |
| honeybadger | HTTP | requests | ✅ |
| honeycomb | HTTP | requests | ✅ |
+| hookdeck | HTTP | requests + `rest_source.RESTClient` | ✅ |
| hoorayhr | HTTP | requests + `rest_source.RESTClient` | ✅ |
| humanitix | HTTP | requests | ✅ |
| hubplanner | HTTP | requests | ✅ |
@@ -1044,7 +1045,6 @@ doesn't conflict with concurrent PRs.
- holded
- honeybadger
- honeycomb
-- hookdeck
- hostaway
- housecall_pro
- hubplanner
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hookdeck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hookdeck.py
index 0c69ebcb0926..fee551352b2f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hookdeck.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hookdeck.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class HookdeckSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/canonical_descriptions.py
new file mode 100644
index 000000000000..0aab4d76db0d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/canonical_descriptions.py
@@ -0,0 +1,191 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_API_DOCS = "https://hookdeck.com/docs/api"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "events": {
+ "description": "A delivery record: one row per event Hookdeck queued for a connection, tracking its status, attempt count and retry schedule. Rows are restated as retries land.",
+ "docs_url": f"{_API_DOCS}#events",
+ "columns": {
+ "id": "ID of the event.",
+ "team_id": "ID of the Hookdeck project.",
+ "webhook_id": "ID of the associated connection (webhook).",
+ "source_id": "ID of the associated source.",
+ "destination_id": "ID of the associated destination.",
+ "delivery_group": "Delivery group computed from the destination's delivery groups config.",
+ "event_data_id": "ID of the event data.",
+ "request_id": "ID of the request that created the event.",
+ "attempts": "Number of delivery attempts made.",
+ "last_attempt_at": "Date of the most recently attempted retry.",
+ "next_attempt_at": "Date of the next scheduled retry.",
+ "response_status": "HTTP status the destination returned for the latest attempt.",
+ "error_code": "Error code of the delivery attempt.",
+ "status": "Delivery status of the event.",
+ "successful_at": "Date of the latest successful attempt.",
+ "cli_id": "ID of the CLI the event is sent to.",
+ "updated_at": "Date the event was last updated.",
+ "created_at": "Date the event was created.",
+ },
+ },
+ "attempts": {
+ "description": "A single delivery try for an event, with the response the destination returned and how long it took.",
+ "docs_url": f"{_API_DOCS}#attempts",
+ "columns": {
+ "id": "ID of the attempt.",
+ "team_id": "ID of the Hookdeck project.",
+ "event_id": "ID of the event this attempt delivered.",
+ "destination_id": "ID of the destination delivery was attempted against.",
+ "response_status": "The attempt's HTTP response code.",
+ "attempt_number": "Sequential number of attempts, up to and including this one, made for the associated event.",
+ "trigger": "How the attempt was triggered.",
+ "error_code": "Error code of the delivery attempt.",
+ "body": "Response body returned by the destination.",
+ "requested_url": "URL of the destination where delivery was attempted.",
+ "http_method": "HTTP method used to deliver the attempt.",
+ "bulk_retry_id": "ID of the associated bulk retry.",
+ "status": "Status of the attempt.",
+ "successful_at": "Date the attempt was successful.",
+ "delivered_at": "Date the attempt was delivered.",
+ "responded_at": "Date the destination responded to this attempt.",
+ "delivery_latency": "Time elapsed between attempt initiation and final delivery, in milliseconds.",
+ "response_latency": "Time elapsed between attempt initiation and a response from the destination, in milliseconds.",
+ "updated_at": "Date the attempt was last updated.",
+ "created_at": "Date the attempt was created.",
+ },
+ },
+ "requests": {
+ "description": "A raw inbound HTTP request received by one of your sources, including requests that were ignored and produced no event.",
+ "docs_url": f"{_API_DOCS}#requests",
+ "columns": {
+ "id": "ID of the request.",
+ "team_id": "ID of the Hookdeck project.",
+ "verified": "Whether the request was verified when received.",
+ "original_event_data_id": "ID of the request data.",
+ "rejection_cause": "Why the request was rejected, when it was.",
+ "ingested_at": "The time the request was originally received.",
+ "source_id": "ID of the associated source.",
+ "events_count": "Count of events created from this request, excluding CLI events.",
+ "cli_events_count": "Count of CLI events created from this request.",
+ "ignored_count": "Count of connections that ignored this request.",
+ "updated_at": "Date the request was last updated.",
+ "created_at": "Date the request was created.",
+ },
+ },
+ "issues": {
+ "description": "A grouped delivery, transformation, backpressure or request failure raised by one of your issue triggers.",
+ "docs_url": f"{_API_DOCS}#issues",
+ "columns": {
+ "id": "ID of the issue.",
+ "team_id": "ID of the Hookdeck project.",
+ "type": "Issue type: delivery, transformation, backpressure or request.",
+ "status": "Status of the issue.",
+ "opened_at": "Timestamp for when the issue was last opened.",
+ "first_seen_at": "Timestamp for when the issue was first opened.",
+ "last_seen_at": "Timestamp for when the issue last occurred.",
+ "dismissed_at": "Timestamp for when the issue was dismissed.",
+ "auto_resolved_at": "Timestamp for when the issue was resolved automatically.",
+ "merged_with": "ID of the issue this one was merged into.",
+ "aggregation_keys": "Keys the issue is aggregated on.",
+ "reference": "Reference to the event and attempt the issue was created for.",
+ "updated_at": "Timestamp for when the issue was last updated.",
+ "created_at": "Timestamp for when the issue was created.",
+ },
+ },
+ "connections": {
+ "description": "A route tying a source to a destination, with the rules (retry, filter, transform, delay) applied in between.",
+ "docs_url": f"{_API_DOCS}#connections",
+ "columns": {
+ "id": "ID of the connection.",
+ "name": "Unique name of the connection for this source.",
+ "full_name": "Full name of the connection, concatenated from the source, connection and destination names.",
+ "description": "Description of the connection.",
+ "team_id": "ID of the Hookdeck project.",
+ "destination": "The associated destination object.",
+ "source": "The associated source object.",
+ "rules": "Rules configured on the connection.",
+ "disabled_at": "Date the connection was disabled.",
+ "paused_at": "Date the connection was paused.",
+ "updated_at": "Date the connection was last updated.",
+ "created_at": "Date the connection was created.",
+ },
+ },
+ "sources": {
+ "description": "An inbound endpoint that receives webhooks from a provider.",
+ "docs_url": f"{_API_DOCS}#sources",
+ "columns": {
+ "id": "ID of the source.",
+ "name": "Name of the source.",
+ "description": "Description of the source.",
+ "team_id": "ID of the Hookdeck project.",
+ "url": "The unique URL to give to the provider sending webhooks.",
+ "type": "Type of the source.",
+ "authenticated": "Whether the source is authenticated.",
+ "config": "Configuration object for the source type.",
+ "disabled_at": "Date the source was disabled.",
+ "updated_at": "Date the source was last updated.",
+ "created_at": "Date the source was created.",
+ },
+ },
+ "destinations": {
+ "description": "An endpoint Hookdeck delivers events to.",
+ "docs_url": f"{_API_DOCS}#destinations",
+ "columns": {
+ "id": "ID of the destination.",
+ "name": "A unique, human-friendly name for the destination.",
+ "description": "Description of the destination.",
+ "team_id": "ID of the Hookdeck project.",
+ "type": "Type of the destination.",
+ "config": "Configuration object for the destination type.",
+ "disabled_at": "Date the destination was disabled.",
+ "updated_at": "Date the destination was last updated.",
+ "created_at": "Date the destination was created.",
+ },
+ },
+ "transformations": {
+ "description": "A JavaScript transformation that rewrites an event before it is delivered.",
+ "docs_url": f"{_API_DOCS}#transformations",
+ "columns": {
+ "id": "ID of the transformation.",
+ "team_id": "ID of the Hookdeck project.",
+ "name": "A unique, human-friendly name for the transformation.",
+ "code": "JavaScript code to be executed.",
+ "env": "Key-value environment variables passed to the transformation.",
+ "updated_at": "Date the transformation was last updated.",
+ "created_at": "Date the transformation was created.",
+ },
+ },
+ "issue_triggers": {
+ "description": "A rule deciding when a delivery, transformation, backpressure or request failure is raised as an issue, and where it is notified.",
+ "docs_url": f"{_API_DOCS}#issue-triggers",
+ "columns": {
+ "id": "ID of the issue trigger.",
+ "team_id": "ID of the Hookdeck project.",
+ "name": "Optional unique name to reference the trigger by in the API.",
+ "type": "Issue type the trigger raises.",
+ "configs": "Configuration object for the selected issue type.",
+ "channels": "Notification channels for the trigger.",
+ "disabled_at": "Timestamp for when the issue trigger was disabled.",
+ "deleted_at": "Timestamp for when the issue trigger was deleted.",
+ "updated_at": "Timestamp for when the issue trigger was last updated.",
+ "created_at": "Timestamp for when the issue trigger was created.",
+ },
+ },
+ "bookmarks": {
+ "description": "A saved event payload kept for replaying against a connection.",
+ "docs_url": f"{_API_DOCS}#bookmarks",
+ "columns": {
+ "id": "ID of the bookmark.",
+ "team_id": "ID of the Hookdeck project.",
+ "webhook_id": "ID of the associated connection (webhook).",
+ "event_data_id": "ID of the bookmarked event data.",
+ "label": "Descriptive name of the bookmark.",
+ "alias": "Alternate alias for the bookmark.",
+ "data": "The bookmarked request data.",
+ "last_used_at": "Date the bookmark was last manually triggered.",
+ "updated_at": "Date the bookmark was last updated.",
+ "created_at": "Date the bookmark was created.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/hookdeck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/hookdeck.py
new file mode 100644
index 000000000000..522b35dd8014
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/hookdeck.py
@@ -0,0 +1,260 @@
+import dataclasses
+from collections.abc import Iterable, Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.settings import (
+ HOOKDECK_API_HOST,
+ HOOKDECK_ENDPOINTS,
+ PAGE_SIZE,
+ HookdeckEndpointConfig,
+)
+
+
+class HookdeckResumeConfig:
+ # Opaque `pagination.next` cursor pointing at the page after the last one yielded.
+ next_cursor: str
+
+
+REDACTED = "***redacted***"
+
+# Nested containers Hookdeck nests auth/verification secrets under. The whole value is masked:
+# connections embed the full source and destination objects, so matching by container name reaches
+# those embedded secrets at any depth without having to enumerate every per-type inner field.
+_SECRET_CONTAINER_KEYS = frozenset({"auth", "auth_method", "verification"})
+
+# Secret-bearing leaf keys that can sit directly in a destination/source config (e.g. an AWS or GCP
+# destination) rather than inside one of the auth containers above. Curated to unambiguously
+# credential names so non-secret fields on these rows survive.
+_SECRET_LEAF_KEYS = frozenset(
+ {
+ "access_token",
+ "refresh_token",
+ "client_secret",
+ "api_key",
+ "apikey",
+ "password",
+ "secret_access_key",
+ "access_key_id",
+ "webhook_secret_key",
+ "signing_secret",
+ "private_key",
+ "authorization",
+ }
+)
+
+
+def _redact_secrets(value: Any) -> Any:
+ """Mask credential-bearing fields in a Hookdeck row before it lands in a warehouse table.
+
+ Destination auth, source verification and transformation `env` values are all secrets a reader
+ of the resulting table would otherwise recover without holding the Hookdeck API key.
+ """
+ if isinstance(value, dict):
+ redacted: dict[str, Any] = {}
+ for key, item in value.items():
+ lowered = key.lower()
+ if item is None:
+ redacted[key] = None
+ elif lowered in _SECRET_CONTAINER_KEYS or lowered in _SECRET_LEAF_KEYS:
+ redacted[key] = REDACTED
+ elif lowered == "env" and isinstance(item, dict):
+ # Transformation env names are user-chosen and not secret; only the values are.
+ redacted[key] = dict.fromkeys(item, REDACTED)
+ else:
+ redacted[key] = _redact_secrets(item)
+ return redacted
+ if isinstance(value, list):
+ return [_redact_secrets(item) for item in value]
+ return value
+
+
+def _redact_pages(pages: Iterable[Any]) -> Iterator[Any]:
+ for page in pages:
+ yield [_redact_secrets(row) for row in page] if isinstance(page, list) else _redact_secrets(page)
+
+
+def base_url(api_version: str) -> str:
+ return f"{HOOKDECK_API_HOST}/{api_version}"
+
+
+def _format_datetime(value: Any) -> str:
+ """Format an incremental cursor value as the ISO 8601 UTC string Hookdeck's date filters take."""
+ if isinstance(value, datetime):
+ moment = value
+ elif isinstance(value, date):
+ moment = datetime.combine(value, datetime.min.time())
+ else:
+ return str(value)
+
+ utc_moment = moment.replace(tzinfo=UTC) if moment.tzinfo is None else moment.astimezone(UTC)
+ return utc_moment.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+
+def resolve_sort_field(config: HookdeckEndpointConfig, incremental_field: Optional[str]) -> str:
+ """Pick the column used for both `order_by` and the `[gte]` filter.
+
+ Falls back to the endpoint's first advertised incremental field when the stored selection isn't
+ one Hookdeck can sort by, so the request sort can never disagree with the pipeline's watermark.
+ """
+ advertised = [entry["field"] for entry in config.incremental_fields]
+ if incremental_field is not None and incremental_field in advertised:
+ return incremental_field
+ if advertised:
+ return advertised[0]
+ return config.default_order_by
+
+
+def build_params(
+ config: HookdeckEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: Optional[str],
+) -> dict[str, Any]:
+ incremental = should_use_incremental_field and bool(config.incremental_fields)
+ sort_field = resolve_sort_field(config, incremental_field) if incremental else config.default_order_by
+
+ params: dict[str, Any] = {
+ "limit": PAGE_SIZE,
+ "order_by": sort_field,
+ # Oldest first so the watermark advances page by page. Hookdeck defaults to `desc`.
+ "dir": "asc",
+ }
+
+ if incremental and db_incremental_field_last_value is not None:
+ # Hookdeck date filters take either an ISO timestamp or an operator object rendered as
+ # `field[gte]=...`. `gte` (not `gt`) re-reads the boundary row; merge dedupes it.
+ params[f"{sort_field}[gte]"] = _format_datetime(db_incremental_field_last_value)
+
+ return params
+
+
+class HookdeckCursorPaginator(JSONResponseCursorPaginator):
+ """Follows Hookdeck's opaque `pagination.next` cursor.
+
+ Hookdeck documents "loop until no `next` is returned" but doesn't state whether the final page
+ omits it, so an empty page or a cursor that doesn't advance also ends pagination rather than
+ risk looping until the activity times out.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(cursor_path="pagination.next", cursor_param="next")
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ previous_cursor = self._cursor_value
+ super().update_state(response, data)
+
+ if not self._has_next_page:
+ return
+ if data is not None and len(data) == 0:
+ self._has_next_page = False
+ return
+ if previous_cursor is not None and self._cursor_value == previous_cursor:
+ self._has_next_page = False
+
+
+def validate_credentials(api_key: str, api_version: str) -> tuple[bool, int | None]:
+ return validate_via_probe(
+ # capture=False: the probe hits `/sources`, whose rows carry verification secrets the
+ # name-based sample scrubbers don't recognise, so keep the response out of HTTP sample storage.
+ lambda: make_tracked_session(redact_values=(api_key,), capture=False),
+ f"{base_url(api_version)}/sources?limit=1",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ )
+
+
+def hookdeck_source(
+ api_key: str,
+ api_version: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[HookdeckResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ config = HOOKDECK_ENDPOINTS[endpoint]
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": base_url(api_version),
+ # The API key rides the framework's bearer auth so it is redacted from logs and errors;
+ # only the non-secret Accept header is set here.
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_key},
+ # capture=False: raw responses reach the sampler before `_redact_pages` runs, and the
+ # name-based scrubbers don't recognise Hookdeck's secret containers (`auth_method`,
+ # `verification`, `env`) or raw inbound request payloads, so keep every response body
+ # out of shared HTTP sample storage. Requests are still metered and logged (key redacted).
+ "session": make_tracked_session(capture=False, redact_values=(api_key,)),
+ },
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": build_params(
+ config,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ incremental_field,
+ ),
+ "data_selector": "models",
+ "paginator": HookdeckCursorPaginator(),
+ },
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = {"cursor": resume.next_cursor}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Called after each page is yielded, so a crash re-yields the last page (merge dedupes)
+ # rather than skipping it.
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(HookdeckResumeConfig(next_cursor=str(state["cursor"])))
+
+ # Incremental filtering is baked into the static params above, so the framework's own
+ # incremental injection is unused.
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ # Endpoints whose rows embed auth/verification secrets get masked before the rows are written,
+ # so a reader of the warehouse table can't recover credentials without the Hookdeck key.
+ items = _redact_pages(resource) if config.contains_credentials else resource
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: items,
+ primary_keys=config.primary_keys,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ # Every request pins `dir=asc` on the same column the watermark tracks.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/settings.py
new file mode 100644
index 000000000000..cf1aa1af3306
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/settings.py
@@ -0,0 +1,127 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Hookdeck pins the API version as the first path segment. Omitting it resolves to the OLDEST
+# supported version, so the version is always part of the base URL.
+HOOKDECK_API_HOST = "https://api.hookdeck.com"
+
+# `limit` is documented as max 250 (the OpenAPI schema allows 255).
+PAGE_SIZE = 250
+
+# Hookdeck restates a delivery record as retries land: `status`, `attempts`, `response_status`,
+# `error_code` and the `*_at` timestamps all move after the row was created. Incremental runs
+# re-read a trailing day of `created_at` so those updates merge in instead of freezing at the
+# value they had when first imported.
+_RESTATED_RECORD_LOOKBACK_SECONDS = 24 * 60 * 60
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class HookdeckEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Sent as `order_by` when the endpoint is synced without an incremental field. Every value here
+ # (and every incremental field below) must be in the endpoint's documented `order_by` enum, so
+ # rows arrive in the order `sort_mode="asc"` promises.
+ default_order_by: str = "created_at"
+ # Only fields Hookdeck accepts BOTH as a date filter and as an `order_by` value. A field that
+ # can be filtered but not sorted (e.g. `last_attempt_at` on events) would leave the request
+ # sort and the pipeline watermark on different columns, which corrupts the watermark.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ partition_key: Optional[str] = "created_at"
+ default_incremental_lookback_seconds: Optional[int] = None
+ description: Optional[str] = None
+ # Rows from this endpoint can carry auth/verification secrets (destination auth, source
+ # verification, transformation `env`, and the source/destination objects connections embed).
+ # When set, those nested fields are masked before rows are written to the warehouse so a reader
+ # of the table can't recover credentials they don't have the Hookdeck key for.
+ contains_credentials: bool = False
+
+
+HOOKDECK_ENDPOINTS: dict[str, HookdeckEndpointConfig] = {
+ "events": HookdeckEndpointConfig(
+ name="events",
+ path="/events",
+ incremental_fields=[_datetime_field("created_at")],
+ default_incremental_lookback_seconds=_RESTATED_RECORD_LOOKBACK_SECONDS,
+ description="Delivery records: one row per event Hookdeck queued for a connection, with its status, attempt count, error code and retry timestamps",
+ ),
+ "attempts": HookdeckEndpointConfig(
+ name="attempts",
+ path="/attempts",
+ # Full refresh only: `/attempts` filters by `event_id` and `id`, and has no date filter, so
+ # there is no server-side cursor to sync from.
+ description="Individual delivery attempts for events, including the response status, latency and error code of each try",
+ ),
+ "requests": HookdeckEndpointConfig(
+ name="requests",
+ path="/requests",
+ incremental_fields=[_datetime_field("created_at"), _datetime_field("ingested_at")],
+ default_incremental_lookback_seconds=_RESTATED_RECORD_LOOKBACK_SECONDS,
+ description="Raw inbound HTTP requests received by your sources, including requests that were ignored and produced no event",
+ ),
+ "issues": HookdeckEndpointConfig(
+ name="issues",
+ path="/issues",
+ incremental_fields=[
+ _datetime_field("created_at"),
+ _datetime_field("first_seen_at"),
+ _datetime_field("last_seen_at"),
+ ],
+ default_incremental_lookback_seconds=_RESTATED_RECORD_LOOKBACK_SECONDS,
+ description="Grouped delivery, transformation, backpressure and request failures raised by your issue triggers",
+ ),
+ "connections": HookdeckEndpointConfig(
+ name="connections",
+ path="/connections",
+ description="Routes that tie a source to a destination, with the rules (retry, filter, transform, delay) applied in between",
+ # Embeds the full source and destination objects, including their auth/verification config.
+ contains_credentials=True,
+ ),
+ "sources": HookdeckEndpointConfig(
+ name="sources",
+ path="/sources",
+ description="Inbound endpoints that receive webhooks from a provider, with their URL, type and verification config",
+ contains_credentials=True,
+ ),
+ "destinations": HookdeckEndpointConfig(
+ name="destinations",
+ path="/destinations",
+ description="Endpoints Hookdeck delivers events to, with their type and delivery config",
+ contains_credentials=True,
+ ),
+ "transformations": HookdeckEndpointConfig(
+ name="transformations",
+ path="/transformations",
+ description="JavaScript transformations that rewrite an event before it is delivered",
+ contains_credentials=True,
+ ),
+ "issue_triggers": HookdeckEndpointConfig(
+ name="issue_triggers",
+ path="/issue-triggers",
+ description="Rules that decide when a delivery, transformation, backpressure or request failure is raised as an issue, and where it is notified",
+ contains_credentials=True,
+ ),
+ "bookmarks": HookdeckEndpointConfig(
+ name="bookmarks",
+ path="/bookmarks",
+ description="Saved event payloads kept for replaying against a connection",
+ ),
+}
+
+ENDPOINTS = tuple(HOOKDECK_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: endpoint.incremental_fields for name, endpoint in HOOKDECK_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/source.py
index 67f26b787ba5..3f599918015f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/source.py
@@ -1,21 +1,46 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hookdeck import (
HookdeckSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.hookdeck import (
+ HookdeckResumeConfig,
+ hookdeck_source,
+ validate_credentials as validate_hookdeck_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.settings import (
+ ENDPOINTS,
+ HOOKDECK_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HookdeckSource(SimpleSource[HookdeckSourceConfig]):
+class HookdeckSource(ResumableSource[HookdeckSourceConfig, HookdeckResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # Hookdeck dates its API versions and carries the version in the URL path. An unversioned
+ # request resolves to the OLDEST supported version, so the pin is always sent.
+ supported_versions = ("2025-07-01",)
+ default_version = "2025-07-01"
+ api_docs_url = "https://hookdeck.com/docs/api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HOOKDECK
@@ -26,7 +51,112 @@ class HookdeckSource(SimpleSource[HookdeckSourceConfig]):
name=SchemaExternalDataSourceType.HOOKDECK,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Hookdeck",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["webhooks", "event gateway"],
+ caption="""Enter your Hookdeck project API key to pull your webhook delivery history into the PostHog Data warehouse.
+
+You can find the key in Hookdeck under **Settings** → **Project** → **Secrets**.
+
+API keys are scoped to a single Hookdeck project, so connect one PostHog source per project. Hookdeck deletes events, requests and attempts once your plan's retention window passes, so the first sync only reaches as far back as that window.
+""",
iconPath="/static/services/hookdeck.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/hookdeck",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.hookdeck.com": "Your Hookdeck API key is invalid or has been rotated. Copy the current key from Settings → Project → Secrets in Hookdeck, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.hookdeck.com": "Your Hookdeck API key can't access this resource. Check that the key belongs to the project you want to sync.",
+ }
+
+ def get_schemas(
+ self,
+ config: HookdeckSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ def build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = HOOKDECK_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=bool(endpoint_config.incremental_fields),
+ # Incremental runs re-read a trailing window of restated rows; only merge dedupes
+ # those, append would materialize a duplicate per sync.
+ supports_append=False,
+ incremental_fields=endpoint_config.incremental_fields,
+ description=endpoint_config.description,
+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,
+ )
+
+ schemas = [build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [schema for schema in schemas if schema.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self,
+ config: HookdeckSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ is_valid, status = validate_hookdeck_credentials(config.api_key, self.resolve_api_version(api_version))
+ if is_valid:
+ return True, None
+ if status == 401:
+ return False, "Invalid Hookdeck API key"
+ if status == 403:
+ # A project API key reaches every resource in its own project, so a 403 at source-create
+ # is more likely a plan restriction on one resource than a bad key. Only fail when a
+ # specific table was asked for.
+ if schema_name is not None:
+ return False, "Your Hookdeck API key can't access this resource"
+ return True, None
+ return False, "Could not connect to the Hookdeck API"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HookdeckResumeConfig]:
+ return ResumableSourceManager[HookdeckResumeConfig](inputs, HookdeckResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HookdeckSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HookdeckResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return hookdeck_source(
+ api_key=config.api_key,
+ api_version=self.resolve_api_version(inputs.api_version),
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/tests/test_hookdeck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/tests/test_hookdeck.py
new file mode 100644
index 000000000000..1d5228670675
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/tests/test_hookdeck.py
@@ -0,0 +1,400 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+import requests
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.hookdeck import (
+ REDACTED,
+ HookdeckResumeConfig,
+ _format_datetime,
+ _redact_secrets,
+ base_url,
+ build_params,
+ hookdeck_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.settings import (
+ HOOKDECK_ENDPOINTS,
+ PAGE_SIZE,
+)
+
+HOOKDECK_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.hookdeck.make_tracked_session"
+)
+
+API_VERSION = "2025-07-01"
+
+INCREMENTAL_ENDPOINTS = sorted(name for name, c in HOOKDECK_ENDPOINTS.items() if c.incremental_fields)
+FULL_REFRESH_ENDPOINTS = sorted(name for name, c in HOOKDECK_ENDPOINTS.items() if not c.incremental_fields)
+ENDPOINT_FIELD_PAIRS = sorted(
+ (name, entry["field"]) for name, c in HOOKDECK_ENDPOINTS.items() for entry in c.incremental_fields
+)
+
+
+def _response(models: list[dict[str, Any]] | None, next_cursor: str | None, status: int = 200) -> Response:
+ pagination: dict[str, Any] = {"order_by": "created_at", "dir": "asc", "limit": PAGE_SIZE}
+ if next_cursor is not None:
+ pagination["next"] = next_cursor
+ body = {"pagination": pagination, "count": len(models or []), "models": models or []}
+ response = Response()
+ response.status_code = status
+ response._content = json.dumps(body).encode()
+ return response
+
+
+def _make_manager(resume_state: HookdeckResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ # `request.params` is one dict mutated in place across pages, so snapshot a copy per request.
+ session.headers = {}
+ param_snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ param_snapshots.append(dict(request.params or {}))
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return param_snapshots
+
+
+def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):
+ return hookdeck_source(
+ "hd_key",
+ API_VERSION,
+ endpoint,
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+
+
+def _rows(source_response) -> list[dict[str, Any]]:
+ return [row for page in cast("Iterable[Any]", source_response.items()) for row in page]
+
+
+class TestHookdeckTransport:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ (datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45.123Z"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("2026-03-04T02:58:14.000Z", "2026-03-04T02:58:14.000Z"),
+ ],
+ )
+ def test_format_datetime_emits_iso_utc(self, value: object, expected: str) -> None:
+ result = _format_datetime(value)
+
+ assert result == expected
+ assert "+00:00" not in result
+
+ def test_base_url_carries_the_version_segment(self) -> None:
+ # An unversioned request resolves to Hookdeck's OLDEST supported version.
+ assert base_url(API_VERSION) == f"https://api.hookdeck.com/{API_VERSION}"
+
+ @pytest.mark.parametrize("endpoint", sorted(HOOKDECK_ENDPOINTS))
+ def test_every_request_pins_ascending_order(self, endpoint: str) -> None:
+ # Hookdeck defaults to `dir=desc`; sort_mode="asc" would corrupt the watermark without this.
+ params = build_params(
+ HOOKDECK_ENDPOINTS[endpoint],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+
+ assert params["dir"] == "asc"
+ assert params["limit"] == PAGE_SIZE
+ assert params["order_by"] == "created_at"
+ assert not [key for key in params if key.endswith("[gte]")]
+
+ @pytest.mark.parametrize("endpoint, field", ENDPOINT_FIELD_PAIRS)
+ def test_selected_incremental_field_drives_both_sort_and_filter(self, endpoint: str, field: str) -> None:
+ params = build_params(
+ HOOKDECK_ENDPOINTS[endpoint],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field=field,
+ )
+
+ assert params["order_by"] == field
+ assert params[f"{field}[gte]"] == "2026-03-04T02:58:14.000Z"
+
+ def test_unsortable_incremental_field_falls_back_instead_of_splitting_sort_and_filter(self) -> None:
+ # `last_attempt_at` is filterable on /events but not a valid `order_by` value.
+ params = build_params(
+ HOOKDECK_ENDPOINTS["events"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="last_attempt_at",
+ )
+
+ assert params["order_by"] == "created_at"
+ assert params["created_at[gte]"] == "2026-03-04T02:58:14.000Z"
+ assert "last_attempt_at[gte]" not in params
+
+ @pytest.mark.parametrize("endpoint", FULL_REFRESH_ENDPOINTS)
+ def test_full_refresh_endpoints_never_send_a_date_filter(self, endpoint: str) -> None:
+ params = build_params(
+ HOOKDECK_ENDPOINTS[endpoint],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+
+ assert not [key for key in params if key.endswith("[gte]")]
+
+ def test_watermark_ignored_when_incremental_is_off(self) -> None:
+ params = build_params(
+ HOOKDECK_ENDPOINTS["events"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+
+ assert "created_at[gte]" not in params
+
+ def test_first_sync_sends_no_filter(self) -> None:
+ params = build_params(
+ HOOKDECK_ENDPOINTS["events"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="created_at",
+ )
+
+ assert "created_at[gte]" not in params
+
+
+class TestHookdeckCredentials:
+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_status_mapping(self, mock_session_factory, status_code: int, expected: bool) -> None:
+ mock_session_factory.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+
+ is_valid, status = validate_credentials("hd_key", API_VERSION)
+
+ assert is_valid is expected
+ assert status == status_code
+
+ call = mock_session_factory.return_value.get.call_args
+ assert call.args[0] == f"https://api.hookdeck.com/{API_VERSION}/sources?limit=1"
+ assert call.kwargs["headers"]["Authorization"] == "Bearer hd_key"
+
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_transport_error_is_not_valid(self, mock_session_factory) -> None:
+ mock_session_factory.return_value.get.side_effect = requests.ConnectionError("boom")
+
+ assert validate_credentials("hd_key", API_VERSION) == (False, None)
+
+
+class TestHookdeckPagination:
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_follows_next_cursor_until_absent(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [_response([{"id": "evt_1"}, {"id": "evt_2"}], "cur_2"), _response([{"id": "evt_3"}], None)],
+ )
+
+ rows = _rows(_source("events", _make_manager()))
+
+ assert [row["id"] for row in rows] == ["evt_1", "evt_2", "evt_3"]
+ assert session.send.call_count == 2
+ assert "next" not in params[0]
+ assert params[1]["next"] == "cur_2"
+
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_stops_when_the_cursor_stops_advancing(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response([{"id": "evt_1"}], "cur_2"), _response([{"id": "evt_2"}], "cur_2")])
+
+ rows = _rows(_source("events", _make_manager()))
+
+ assert [row["id"] for row in rows] == ["evt_1", "evt_2"]
+ assert session.send.call_count == 2
+
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_stops_on_an_empty_page_even_with_a_cursor(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response([], "cur_2")])
+
+ assert _rows(_source("events", _make_manager())) == []
+ assert session.send.call_count == 1
+
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_saves_resume_state_after_each_page_but_not_the_last(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response([{"id": "evt_1"}], "cur_2"), _response([{"id": "evt_2"}], None)])
+ manager = _make_manager()
+
+ _rows(_source("events", manager))
+
+ assert manager.save_state.call_count == 1
+ assert manager.save_state.call_args.args[0] == HookdeckResumeConfig(next_cursor="cur_2")
+
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_resumes_from_saved_cursor(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_response([{"id": "evt_9"}], None)])
+
+ rows = _rows(_source("events", _make_manager(HookdeckResumeConfig(next_cursor="cur_7"))))
+
+ assert [row["id"] for row in rows] == ["evt_9"]
+ assert params[0]["next"] == "cur_7"
+
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_incremental_filter_rides_the_first_request(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_response([{"id": "iss_1"}], None)])
+
+ _rows(
+ _source(
+ "issues",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="last_seen_at",
+ )
+ )
+
+ assert params[0]["order_by"] == "last_seen_at"
+ assert params[0]["dir"] == "asc"
+ assert params[0]["last_seen_at[gte]"] == "2026-03-04T02:58:14.000Z"
+
+ @mock.patch("tenacity.nap.time.sleep", return_value=None)
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_retries_throttles_and_server_errors(self, MockSession, _mock_sleep) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response(None, None, status=429),
+ _response(None, None, status=503),
+ _response([{"id": "evt_1"}], None),
+ ],
+ )
+
+ rows = _rows(_source("events", _make_manager()))
+
+ assert [row["id"] for row in rows] == ["evt_1"]
+ assert session.send.call_count == 3
+
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_client_error_raises(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response(None, None, status=404)])
+
+ with pytest.raises(requests.HTTPError):
+ _rows(_source("events", _make_manager()))
+
+
+class TestHookdeckRedaction:
+ @pytest.mark.parametrize(
+ "row, expected",
+ [
+ # Destination auth_method container masked wholesale; benign fields survive.
+ (
+ {
+ "id": "des_1",
+ "name": "prod",
+ "config": {"url": "https://x", "auth_method": {"type": "BEARER", "config": {"token": "sk_live"}}},
+ },
+ {"id": "des_1", "name": "prod", "config": {"url": "https://x", "auth_method": REDACTED}},
+ ),
+ # Source verification container masked.
+ (
+ {"id": "src_1", "verification": {"type": "HMAC", "configs": {"webhook_secret_key": "whsec"}}},
+ {"id": "src_1", "verification": REDACTED},
+ ),
+ # Transformation env values masked but the (non-secret) names kept.
+ (
+ {"id": "trs_1", "code": "return x", "env": {"API_KEY": "secret", "REGION": "us"}},
+ {"id": "trs_1", "code": "return x", "env": {"API_KEY": REDACTED, "REGION": REDACTED}},
+ ),
+ # Connection embeds full source and destination objects — nested secrets reached at depth.
+ (
+ {
+ "id": "con_1",
+ "source": {"verification": {"configs": {"api_key": "k"}}},
+ "destination": {"auth": {"password": "p"}},
+ },
+ {"id": "con_1", "source": {"verification": REDACTED}, "destination": {"auth": REDACTED}},
+ ),
+ # Secret leaf keys sitting directly in a config are masked; None is left intact.
+ (
+ {"config": {"access_key_id": "AKIA", "secret_access_key": "abc", "region": None}},
+ {"config": {"access_key_id": REDACTED, "secret_access_key": REDACTED, "region": None}},
+ ),
+ ],
+ )
+ def test_redacts_credential_bearing_fields(self, row: dict[str, Any], expected: dict[str, Any]) -> None:
+ assert _redact_secrets(row) == expected
+
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_credential_endpoint_rows_are_redacted_end_to_end(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response([{"id": "des_1", "auth_method": {"config": {"token": "sk_live"}}}], None)])
+
+ rows = _rows(_source("destinations", _make_manager()))
+
+ assert rows == [{"id": "des_1", "auth_method": REDACTED}]
+
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_non_credential_endpoint_rows_pass_through_untouched(self, MockSession) -> None:
+ # `events` isn't flagged as credential-bearing, so an auth-shaped key must not be masked.
+ session = MockSession.return_value
+ _wire(session, [_response([{"id": "evt_1", "auth_method": {"config": {"token": "kept"}}}], None)])
+
+ rows = _rows(_source("events", _make_manager()))
+
+ assert rows == [{"id": "evt_1", "auth_method": {"config": {"token": "kept"}}}]
+
+
+class TestHookdeckSampleCapture:
+ # Raw responses reach the sampler before `_redact_secrets` runs, and the name-based scrubbers
+ # don't recognise Hookdeck's secret containers, so both transports must opt out of sample capture.
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_sync_session_disables_sample_capture(self, MockSession) -> None:
+ MockSession.return_value.headers = {}
+
+ _source("events", _make_manager())
+
+ assert MockSession.call_args.kwargs["capture"] is False
+
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_probe_disables_sample_capture(self, MockSession) -> None:
+ MockSession.return_value.get.return_value = mock.MagicMock(status_code=200)
+
+ validate_credentials("hd_key", API_VERSION)
+
+ assert MockSession.call_args.kwargs["capture"] is False
+
+
+class TestHookdeckSourceResponse:
+ @pytest.mark.parametrize("endpoint", sorted(HOOKDECK_ENDPOINTS))
+ @mock.patch(HOOKDECK_SESSION_PATCH)
+ def test_source_response_shape(self, MockSession, endpoint: str) -> None:
+ MockSession.return_value.headers = {}
+
+ response = _source(endpoint, _make_manager())
+
+ assert response.name == endpoint
+ # Hookdeck ids are unique per resource type, and no endpoint fans out from a parent.
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created_at"]
+ assert response.partition_format == "month"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/tests/test_hookdeck_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/tests/test_hookdeck_source.py
new file mode 100644
index 000000000000..f5722bb4f338
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hookdeck/tests/test_hookdeck_source.py
@@ -0,0 +1,170 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hookdeck import (
+ HookdeckSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.hookdeck import HookdeckResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.settings import (
+ ENDPOINTS,
+ HOOKDECK_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.source import HookdeckSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.hookdeck.source"
+
+INCREMENTAL_ENDPOINTS = sorted(name for name, c in HOOKDECK_ENDPOINTS.items() if c.incremental_fields)
+FULL_REFRESH_ENDPOINTS = sorted(name for name, c in HOOKDECK_ENDPOINTS.items() if not c.incremental_fields)
+
+
+def _make_inputs(schema_name: str = "events", **overrides):
+ defaults = {
+ "schema_name": schema_name,
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ "api_version": None,
+ }
+ defaults.update(overrides)
+ return mock.MagicMock(**defaults)
+
+
+class TestHookdeckSource:
+ def setup_method(self) -> None:
+ self.source = HookdeckSource()
+ self.team_id = 123
+ self.config = HookdeckSourceConfig(api_key="hd_test_key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.HOOKDECK
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Hookdeck"
+ assert config.label == "Hookdeck"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert not config.unreleasedSource
+ assert config.iconPath == "/static/services/hookdeck.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/hookdeck"
+ assert len(config.fields) == 1
+
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ def test_non_retryable_errors_match_the_error_the_api_raises(self) -> None:
+ observed = "401 Client Error: Unauthorized for url: https://api.hookdeck.com/2025-07-01/events?limit=250"
+
+ assert any(key in observed for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas_lists_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("name", INCREMENTAL_ENDPOINTS)
+ def test_incremental_endpoints_merge_with_a_lookback(self, name: str) -> None:
+ schema = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}[name]
+
+ assert schema.supports_incremental is True
+ # Hookdeck restates rows as retries land, so a re-read window is merged, never appended.
+ assert schema.supports_append is False
+ assert schema.default_incremental_lookback_seconds == 24 * 60 * 60
+ assert {f["field"] for f in schema.incremental_fields} == {
+ f["field"] for f in HOOKDECK_ENDPOINTS[name].incremental_fields
+ }
+
+ @pytest.mark.parametrize("name", FULL_REFRESH_ENDPOINTS)
+ def test_full_refresh_endpoints_advertise_no_cursor(self, name: str) -> None:
+ schema = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}[name]
+
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filters_by_name(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["events", "attempts"])
+
+ assert {s.name for s in schemas} == {"events", "attempts"}
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "probe_result, schema_name, expected",
+ [
+ ((True, 200), None, (True, None)),
+ ((False, 401), None, (False, "Invalid Hookdeck API key")),
+ # A 403 at source-create is a per-resource restriction, not a bad key.
+ ((False, 403), None, (True, None)),
+ ((False, 403), "events", (False, "Your Hookdeck API key can't access this resource")),
+ ((False, None), None, (False, "Could not connect to the Hookdeck API")),
+ ((False, 500), None, (False, "Could not connect to the Hookdeck API")),
+ ],
+ )
+ @mock.patch(f"{SOURCE_MODULE}.validate_hookdeck_credentials")
+ def test_validate_credentials(self, mock_validate, probe_result, schema_name, expected) -> None:
+ mock_validate.return_value = probe_result
+
+ assert self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name) == expected
+ mock_validate.assert_called_once_with("hd_test_key", "2025-07-01")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is HookdeckResumeConfig
+
+ @mock.patch(f"{SOURCE_MODULE}.hookdeck_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_hookdeck_source) -> None:
+ inputs = _make_inputs(
+ schema_name="issues",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00.000Z",
+ incremental_field="last_seen_at",
+ )
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_hookdeck_source.call_args.kwargs
+ assert kwargs["api_key"] == "hd_test_key"
+ assert kwargs["endpoint"] == "issues"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00.000Z"
+ assert kwargs["incremental_field"] == "last_seen_at"
+
+ @pytest.mark.parametrize("pinned, expected", [(None, "2025-07-01"), ("2025-01-01", "2025-01-01")])
+ @mock.patch(f"{SOURCE_MODULE}.hookdeck_source")
+ def test_source_for_pipeline_resolves_the_api_version(self, mock_hookdeck_source, pinned, expected) -> None:
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), _make_inputs(api_version=pinned))
+
+ assert mock_hookdeck_source.call_args.kwargs["api_version"] == expected
+
+ @mock.patch(f"{SOURCE_MODULE}.hookdeck_source")
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, mock_hookdeck_source) -> None:
+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value="2026-01-01")
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_hookdeck_source.call_args.kwargs["db_incremental_field_last_value"] is None