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 Calendly webhook ingestion (#77463)

Tom Owers2f5dfa90a339
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 df0d50106cd8..1c81b247bae0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -126,7 +126,7 @@ the row lists both.
| buttondown | HTTP | requests + `rest_source.RESTClient` | ✅ |
| buzzsprout | HTTP | requests | ✅ |
| cal_com | HTTP | requests | ✅ |
-| calendly | HTTP | requests | ✅ |
+| calendly | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| callrail | HTTP | requests | ✅ |
| campaign_monitor | HTTP | requests | ✅ |
| campayn | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/calendly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/calendly.py
index 94fd0ca5e3d5..06d83e2d3c92 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/calendly.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/calendly.py
@@ -1,12 +1,27 @@
+import secrets
import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
+from urllib.parse import quote, urlencode, urlsplit
+import orjson
+import pyarrow as pa
+from asgiref.sync import async_to_sync
+from requests import Session
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.settings import (
CALENDLY_ENDPOINTS,
+ CALENDLY_WEBHOOK_EVENTS,
+ WEBHOOK_SCHEMA_NAMES,
CalendlyEndpointConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
@@ -18,11 +33,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
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.common.webhook_s3 import WebhookSourceManager
CALENDLY_BASE_URL = "https://api.calendly.com"
PAGE_SIZE = 100
REQUEST_TIMEOUT = 60
+# Calendly webhook subscriptions are scoped to an organization or a single user. Every table this
+# source syncs is read with the `organization` scope param, so the subscription matches it.
+CALENDLY_WEBHOOK_SCOPE = "organization"
+
CALENDLY_API_VERSION_V1 = "v1"
CALENDLY_API_VERSION_V2 = "v2"
SUPPORTED_API_VERSIONS = (CALENDLY_API_VERSION_V1, CALENDLY_API_VERSION_V2)
@@ -113,6 +133,7 @@ def calendly_source(
api_version: str = CALENDLY_API_VERSION_V1,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
+ webhook_source_manager: Optional[WebhookSourceManager] = None,
) -> SourceResponse:
config = CALENDLY_ENDPOINTS[endpoint]
base_url = _base_url_for_version(api_version)
@@ -169,9 +190,18 @@ def calendly_source(
initial_paginator_state=initial_paginator_state,
)
+ webhook_enabled = False
+ if webhook_source_manager is not None and endpoint in WEBHOOK_SCHEMA_NAMES:
+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=False)
+
+ def items() -> Any:
+ if webhook_enabled and webhook_source_manager is not None:
+ return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)
+ return get_rows()
+
return SourceResponse(
name=endpoint,
- items=get_rows,
+ items=items,
primary_keys=["uri"],
partition_count=1,
partition_size=1,
@@ -180,3 +210,225 @@ def calendly_source(
partition_keys=[config.partition_key] if config.partition_key else None,
sort_mode="asc",
)
+
+
+def _parse_datetime(value: Any) -> Optional[datetime]:
+ """Coerce a Calendly RFC 3339 timestamp to an aware UTC datetime, or None when unusable."""
+ if isinstance(value, datetime):
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ if not isinstance(value, str):
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
+
+
+def _maybe_json(value: Any) -> Any:
+ """The buffering layer may hand nested structures back as JSON strings."""
+ if isinstance(value, str | bytes):
+ try:
+ return orjson.loads(value)
+ except orjson.JSONDecodeError:
+ return None
+ return value
+
+
+def _webhook_table_transformer(table: pa.Table) -> pa.Table:
+ """Reshape Calendly invitee deliveries into rows matching the polled `scheduled_events` table.
+
+ A delivery is the envelope `{"event", "created_at", "created_by", "payload": {<invitee>}}`, and
+ the invitee embeds the whole scheduled event under `payload.scheduled_event` using the same
+ field names `GET /scheduled_events` returns. We lift that object out and keep only the newest
+ version per `uri` in the batch: delta merge dedupes across syncs, so a batch carrying
+ `invitee.created` then `invitee.canceled` for one meeting must collapse to the latest row here.
+ """
+ if "payload" not in table.column_names:
+ return table_from_py_list([])
+
+ payloads = table.column("payload").to_pylist()
+ if "created_at" in table.column_names:
+ event_times = table.column("created_at").to_pylist()
+ else:
+ event_times = [None] * len(payloads)
+
+ latest_by_uri: dict[Any, tuple[Optional[datetime], dict[str, Any]]] = {}
+ for payload, event_time in zip(payloads, event_times):
+ payload = _maybe_json(payload)
+ if not isinstance(payload, dict):
+ continue
+ scheduled_event = _maybe_json(payload.get("scheduled_event"))
+ if not isinstance(scheduled_event, dict) or scheduled_event.get("uri") is None:
+ continue
+
+ # The envelope timestamp is when Calendly emitted the event, which orders two deliveries
+ # for one meeting even when the nested object's own `updated_at` is stale or absent.
+ occurred_at = _parse_datetime(event_time) or _parse_datetime(scheduled_event.get("updated_at"))
+ existing = latest_by_uri.get(scheduled_event["uri"])
+ # Later rows win ties so batch arrival order breaks equal or missing timestamps.
+ if existing is None or existing[0] is None or (occurred_at is not None and occurred_at >= existing[0]):
+ latest_by_uri[scheduled_event["uri"]] = (occurred_at, scheduled_event)
+
+ return table_from_py_list([row for _, row in latest_by_uri.values()])
+
+
+class CalendlyUntrustedURLError(Exception):
+ pass
+
+
+def _assert_calendly_origin(url: str, base_url: str) -> None:
+ """Reject a paginated webhook-management URL that points off the Calendly API origin.
+
+ `pagination.next_page` is response-controlled and the webhook-management session sends the
+ access token on every request, so a poisoned next link (off-host, downgraded to http, or on a
+ non-default port, which netloc carries) would otherwise exfiltrate the token. Redirects are
+ separately refused by the no-redirect session `_webhook_session` builds.
+ """
+ split = urlsplit(url)
+ if not (split.scheme == "https" and split.netloc == urlsplit(base_url).netloc):
+ raise CalendlyUntrustedURLError(f"Refusing to follow a Calendly URL outside {base_url}")
+
+
+def _webhook_session(token: str) -> Session:
+ return make_tracked_session(
+ headers=_get_headers(token),
+ redact_values=(token,),
+ # Subscription responses carry the signing key, so keep the raw bodies out of HTTP sample
+ # capture even when an operator enables it; no-redirect pins the credentialed request to
+ # the origin it validated.
+ capture=False,
+ allow_redirects=False,
+ )
+
+
+def _list_webhook_subscriptions(session: Session, base_url: str, organization: str) -> Iterator[dict[str, Any]]:
+ query = urlencode({"organization": organization, "scope": CALENDLY_WEBHOOK_SCOPE, "count": PAGE_SIZE})
+ next_url: Optional[str] = f"{base_url}/webhook_subscriptions?{query}"
+ while next_url:
+ _assert_calendly_origin(next_url, base_url)
+ response = session.get(next_url, timeout=REQUEST_TIMEOUT)
+ response.raise_for_status()
+ body = response.json()
+ yield from (item for item in body.get("collection") or [] if isinstance(item, dict))
+ next_url = (body.get("pagination") or {}).get("next_page")
+
+
+def _subscriptions_matching(session: Session, base_url: str, organization: str, webhook_url: str) -> list[dict]:
+ return [
+ item
+ for item in _list_webhook_subscriptions(session, base_url, organization)
+ if item.get("callback_url") == webhook_url
+ ]
+
+
+def _subscription_uuid(subscription: dict[str, Any]) -> Optional[str]:
+ """Take the trailing id off a subscription URI so we build the delete URL ourselves.
+
+ The response-supplied `uri` never becomes a request target; only this opaque segment does.
+ """
+ uri = subscription.get("uri")
+ if not isinstance(uri, str):
+ return None
+ segment = uri.rstrip("/").rsplit("/", 1)[-1]
+ return segment or None
+
+
+def _delete_subscriptions(session: Session, base_url: str, subscriptions: list[dict[str, Any]]) -> list[str]:
+ errors: list[str] = []
+ for subscription in subscriptions:
+ uuid = _subscription_uuid(subscription)
+ if uuid is None:
+ errors.append(f"subscription {subscription.get('uri')}: could not read its id")
+ continue
+ response = session.delete(f"{base_url}/webhook_subscriptions/{quote(uuid, safe='')}", timeout=REQUEST_TIMEOUT)
+ if response.status_code not in (200, 204):
+ errors.append(f"subscription {uuid}: HTTP {response.status_code}")
+ return errors
+
+
+def create_webhook(token: str, webhook_url: str, api_version: str = CALENDLY_API_VERSION_V2) -> WebhookCreationResult:
+ """Register an organization-scoped webhook subscription pointing at `webhook_url`.
+
+ We generate the signing key rather than letting Calendly pick one, and drop any subscription
+ already pointing at this URL first: Calendly rejects a duplicate callback URL and never returns
+ an existing subscription's signing key, so recreating is the only way to end up holding a key
+ we can verify deliveries with.
+ """
+ base_url = _base_url_for_version(api_version)
+ signing_key = secrets.token_hex(32)
+
+ try:
+ session = _webhook_session(token)
+ organization = get_current_organization(token, base_url)
+
+ _delete_subscriptions(session, base_url, _subscriptions_matching(session, base_url, organization, webhook_url))
+
+ response = session.post(
+ f"{base_url}/webhook_subscriptions",
+ json={
+ "url": webhook_url,
+ "events": list(CALENDLY_WEBHOOK_EVENTS),
+ "organization": organization,
+ "scope": CALENDLY_WEBHOOK_SCOPE,
+ "signing_key": signing_key,
+ },
+ timeout=REQUEST_TIMEOUT,
+ )
+ if response.status_code not in (200, 201):
+ detail = "Webhooks need a Standard plan or higher, and organization-wide subscriptions need an admin or owner token."
+ return WebhookCreationResult(
+ success=False,
+ error=(
+ f"Calendly rejected the webhook subscription (HTTP {response.status_code}). {detail} "
+ "Please create it manually below."
+ ),
+ )
+
+ # Calendly echoes the key back; prefer its value so a server-side rewrite can't leave us
+ # verifying against a key it never stored.
+ returned = ((response.json() or {}).get("resource") or {}).get("signing_key")
+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": returned or signing_key})
+ except Exception as e:
+ return WebhookCreationResult(
+ success=False,
+ error=f"Failed to create the Calendly webhook subscription: {e}. Please create it manually below.",
+ )
+
+
+def get_external_webhook_info(
+ token: str, webhook_url: str, api_version: str = CALENDLY_API_VERSION_V2
+) -> ExternalWebhookInfo:
+ base_url = _base_url_for_version(api_version)
+ try:
+ session = _webhook_session(token)
+ organization = get_current_organization(token, base_url)
+ matching = _subscriptions_matching(session, base_url, organization, webhook_url)
+ if not matching:
+ return ExternalWebhookInfo(exists=False)
+
+ subscription = matching[0]
+ return ExternalWebhookInfo(
+ exists=True,
+ url=subscription.get("callback_url"),
+ enabled_events=subscription.get("events"),
+ status=subscription.get("state"),
+ created_at=subscription.get("created_at"),
+ )
+ except Exception as e:
+ return ExternalWebhookInfo(exists=False, error=str(e))
+
+
+def delete_webhook(token: str, webhook_url: str, api_version: str = CALENDLY_API_VERSION_V2) -> WebhookDeletionResult:
+ base_url = _base_url_for_version(api_version)
+ try:
+ session = _webhook_session(token)
+ organization = get_current_organization(token, base_url)
+ errors = _delete_subscriptions(
+ session, base_url, _subscriptions_matching(session, base_url, organization, webhook_url)
+ )
+ if errors:
+ return WebhookDeletionResult(success=False, error="; ".join(errors))
+ return WebhookDeletionResult(success=True)
+ except Exception as e:
+ return WebhookDeletionResult(success=False, error=str(e))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/settings.py
index 4623eb556721..2dc13df4228b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/settings.py
@@ -62,3 +62,17 @@ ENDPOINTS = tuple(CALENDLY_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in CALENDLY_ENDPOINTS.items()
}
+
+# Calendly only emits webhooks for invitee lifecycle and routing form submissions. The invitee
+# payloads embed the whole `scheduled_event` object under the same field names the REST list
+# endpoint returns, so those deliveries can merge straight into `scheduled_events`. Nothing else
+# we sync has a matching event: there is no event type for event types, groups or memberships,
+# and `routing_form_submission.created` carries a submission rather than the form we sync.
+CALENDLY_WEBHOOK_EVENTS = ("invitee.created", "invitee.canceled")
+
+# Key the hog template routes on, not a Calendly event name: both subscribed events map to the
+# one table, so the template routes on the resource it found in the payload rather than on
+# `body.event`.
+WEBHOOK_RESOURCE_MAP: dict[str, str] = {"scheduled_events": "scheduled_event"}
+
+WEBHOOK_SCHEMA_NAMES = tuple(WEBHOOK_RESOURCE_MAP)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/source.py
index ccf3c6f924d2..e951ce7d4663 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/source.py
@@ -1,4 +1,4 @@
-from typing import Optional, cast
+from typing import TYPE_CHECKING, Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
@@ -15,16 +15,26 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.c
SUPPORTED_API_VERSIONS,
CalendlyResumeConfig,
calendly_source,
+ create_webhook as create_calendly_webhook,
+ delete_webhook as delete_calendly_webhook,
+ get_external_webhook_info as get_calendly_webhook_info,
validate_credentials as validate_calendly_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.settings import (
+ CALENDLY_WEBHOOK_EVENTS,
ENDPOINTS,
INCREMENTAL_FIELDS,
+ WEBHOOK_RESOURCE_MAP,
+ WEBHOOK_SCHEMA_NAMES,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
FieldType,
ResumableSource,
VersionDeprecation,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
@@ -36,14 +46,21 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
build_endpoint_schemas,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.calendly import (
CalendlySourceConfig,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+if TYPE_CHECKING:
+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
@SourceRegistry.register
-class CalendlySource(ResumableSource[CalendlySourceConfig, CalendlyResumeConfig]):
+class CalendlySource(
+ ResumableSource[CalendlySourceConfig, CalendlyResumeConfig],
+ WebhookSource[CalendlySourceConfig],
+):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
api_docs_url = "https://developer.calendly.com/"
@@ -59,6 +76,16 @@ class CalendlySource(ResumableSource[CalendlySourceConfig, CalendlyResumeConfig]
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CALENDLY
+ @property
+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.webhook_template import template
+
+ return template
+
+ @property
+ def webhook_resource_map(self) -> dict[str, str]:
+ return WEBHOOK_RESOURCE_MAP
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -84,6 +111,37 @@ You can create a personal access token in Calendly under **Integrations → API
),
],
),
+ webhookSetupCaption="""PostHog registers an organization-wide webhook subscription with your personal access token, using a generated signing key to verify every delivery. Webhooks need a Calendly Standard plan or higher, and an organization-wide subscription needs an admin or owner token.
+
+**Manual setup** (only needed if automatic registration failed):
+
+Calendly has no webhook screen in its dashboard, so subscriptions are created through its API. Get your organization URI from `GET https://api.calendly.com/users/me`, pick a random signing key, then run:
+
+```
+curl -X POST https://api.calendly.com/webhook_subscriptions \\
+ -H "Authorization: Bearer YOUR_TOKEN" \\
+ -H "Content-Type: application/json" \\
+ -d '{"url": "THE_WEBHOOK_URL_BELOW", "events": ["invitee.created", "invitee.canceled"], "organization": "YOUR_ORGANIZATION_URI", "scope": "organization", "signing_key": "YOUR_SIGNING_KEY"}'
+```
+
+Paste the same signing key into the field below so PostHog can verify deliveries.""",
+ webhookFields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="signing_secret",
+ label="Signing key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ caption=(
+ "The signing key set on the Calendly webhook subscription. PostHog uses it to "
+ "verify the Calendly-Webhook-Signature header on every delivery."
+ ),
+ secret=True,
+ ),
+ ],
+ ),
)
def get_canonical_descriptions(self) -> CanonicalDescriptions:
@@ -102,7 +160,7 @@ You can create a personal access token in Calendly under **Integrations → API
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, supports_webhooks=WEBHOOK_SCHEMA_NAMES)
def validate_credentials(
self,
@@ -125,6 +183,33 @@ You can create a personal access token in Calendly under **Integrations → API
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CalendlyResumeConfig]:
return ResumableSourceManager[CalendlyResumeConfig](inputs, CalendlyResumeConfig)
+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
+ return WebhookSourceManager(inputs, inputs.logger)
+
+ def create_webhook(
+ self, config: CalendlySourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> WebhookCreationResult:
+ return create_calendly_webhook(config.personal_access_token, webhook_url, self.resolve_api_version(api_version))
+
+ def get_desired_webhook_events(
+ self, config: CalendlySourceConfig, eligible_schema_names: list[str]
+ ) -> list[str] | None:
+ # Fixed regardless of the selected schemas: both events feed the one webhook-capable table,
+ # and Calendly subscriptions are immutable, so there is nothing to reconcile afterwards.
+ return list(CALENDLY_WEBHOOK_EVENTS)
+
+ def get_external_webhook_info(
+ self, config: CalendlySourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> ExternalWebhookInfo | None:
+ return get_calendly_webhook_info(
+ config.personal_access_token, webhook_url, self.resolve_api_version(api_version)
+ )
+
+ def delete_webhook(
+ self, config: CalendlySourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> WebhookDeletionResult:
+ return delete_calendly_webhook(config.personal_access_token, webhook_url, self.resolve_api_version(api_version))
+
def source_for_pipeline(
self,
config: CalendlySourceConfig,
@@ -137,6 +222,7 @@ You can create a personal access token in Calendly under **Integrations → API
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ webhook_source_manager=self.get_webhook_source_manager(inputs),
api_version=self.resolve_api_version(inputs.api_version),
should_use_incremental_field=inputs.should_use_incremental_field,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly.py
index dd703f66eefe..c295827ea584 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly.py
@@ -8,16 +8,24 @@ from unittest import mock
from parameterized import parameterized
from requests import HTTPError, Response
+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.calendly.calendly import (
CALENDLY_BASE_URL,
SUPPORTED_API_VERSIONS,
CalendlyResumeConfig,
_format_datetime,
+ _webhook_table_transformer,
calendly_source,
+ create_webhook,
+ delete_webhook,
get_current_organization,
+ get_external_webhook_info,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.settings import (
+ CALENDLY_WEBHOOK_EVENTS,
+ ENDPOINTS,
+)
# RESTClient builds its session via make_tracked_session in the rest_client module.
CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
@@ -320,3 +328,336 @@ class TestCalendlySource:
assert response.sort_mode == "asc"
assert response.partition_keys == ["created_at"]
assert response.partition_mode == "datetime"
+
+
+WEBHOOK_URL = "https://webhooks.us.posthog.com/public/webhooks/dwh/hog-fn-1"
+
+
+def _scheduled_event(uri: str = "https://api.calendly.com/scheduled_events/EVENT", **overrides: Any) -> dict[str, Any]:
+ return {
+ "uri": uri,
+ "name": "30 Minute Meeting",
+ "status": "active",
+ "start_time": "2026-07-10T15:00:00.000000Z",
+ "end_time": "2026-07-10T15:30:00.000000Z",
+ "created_at": "2026-07-02T12:00:00.000000Z",
+ "updated_at": "2026-07-02T12:00:00.000000Z",
+ **overrides,
+ }
+
+
+def _delivery(scheduled_event: Optional[dict[str, Any]], created_at: str = "2026-07-02T12:00:00.000000Z") -> dict:
+ payload: dict[str, Any] = {"uri": "https://api.calendly.com/scheduled_events/EVENT/invitees/INVITEE"}
+ if scheduled_event is not None:
+ payload["scheduled_event"] = scheduled_event
+ return {"event": "invitee.created", "created_at": created_at, "payload": payload}
+
+
+def _subscription(
+ uuid: str = "sub-1",
+ callback_url: str = WEBHOOK_URL,
+ **overrides: Any,
+) -> dict[str, Any]:
+ return {
+ "uri": f"https://api.calendly.com/webhook_subscriptions/{uuid}",
+ "callback_url": callback_url,
+ "events": list(CALENDLY_WEBHOOK_EVENTS),
+ "state": "active",
+ "scope": "organization",
+ "created_at": "2026-07-01T00:00:00.000000Z",
+ **overrides,
+ }
+
+
+def _subscriptions_response(items: list[dict[str, Any]], next_page: Optional[str] = None) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp.url = f"{CALENDLY_BASE_URL}/webhook_subscriptions"
+ resp._content = json.dumps({"collection": items, "pagination": {"next_page": next_page}}).encode()
+ return resp
+
+
+def _wire_webhook_session(
+ mock_session: mock.MagicMock,
+ subscription_pages: Optional[list[Response]] = None,
+) -> mock.MagicMock:
+ """Serve `/users/me` and the subscription listing off the one patched session factory."""
+ session = mock_session.return_value
+ pages = list(subscription_pages if subscription_pages is not None else [_subscriptions_response([])])
+
+ def _get(url: str, **_kwargs: Any) -> Response:
+ if url.endswith("/users/me"):
+ return _users_me_response()
+ return pages.pop(0)
+
+ session.get.side_effect = _get
+ return session
+
+
+class TestWebhookTableTransformer:
+ def test_lifts_the_nested_scheduled_event_into_the_polled_row_shape(self) -> None:
+ table = table_from_py_list([_delivery(_scheduled_event())])
+
+ rows = _webhook_table_transformer(table).to_pylist()
+
+ assert rows == [_scheduled_event()]
+
+ def test_keeps_only_the_latest_delivery_per_scheduled_event(self) -> None:
+ # A batch can carry invitee.created then invitee.canceled for one meeting. Delta merge only
+ # dedupes across syncs, so the batch itself must collapse to the canceled row.
+ table = table_from_py_list(
+ [
+ _delivery(_scheduled_event(status="active"), created_at="2026-07-02T12:00:00.000000Z"),
+ _delivery(_scheduled_event(status="canceled"), created_at="2026-07-03T09:00:00.000000Z"),
+ ]
+ )
+
+ rows = _webhook_table_transformer(table).to_pylist()
+
+ assert len(rows) == 1
+ assert rows[0]["status"] == "canceled"
+
+ def test_out_of_order_deliveries_still_resolve_to_the_newest(self) -> None:
+ table = table_from_py_list(
+ [
+ _delivery(_scheduled_event(status="canceled"), created_at="2026-07-03T09:00:00.000000Z"),
+ _delivery(_scheduled_event(status="active"), created_at="2026-07-02T12:00:00.000000Z"),
+ ]
+ )
+
+ rows = _webhook_table_transformer(table).to_pylist()
+
+ assert [row["status"] for row in rows] == ["canceled"]
+
+ def test_distinct_meetings_are_all_kept(self) -> None:
+ table = table_from_py_list(
+ [
+ _delivery(_scheduled_event(uri="https://api.calendly.com/scheduled_events/A")),
+ _delivery(_scheduled_event(uri="https://api.calendly.com/scheduled_events/B")),
+ ]
+ )
+
+ rows = _webhook_table_transformer(table).to_pylist()
+
+ assert {row["uri"] for row in rows} == {
+ "https://api.calendly.com/scheduled_events/A",
+ "https://api.calendly.com/scheduled_events/B",
+ }
+
+ @parameterized.expand(
+ [
+ ("no_scheduled_event", _delivery(None)),
+ ("scheduled_event_without_uri", _delivery({"name": "30 Minute Meeting"})),
+ ]
+ )
+ def test_deliveries_without_a_usable_scheduled_event_are_dropped(self, _name: str, delivery: dict) -> None:
+ assert _webhook_table_transformer(table_from_py_list([delivery])).num_rows == 0
+
+ def test_empty_batch_is_dropped_rather_than_passed_through(self) -> None:
+ assert _webhook_table_transformer(table_from_py_list([])).num_rows == 0
+
+
+class TestCreateWebhook:
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ def test_creates_an_organization_scoped_subscription_and_keeps_the_signing_key(
+ self, mock_session: mock.MagicMock
+ ) -> None:
+ session = _wire_webhook_session(mock_session)
+ created = Response()
+ created.status_code = 201
+ created._content = json.dumps({"resource": _subscription(signing_key="key-from-calendly")}).encode()
+ session.post.return_value = created
+
+ result = create_webhook("token", WEBHOOK_URL)
+
+ assert result.success is True
+ # Without the signing key on the hog function every delivery fails verification.
+ assert result.extra_inputs["signing_secret"] == "key-from-calendly"
+ body = session.post.call_args.kwargs["json"]
+ assert body["url"] == WEBHOOK_URL
+ assert body["scope"] == "organization"
+ assert body["organization"] == ORG_URI
+ assert body["events"] == list(CALENDLY_WEBHOOK_EVENTS)
+ assert body["signing_key"]
+
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ def test_falls_back_to_the_generated_key_when_the_response_omits_it(self, mock_session: mock.MagicMock) -> None:
+ session = _wire_webhook_session(mock_session)
+ created = Response()
+ created.status_code = 201
+ created._content = json.dumps({"resource": _subscription()}).encode()
+ session.post.return_value = created
+
+ result = create_webhook("token", WEBHOOK_URL)
+
+ assert result.success is True
+ assert result.extra_inputs["signing_secret"] == session.post.call_args.kwargs["json"]["signing_key"]
+
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ def test_replaces_an_existing_subscription_on_the_same_url(self, mock_session: mock.MagicMock) -> None:
+ # Calendly rejects a duplicate callback URL and never hands back an existing subscription's
+ # signing key, so the stale one has to go before we can register a key we hold.
+ session = _wire_webhook_session(mock_session, [_subscriptions_response([_subscription(uuid="old-sub")])])
+ session.delete.return_value = mock.MagicMock(status_code=204)
+ created = Response()
+ created.status_code = 201
+ created._content = json.dumps({"resource": _subscription()}).encode()
+ session.post.return_value = created
+
+ result = create_webhook("token", WEBHOOK_URL)
+
+ assert result.success is True
+ assert session.delete.call_args.args[0].endswith("/webhook_subscriptions/old-sub")
+
+ @parameterized.expand([("payment_required", 402), ("forbidden", 403), ("conflict", 409)])
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ def test_rejection_surfaces_an_actionable_error(
+ self, _name: str, status_code: int, mock_session: mock.MagicMock
+ ) -> None:
+ session = _wire_webhook_session(mock_session)
+ session.post.return_value = mock.MagicMock(status_code=status_code)
+
+ result = create_webhook("token", WEBHOOK_URL)
+
+ assert result.success is False
+ assert result.error is not None
+ assert "Standard plan" in result.error
+
+ @mock.patch(CALENDLY_SESSION_PATCH, side_effect=Exception("network down"))
+ def test_network_failure_is_reported_rather_than_raised(self, _mock_session: mock.MagicMock) -> None:
+ result = create_webhook("token", WEBHOOK_URL)
+
+ assert result.success is False
+ assert result.error is not None and "network down" in result.error
+
+
+class TestDeleteWebhook:
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ def test_deletes_only_subscriptions_pointing_at_our_url(self, mock_session: mock.MagicMock) -> None:
+ session = _wire_webhook_session(
+ mock_session,
+ [
+ _subscriptions_response(
+ [
+ _subscription(uuid="ours"),
+ _subscription(uuid="theirs", callback_url="https://elsewhere.example.com/hook"),
+ ]
+ )
+ ],
+ )
+ session.delete.return_value = mock.MagicMock(status_code=204)
+
+ result = delete_webhook("token", WEBHOOK_URL)
+
+ assert result.success is True
+ assert session.delete.call_count == 1
+ assert session.delete.call_args.args[0].endswith("/webhook_subscriptions/ours")
+
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ def test_walks_every_page_of_subscriptions(self, mock_session: mock.MagicMock) -> None:
+ next_page = f"{CALENDLY_BASE_URL}/webhook_subscriptions?page_token=abc"
+ session = _wire_webhook_session(
+ mock_session,
+ [
+ _subscriptions_response([_subscription(uuid="page-1", callback_url="https://other/hook")], next_page),
+ _subscriptions_response([_subscription(uuid="page-2")]),
+ ],
+ )
+ session.delete.return_value = mock.MagicMock(status_code=204)
+
+ result = delete_webhook("token", WEBHOOK_URL)
+
+ assert result.success is True
+ assert session.delete.call_args.args[0].endswith("/webhook_subscriptions/page-2")
+
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ def test_failed_delete_is_reported(self, mock_session: mock.MagicMock) -> None:
+ session = _wire_webhook_session(mock_session, [_subscriptions_response([_subscription(uuid="ours")])])
+ session.delete.return_value = mock.MagicMock(status_code=500)
+
+ result = delete_webhook("token", WEBHOOK_URL)
+
+ assert result.success is False
+ assert result.error is not None and "ours" in result.error
+
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ def test_off_origin_next_page_is_refused(self, mock_session: mock.MagicMock) -> None:
+ # `pagination.next_page` is response-controlled and the session carries the access token.
+ _wire_webhook_session(
+ mock_session,
+ [_subscriptions_response([], next_page="https://evil.example.com/webhook_subscriptions")],
+ )
+
+ result = delete_webhook("token", WEBHOOK_URL)
+
+ assert result.success is False
+ assert result.error is not None and "Refusing to follow" in result.error
+
+
+class TestGetExternalWebhookInfo:
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ def test_reports_the_registered_subscription(self, mock_session: mock.MagicMock) -> None:
+ _wire_webhook_session(mock_session, [_subscriptions_response([_subscription()])])
+
+ info = get_external_webhook_info("token", WEBHOOK_URL)
+
+ assert info.exists is True
+ assert info.url == WEBHOOK_URL
+ assert info.enabled_events == list(CALENDLY_WEBHOOK_EVENTS)
+ assert info.status == "active"
+
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ def test_reports_absence_when_nothing_points_at_our_url(self, mock_session: mock.MagicMock) -> None:
+ _wire_webhook_session(
+ mock_session, [_subscriptions_response([_subscription(callback_url="https://elsewhere/hook")])]
+ )
+
+ info = get_external_webhook_info("token", WEBHOOK_URL)
+
+ assert info.exists is False
+
+ @mock.patch(CALENDLY_SESSION_PATCH, side_effect=Exception("network down"))
+ def test_network_failure_is_reported_rather_than_raised(self, _mock_session: mock.MagicMock) -> None:
+ info = get_external_webhook_info("token", WEBHOOK_URL)
+
+ assert info.exists is False
+ assert info.error == "network down"
+
+
+class TestWebhookPipelineWiring:
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_webhook_items_replace_the_poll_once_the_schema_is_webhook_backed(
+ self, MockClientSession: mock.MagicMock, mock_calendly_session: mock.MagicMock
+ ) -> None:
+ mock_calendly_session.return_value.get.return_value = _users_me_response()
+ _wire(MockClientSession.return_value, [_response([{"uri": "polled"}])])
+ webhook_manager = mock.MagicMock()
+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)
+ webhook_manager.get_items.return_value = "webhook-items"
+
+ response = _source(_make_manager(), endpoint="scheduled_events", webhook_source_manager=webhook_manager)
+
+ assert response.items() == "webhook-items"
+ assert webhook_manager.get_items.call_args.kwargs["table_transformer"] is _webhook_table_transformer
+
+ @parameterized.expand([("webhook_disabled", "scheduled_events", False), ("non_webhook_table", "groups", True)])
+ @mock.patch(CALENDLY_SESSION_PATCH)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_poll_path_is_untouched(
+ self,
+ _name: str,
+ endpoint: str,
+ webhook_enabled: bool,
+ MockClientSession: mock.MagicMock,
+ mock_calendly_session: mock.MagicMock,
+ ) -> None:
+ mock_calendly_session.return_value.get.return_value = _users_me_response()
+ _wire(MockClientSession.return_value, [_response([{"uri": "polled"}])])
+ webhook_manager = mock.MagicMock()
+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=webhook_enabled)
+
+ response = _source(_make_manager(), endpoint=endpoint, webhook_source_manager=webhook_manager)
+
+ assert [row["uri"] for page in response.items() for row in page] == ["polled"]
+ webhook_manager.get_items.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly_source.py
index 1ea0bdb77449..f9f3f77278fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly_source.py
@@ -8,9 +8,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.c
CALENDLY_API_VERSION_V2,
CalendlyResumeConfig,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.settings import (
+ CALENDLY_WEBHOOK_EVENTS,
+ ENDPOINTS,
+ WEBHOOK_SCHEMA_NAMES,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.source import CalendlySource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.calendly import (
CalendlySourceConfig,
)
@@ -198,3 +203,103 @@ class TestCalendlySource:
self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
assert mock_calendly_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+
+WEBHOOK_URL = "https://webhooks.us.posthog.com/public/webhooks/dwh/hog-fn-1"
+WEBHOOK_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.calendly.source"
+
+
+class TestCalendlySourceWebhooks:
+ def setup_method(self):
+ self.source = CalendlySource()
+ self.team_id = 123
+ self.config = CalendlySourceConfig(personal_access_token="cal_test_token")
+
+ def test_only_scheduled_events_accepts_webhooks(self):
+ # Calendly's webhook events all describe invitee activity; only their payloads embed a
+ # scheduled event, and nothing it emits matches the other four tables.
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert {name for name, schema in schemas.items() if schema.supports_webhooks} == set(WEBHOOK_SCHEMA_NAMES)
+ # Every table still has a working list endpoint, so none of them is webhook-only.
+ assert all(not schema.webhook_only for schema in schemas.values())
+
+ def test_polling_metadata_is_unchanged_by_webhook_support(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["scheduled_events"].supports_incremental is True
+ assert schemas["scheduled_events"].supports_append is True
+ assert {f["field"] for f in schemas["scheduled_events"].incremental_fields} == {"start_time"}
+
+ def test_routing_key_matches_the_key_the_template_looks_up(self):
+ # The hog template reads a fixed key out of `schema_mapping`; if the map and the template
+ # drift apart, deliveries are acked and silently dropped.
+ template = self.source.webhook_template
+
+ assert self.source.webhook_resource_map == {"scheduled_events": "scheduled_event"}
+ assert self.source.webhook_mapping_key("scheduled_events") == "scheduled_event"
+ assert template is not None
+ assert "inputs.schema_mapping?.['scheduled_event']" in template.code
+
+ def test_webhook_template_verifies_the_calendly_signature_header(self):
+ template = self.source.webhook_template
+
+ assert template is not None
+ assert template.id == "template-warehouse-source-calendly"
+ assert "calendly-webhook-signature" in template.code
+ assert "produceToWarehouseWebhooks" in template.code
+
+ def test_webhook_fields_collect_the_signing_key(self):
+ config = self.source.get_source_config
+
+ assert config.webhookFields is not None
+ signing_key = [
+ f for f in config.webhookFields if isinstance(f, SourceFieldInputConfig) and f.name == "signing_secret"
+ ]
+ assert len(signing_key) == 1
+ assert signing_key[0].type == SourceFieldInputConfigType.PASSWORD
+ assert signing_key[0].secret is True
+
+ def test_desired_events_do_not_narrow_with_the_selected_schemas(self):
+ # Calendly subscriptions are immutable, so the event list must not depend on what the user
+ # happens to have selected when the webhook is registered.
+ assert self.source.get_desired_webhook_events(self.config, []) == list(CALENDLY_WEBHOOK_EVENTS)
+ assert self.source.get_desired_webhook_events(self.config, ["scheduled_events"]) == list(
+ CALENDLY_WEBHOOK_EVENTS
+ )
+
+ @pytest.mark.parametrize(
+ "method, patched, extra_kwargs",
+ [
+ ("create_webhook", "create_calendly_webhook", {}),
+ ("delete_webhook", "delete_calendly_webhook", {}),
+ ("get_external_webhook_info", "get_calendly_webhook_info", {}),
+ ],
+ )
+ def test_webhook_management_delegates_with_the_token(self, method, patched, extra_kwargs):
+ with mock.patch(f"{WEBHOOK_MODULE}.{patched}") as delegate:
+ getattr(self.source, method)(self.config, WEBHOOK_URL, self.team_id, **extra_kwargs)
+
+ delegate.assert_called_once_with("cal_test_token", WEBHOOK_URL, CALENDLY_API_VERSION_V2)
+
+ @pytest.mark.parametrize(
+ "pin, expected",
+ [
+ (CALENDLY_API_VERSION_V1, CALENDLY_API_VERSION_V1),
+ (None, CALENDLY_API_VERSION_V2),
+ ],
+ )
+ def test_webhook_management_runs_against_the_pinned_version(self, pin, expected):
+ with mock.patch(f"{WEBHOOK_MODULE}.create_calendly_webhook") as delegate:
+ self.source.create_webhook(self.config, WEBHOOK_URL, self.team_id, api_version=pin)
+
+ assert delegate.call_args.args[2] == expected
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.calendly.source.calendly_source")
+ def test_source_for_pipeline_passes_a_webhook_manager(self, mock_calendly_source):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), _make_inputs())
+
+ assert isinstance(
+ mock_calendly_source.call_args.kwargs["webhook_source_manager"],
+ WebhookSourceManager,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly_webhook_template.py
new file mode 100644
index 000000000000..60c2e521e10c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/tests/test_calendly_webhook_template.py
@@ -0,0 +1,187 @@
+import hmac
+import json
+import time
+import hashlib
+
+from parameterized import parameterized
+
+from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.calendly.webhook_template import template
+
+SOURCE_ID = "source_test_123"
+SIGNING_KEY = "cal_signing_key_test"
+SCHEMA_ID = "schema_scheduled_events"
+SCHEMA_MAPPING = {"scheduled_event": SCHEMA_ID}
+
+INVITEE_CREATED = {
+ "event": "invitee.created",
+ "created_at": "2026-07-02T12:00:00.000000Z",
+ "created_by": "https://api.calendly.com/users/AAAA",
+ "payload": {
+ "uri": "https://api.calendly.com/scheduled_events/EVENT/invitees/INVITEE",
+ "email": "[email protected]",
+ "name": "Jane Doe",
+ "status": "active",
+ "scheduled_event": {
+ "uri": "https://api.calendly.com/scheduled_events/EVENT",
+ "name": "30 Minute Meeting",
+ "status": "active",
+ "start_time": "2026-07-10T15:00:00.000000Z",
+ "end_time": "2026-07-10T15:30:00.000000Z",
+ "created_at": "2026-07-02T12:00:00.000000Z",
+ "updated_at": "2026-07-02T12:00:00.000000Z",
+ },
+ },
+}
+
+
+class TestCalendlyWarehouseWebhookTemplate(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 _signed_request(
+ self,
+ secret: str = SIGNING_KEY,
+ body: dict | None = None,
+ method: str = "POST",
+ timestamp: int | None = None,
+ ) -> dict:
+ payload = json.dumps(body if body is not None else INVITEE_CREATED)
+ ts = str(timestamp if timestamp is not None else int(time.time()))
+ signature = hmac.new(secret.encode(), f"{ts}.{payload}".encode(), hashlib.sha256).hexdigest()
+ return {
+ "request": {
+ "method": method,
+ "headers": {"calendly-webhook-signature": f"t={ts},v1={signature}"},
+ "body": json.loads(payload),
+ "stringBody": payload,
+ "query": {},
+ }
+ }
+
+ def _inputs(self, **overrides) -> dict:
+ return {
+ "signing_secret": SIGNING_KEY,
+ "bypass_signature_check": False,
+ "schema_mapping": SCHEMA_MAPPING,
+ "source_id": SOURCE_ID,
+ **overrides,
+ }
+
+ def test_valid_signed_delivery_is_routed_to_the_scheduled_events_schema(self):
+ globals = self._signed_request()
+
+ self.run_function(self._inputs(), globals=globals)
+
+ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(globals["request"]["body"], SCHEMA_ID)
+
+ def test_signature_signs_the_timestamp_and_body_not_the_body_alone(self):
+ payload = json.dumps(INVITEE_CREATED)
+ body_only = hmac.new(SIGNING_KEY.encode(), payload.encode(), hashlib.sha256).hexdigest()
+ globals = {
+ "request": {
+ "method": "POST",
+ "headers": {"calendly-webhook-signature": f"t={int(time.time())},v1={body_only}"},
+ "body": INVITEE_CREATED,
+ "stringBody": payload,
+ "query": {},
+ }
+ }
+
+ res = self.run_function(self._inputs(), globals=globals)
+
+ assert res.result == {"httpResponse": {"status": 400, "body": "Bad signature"}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_signature_from_another_key_is_rejected(self):
+ res = self.run_function(self._inputs(), globals=self._signed_request(secret="someone_elses_key"))
+
+ assert res.result == {"httpResponse": {"status": 400, "body": "Bad signature"}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_replayed_delivery_outside_the_tolerance_is_rejected(self):
+ globals = self._signed_request(timestamp=int(time.time()) - 400)
+
+ res = self.run_function(self._inputs(), globals=globals)
+
+ assert res.result == {"httpResponse": {"status": 400, "body": "Timestamp outside tolerance"}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("null", None),
+ ("empty_string", ""),
+ ]
+ )
+ def test_unconfigured_signing_key_rejects_instead_of_accepting_anything(self, _name, signing_secret):
+ res = self.run_function(
+ self._inputs(signing_secret=signing_secret), globals=self._signed_request(secret="anything")
+ )
+
+ assert res.result == {"httpResponse": {"status": 400, "body": "Signing secret not configured"}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("missing_header", {}, "Missing signature"),
+ ("no_recognised_parts", {"calendly-webhook-signature": "nonsense"}, "Could not parse signature"),
+ ("timestamp_only", {"calendly-webhook-signature": "t=12345"}, "Could not parse signature"),
+ ]
+ )
+ def test_malformed_signature_header_is_rejected(self, _name, headers, expected_body):
+ globals = {
+ "request": {
+ "method": "POST",
+ "headers": headers,
+ "body": INVITEE_CREATED,
+ "stringBody": json.dumps(INVITEE_CREATED),
+ "query": {},
+ }
+ }
+
+ res = self.run_function(self._inputs(), globals=globals)
+
+ assert res.result == {"httpResponse": {"status": 400, "body": expected_body}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_non_post_request_is_rejected(self):
+ res = self.run_function(self._inputs(), globals=self._signed_request(method="GET"))
+
+ assert res.result == {"httpResponse": {"status": 405, "body": "Method not allowed"}}
+
+ def test_delivery_without_a_scheduled_event_is_acked_and_dropped(self):
+ # A routing form submission is signed and valid, but carries no scheduled event, so it must
+ # not be written into the scheduled_events table.
+ body = {
+ "event": "routing_form_submission.created",
+ "created_at": "2026-07-02T12:00:00.000000Z",
+ "payload": {"uri": "https://api.calendly.com/routing_form_submissions/SUB", "routing_form": "form"},
+ }
+
+ res = self.run_function(self._inputs(), globals=self._signed_request(body=body))
+
+ assert res.result == {"httpResponse": {"status": 200, "body": "No scheduled event found, skipping"}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_delivery_is_dropped_when_scheduled_events_is_not_synced(self):
+ res = self.run_function(self._inputs(schema_mapping={}), globals=self._signed_request())
+
+ assert res.result == {
+ "httpResponse": {"status": 200, "body": "No schema mapping for scheduled events, skipping"}
+ }
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/webhook_template.py
new file mode 100644
index 000000000000..04e6d64beb56
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/calendly/webhook_template.py
@@ -0,0 +1,168 @@
+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+template: HogFunctionTemplateDC = HogFunctionTemplateDC(
+ status="alpha",
+ free=False,
+ type="warehouse_source_webhook",
+ id="template-warehouse-source-calendly",
+ name="Calendly warehouse source webhook",
+ description="Receive Calendly webhook events for data warehouse ingestion",
+ icon_url="/static/services/calendly.png",
+ category=["Data warehouse"],
+ code_language="hog",
+ code="""\
+if (request.method != 'POST') {
+ return {
+ 'httpResponse': {
+ 'status': 405,
+ 'body': 'Method not allowed'
+ }
+ }
+}
+
+if (not inputs.bypass_signature_check) {
+ if (empty(inputs.signing_secret)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Signing secret not configured',
+ }
+ }
+ }
+
+ let body := request.stringBody
+ let signatureHeader := request.headers['calendly-webhook-signature']
+
+ if (empty(signatureHeader)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Missing signature',
+ }
+ }
+ }
+
+ let headerParts := splitByString(',', signatureHeader)
+ let timestamp := null
+ let v1Signature := null
+
+ for (let _, part in headerParts) {
+ let trimmed := trim(part)
+ if (trimmed like 't=%') {
+ let tParts := splitByString('=', trimmed, 2)
+ if (length(tParts) = 2) {
+ timestamp := tParts[2]
+ }
+ }
+ if (trimmed like 'v1=%') {
+ let v1Parts := splitByString('=', trimmed, 2)
+ if (length(v1Parts) = 2) {
+ v1Signature := v1Parts[2]
+ }
+ }
+ }
+
+ if (empty(timestamp) or empty(v1Signature)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Could not parse signature',
+ }
+ }
+ }
+
+ let signedPayload := concat(timestamp, '.', body)
+ let computedSignature := sha256HmacChainHex([inputs.signing_secret, signedPayload])
+
+ if (computedSignature != v1Signature) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Bad signature',
+ }
+ }
+ }
+
+ let currentTime := toInt(toUnixTimestamp(now()))
+ let timestampDelta := currentTime - toInt(timestamp)
+ if (timestampDelta > 300 or timestampDelta < -300) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Timestamp outside tolerance',
+ }
+ }
+ }
+}
+
+// Every subscribed event is an invitee event whose payload embeds the scheduled event. Events
+// without one (a routing form submission, or an invitee payload missing it) are acked and
+// dropped rather than routed to a table they don't fit.
+let scheduledEvent := request.body.payload?.scheduled_event
+
+if (empty(scheduledEvent) or empty(scheduledEvent?.uri)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'No scheduled event found, skipping'
+ }
+ }
+}
+
+let schemaId := inputs.schema_mapping?.['scheduled_event']
+
+if (empty(schemaId)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'No schema mapping for scheduled events, skipping'
+ }
+ }
+}
+
+produceToWarehouseWebhooks(request.body, schemaId)""",
+ inputs_schema=[
+ {
+ "type": "string",
+ "key": "signing_secret",
+ "label": "Signing key",
+ "required": False,
+ "secret": True,
+ "hidden": False,
+ "description": (
+ "The webhook subscription's signing key. Used to verify the Calendly-Webhook-Signature "
+ "header (HMAC-SHA256 over the timestamp and the raw request body) so deliveries "
+ "provably come from Calendly."
+ ),
+ },
+ {
+ "type": "boolean",
+ "key": "bypass_signature_check",
+ "label": "Bypass signature check",
+ "description": (
+ "If set, the Calendly-Webhook-Signature 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 Calendly resource types to ExternalDataSchema IDs",
+ "required": True,
+ "secret": False,
+ "hidden": True,
+ },
+ {
+ "type": "string",
+ "key": "source_id",
+ "label": "Source ID",
+ "description": "The ExternalDataSource ID this webhook is associated with",
+ "required": True,
+ "secret": False,
+ "hidden": True,
+ },
+ ],
+)