:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse): add WorkOS webhook sync (#87806)
ella-c29a3b18684e1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex fe3bd6597670..4bc5706d90d5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -745,7 +745,7 @@ the row lists both.| workable | HTTP | requests | ✅ || workday | HTTP | requests + `rest_source.RESTClient` | ✅ || workiz | HTTP | requests + `rest_source.RESTClient` | ✅ |-| workos | HTTP | requests + `rest_source.RESTClient` | ✅ |+| workos | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || world_bank | HTTP | requests + `rest_source.RESTClient` | ✅ || wrike | HTTP | requests | ✅ || writesonic | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/canonical_descriptions.pyindex d201b2cd4062..eae9343e7b90 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/canonical_descriptions.py@@ -18,8 +18,17 @@ _COMMON_COLUMNS = {}-def _columns(**overrides: str) -> dict[str, str]:- return {**_COMMON_COLUMNS, **overrides}+# PostHog adds these columns to the tables that can sync by webhook, because a webhook delete+# merges on `id` and can only mark a row, never remove it. WorkOS itself does not send them.+# The tables that get them are the keys of WEBHOOK_EVENTS_BY_SCHEMA in `settings.py`.+_TOMBSTONE_COLUMNS = {+ "workos_deleted": "Whether WorkOS reported this record as deleted. Added by PostHog, not a WorkOS field.",+ "workos_deleted_at": "Time at which WorkOS reported the delete. Null while the record still exists.",+}+++def _columns(*, webhook_synced: bool = False, **overrides: str) -> dict[str, str]:+ return {**_COMMON_COLUMNS, **(_TOMBSTONE_COLUMNS if webhook_synced else {}), **overrides}CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {@@ -27,6 +36,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"description": "An organization (a tenant/company) in WorkOS that users and connections belong to.","docs_url": "https://workos.com/docs/reference/organization","columns": _columns(+ webhook_synced=True,name="The organization's display name.",domains="Verified domains associated with the organization.",allow_profiles_outside_organization="Whether users outside the organization's domains may sign in.",@@ -36,6 +46,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"description": "A user managed by WorkOS User Management (AuthKit).","docs_url": "https://workos.com/docs/reference/user-management/user","columns": _columns(+ webhook_synced=True,email="The user's email address.",first_name="The user's first name.",last_name="The user's last name.",@@ -69,6 +80,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"description": "A user synced from an organization's directory via Directory Sync.","docs_url": "https://workos.com/docs/reference/directory-sync/directory-user","columns": _columns(+ webhook_synced=True,directory_id="ID of the directory the user was synced from.",organization_id="ID of the organization the directory belongs to.",email="The user's primary email address.",@@ -83,6 +95,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"description": "A group synced from an organization's directory via Directory Sync.","docs_url": "https://workos.com/docs/reference/directory-sync/directory-group","columns": _columns(+ webhook_synced=True,directory_id="ID of the directory the group was synced from.",organization_id="ID of the organization the directory belongs to.",name="The group's name.",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/settings.pyindex 79804011edd4..e128e3524cd7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/settings.py@@ -12,8 +12,9 @@ class WorkOSEndpointConfig:# WorkOS list endpoints share one cursor-paginated envelope# ({"data": [...], "list_metadata": {"before": ..., "after": ...}}) and expose no-# server-side timestamp filter, so every endpoint is full-refresh only. Incremental+# server-side timestamp filter, so a polled sync is always a full refresh. Incremental# sync on WorkOS is only possible through the /events API, which is not modeled here.+# WEBHOOK_EVENTS_BY_SCHEMA below lists the tables that leave polling behind.WORKOS_ENDPOINTS: dict[str, WorkOSEndpointConfig] = {"organizations": WorkOSEndpointConfig(name="organizations", path="/organizations"),"users": WorkOSEndpointConfig(name="users", path="/user_management/users"),@@ -24,3 +25,18 @@ WORKOS_ENDPOINTS: dict[str, WorkOSEndpointConfig] = {}ENDPOINTS = tuple(WORKOS_ENDPOINTS.keys())++# Webhook sync replaces polling, so a table only qualifies when its events cover the whole+# create, update, and delete cycle. WorkOS publishes no `connection.updated` or `dsync.updated`+# event, which is why `connections` and `directories` stay on full refresh: under webhook sync a+# directory rename or a SAML certificate renewal would never reach the table.+WEBHOOK_EVENTS_BY_SCHEMA: dict[str, tuple[str, ...]] = {+ "users": ("user.created", "user.updated", "user.deleted"),+ "organizations": ("organization.created", "organization.updated", "organization.deleted"),+ "directory_users": ("dsync.user.created", "dsync.user.updated", "dsync.user.deleted"),+ "directory_groups": ("dsync.group.created", "dsync.group.updated", "dsync.group.deleted"),+}++WEBHOOK_EVENT_TO_SCHEMA = {event: schema for schema, events in WEBHOOK_EVENTS_BY_SCHEMA.items() for event in events}+WEBHOOK_SCHEMA_NAMES = frozenset(WEBHOOK_EVENTS_BY_SCHEMA)+ALL_WEBHOOK_EVENTS = tuple(event for events in WEBHOOK_EVENTS_BY_SCHEMA.values() for event in events)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/source.pyindex 558c5f8f366a..29d590cfd0aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/source.py@@ -1,4 +1,9 @@-from typing import Optional, cast+from typing import TYPE_CHECKING, Optional, cast++from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager++if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDCfrom posthog.schema import (DataWarehouseSourceCategory,@@ -9,7 +14,15 @@ from posthog.schema import (SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ FieldType,+ ResumableSource,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,+ WebhookSyncResult,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)@@ -18,9 +31,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.workos import WorkOSSourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.workos.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.workos.settings import (+ ALL_WEBHOOK_EVENTS,+ ENDPOINTS,+ WEBHOOK_SCHEMA_NAMES,+)from products.warehouse_sources.backend.temporal.data_imports.sources.workos.workos import (WorkOSResumeConfig,+ create_webhook as create_workos_webhook,+ delete_webhook as delete_workos_webhook,+ get_webhook_info as get_workos_webhook_info,+ sync_webhook_events as sync_workos_webhook_events,validate_credentials as validate_workos_credentials,workos_source,)@@ -28,7 +49,10 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class WorkOSSource(ResumableSource[WorkOSSourceConfig, WorkOSResumeConfig]):+class WorkOSSource(+ ResumableSource[WorkOSSourceConfig, WorkOSResumeConfig],+ WebhookSource[WorkOSSourceConfig],+):api_docs_url = "https://workos.com/docs/reference"lists_tables_without_credentials = True # static endpoint catalog — safe for public docs@@ -37,6 +61,16 @@ class WorkOSSource(ResumableSource[WorkOSSourceConfig, WorkOSResumeConfig]):def source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WORKOS+ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.workos.webhook_template import template++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return {name: name for name in WEBHOOK_SCHEMA_NAMES}+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(@@ -51,6 +85,7 @@ You can find your API key in the [WorkOS Dashboard](https://dashboard.workos.comThe key starts with `sk_`.""",iconPath="/static/services/workos.png",+ docsUrl="https://posthog.com/docs/cdp/sources/workos",fields=cast(list[FieldType],[@@ -64,6 +99,26 @@ The key starts with `sk_`.),],),+ webhookSetupCaption="""PostHog can create the WorkOS webhook automatically. To set it up manually:++1. Open **Webhooks** in the WorkOS Dashboard.+2. Create an endpoint and paste the webhook URL shown below.+3. Select the events for the tables you sync.+4. Copy the endpoint's signing secret into the field below.+""",+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="Signing secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="whsec_...",+ secret=True,+ )+ ],+ ),)def get_canonical_descriptions(self) -> CanonicalDescriptions:@@ -82,13 +137,15 @@ The key starts with `sk_`.force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # WorkOS list endpoints expose no server-side timestamp filter, so only- # full refresh is supported.+ # WorkOS list endpoints expose no server-side timestamp filter, so a polled sync is+ # always a full refresh. The tables in WEBHOOK_SCHEMA_NAMES can switch to webhook sync+ # after the initial backfill.schemas = [SourceSchema(name=endpoint,supports_incremental=False,supports_append=False,+ supports_webhooks=endpoint in WEBHOOK_SCHEMA_NAMES,incremental_fields=[],)for endpoint in list(ENDPOINTS)@@ -103,7 +160,10 @@ The key starts with `sk_`.def get_non_retryable_errors(self) -> dict[str, str | None]:return {"401 Client Error: Unauthorized for url: https://api.workos.com": "Your WorkOS API key is invalid or has been revoked. Please update the key in your WorkOS dashboard and reconnect.",- "403 Client Error: Forbidden for url: https://api.workos.com": "Your WorkOS API key does not have permission to access this endpoint. Please check the key's scopes in your WorkOS dashboard.",+ # A WorkOS API key can make any request in its own environment, so a 403 is about the+ # account rather than the key's access: the key belongs to another environment, or the+ # product behind the endpoint is not enabled.+ "403 Client Error: Forbidden for url: https://api.workos.com": "WorkOS refused access to one of the endpoints being synced. Check that the API key comes from the WorkOS environment that holds this data, and that the product behind the table is enabled for your account. Then reconnect the source.",# WorkOS returns 422 for a syntactically valid list request it can't fulfil for this# account — e.g. the Directory Sync endpoints (directory_users/directory_groups) when# Directory Sync isn't provisioned. It's deterministic, so retrying never resolves it.@@ -122,6 +182,40 @@ The key starts with `sk_`.def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WorkOSResumeConfig]:return ResumableSourceManager[WorkOSResumeConfig](inputs, WorkOSResumeConfig)+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def create_webhook(+ self, config: WorkOSSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookCreationResult:+ return create_workos_webhook(config.api_key, webhook_url, list(ALL_WEBHOOK_EVENTS))++ def get_desired_webhook_events(+ self, config: WorkOSSourceConfig, eligible_schema_names: list[str]+ ) -> list[str] | None:+ return list(ALL_WEBHOOK_EVENTS)++ def sync_webhook_events(+ self,+ config: WorkOSSourceConfig,+ webhook_url: str,+ team_id: int,+ eligible_schema_names: list[str],+ api_version: str | None = None,+ ) -> WebhookSyncResult:+ desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []+ return sync_workos_webhook_events(config.api_key, webhook_url, desired_events)++ def get_external_webhook_info(+ self, config: WorkOSSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> ExternalWebhookInfo:+ return get_workos_webhook_info(config.api_key, webhook_url)++ def delete_webhook(+ self, config: WorkOSSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookDeletionResult:+ return delete_workos_webhook(config.api_key, webhook_url)+def source_for_pipeline(self,config: WorkOSSourceConfig,@@ -134,4 +228,5 @@ The key starts with `sk_`.team_id=inputs.team_id,job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,+ webhook_source_manager=self.get_webhook_source_manager(inputs),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos.pyindex 707935b22d61..ea5f2c13a219 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos.py@@ -4,20 +4,29 @@ from collections.abc import Iterablefrom typing import Any, castimport pytest-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patchfrom requests import Request, Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.workos.settings import ENDPOINTS, WORKOS_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.workos.workos import (WorkOSPaginator,WorkOSResumeConfig,+ create_webhook,+ delete_webhook,get_resource,+ get_webhook_info,+ sync_webhook_events,validate_credentials,workos_source,)+WORKOS_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.workos.workos.make_tracked_session"+)+class TestWorkOSPaginator:def test_initial_state(self) -> None:@@ -132,6 +141,12 @@ def _page(ids: list[str], after: str | None) -> dict[str, Any]:return {"data": [{"id": i} for i in ids], "list_metadata": {"before": None, "after": after}}+def _webhook_manager(enabled: bool) -> MagicMock:+ manager = MagicMock(spec=WebhookSourceManager)+ manager.webhook_enabled = AsyncMock(return_value=enabled)+ return manager++class TestWorkOSEndpoints:def test_all_endpoints_registered(self) -> None:assert set(ENDPOINTS) == set(WORKOS_ENDPOINTS)@@ -159,6 +174,7 @@ class TestWorkOSEndpoints:team_id=123,job_id="job_1",resumable_source_manager=manager,+ webhook_source_manager=_webhook_manager(enabled=False),)assert response.name == endpoint@@ -166,11 +182,38 @@ class TestWorkOSEndpoints:assert response.partition_keys == ["created_at"]assert response.partition_mode == "datetime"+ @pytest.mark.parametrize("webhook_enabled", [True, False])+ def test_items_come_from_the_webhook_manager_only_once_webhooks_are_live(self, webhook_enabled: bool) -> None:+ # Reading webhook files before the backfill finishes leaves the table seeded with only+ # the rows a webhook happened to deliver; polling after it finishes never sees deletes.+ resumable = MagicMock(spec=ResumableSourceManager)+ resumable.can_resume.return_value = False+ webhook_manager = _webhook_manager(enabled=webhook_enabled)+ webhook_items = object()+ webhook_manager.get_items.return_value = webhook_items++ response = workos_source(+ api_key="sk_test_123",+ endpoint="users",+ team_id=123,+ job_id="job_1",+ resumable_source_manager=resumable,+ webhook_source_manager=webhook_manager,+ )++ if webhook_enabled:+ assert response.items() is webhook_items+ else:+ assert response.items() is not webhook_items+ webhook_manager.get_items.assert_not_called()+class TestWorkOSSourceResumeBehavior:"""End-to-end resume behaviour through the shared ``rest_api_resource`` path."""- def _drive(self, manager: MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ def _drive(+ self, manager: MagicMock, responses: list[Response], endpoint: str = "organizations"+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:sent_params: list[dict[str, Any]] = []response_iter = iter(responses)@@ -188,13 +231,14 @@ class TestWorkOSSourceResumeBehavior:source_response = workos_source(api_key="sk_test_123",- endpoint="organizations",+ endpoint=endpoint,team_id=123,job_id="job_1",resumable_source_manager=manager,+ webhook_source_manager=_webhook_manager(enabled=False),)- list(cast(Iterable[Any], source_response.items()))- return sent_params+ pages = list(cast(Iterable[Any], source_response.items()))+ return sent_params, [row for page in pages for row in page]def test_fresh_run_saves_cursor_after_each_non_terminal_page(self) -> None:manager = MagicMock(spec=ResumableSourceManager)@@ -205,7 +249,7 @@ class TestWorkOSSourceResumeBehavior:_make_http_response(_page(["org_3", "org_4"], after="org_4")),_make_http_response(_page(["org_5"], after=None)),]- sent_params = self._drive(manager, responses)+ sent_params, _ = self._drive(manager, responses)# First request omits the cursor (fresh run); subsequent requests carry it.assert [p.get("after") for p in sent_params] == [None, "org_2", "org_4"]@@ -221,9 +265,9 @@ class TestWorkOSSourceResumeBehavior:responses = [_make_http_response(_page(["org_5"], after=None)),]- sent_params = self._drive(manager, responses)+ sent_params, _ = self._drive(manager, responses)- # First request goes out at the resumed cursor — no re-fetch of synced pages.+ # First request goes out at the resumed cursor, so synced pages are not re-fetched.assert [p.get("after") for p in sent_params] == ["org_4"]def test_terminal_single_page_does_not_save_state(self) -> None:@@ -237,6 +281,27 @@ class TestWorkOSSourceResumeBehavior:manager.save_state.assert_not_called()+ @pytest.mark.parametrize(+ ("endpoint", "expected_row"),+ [+ ("organizations", {"id": "org_1", "workos_deleted": False, "workos_deleted_at": None}),+ ("connections", {"id": "org_1"}),+ ],+ )+ def test_polled_rows_carry_a_tombstone_only_where_webhooks_can_set_one(+ self, endpoint: str, expected_row: dict[str, Any]+ ) -> None:+ # A webhook delete merges a tombstone onto a row the backfill wrote, so the backfill has+ # to write the same columns. Without this they read NULL for every backfilled row, and+ # `where not workos_deleted` drops the rows no webhook has touched. Tables that never+ # sync by webhook get no tombstone column, because nothing can ever set it.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ _, rows = self._drive(manager, [_make_http_response(_page(["org_1"], after=None))], endpoint=endpoint)++ assert rows == [expected_row]+class TestWorkOSValidateCredentials:@pytest.mark.parametrize(@@ -261,3 +326,116 @@ class TestWorkOSValidateCredentials:cfg = WorkOSResumeConfig(after="org_1500")reconstituted = WorkOSResumeConfig(**json.loads(json.dumps(dataclasses.asdict(cfg))))assert reconstituted == cfg+++WEBHOOK_URL = "https://webhooks.us.posthog.com/public/webhooks/dwh/hog_1"+++def _webhook_page(webhooks: list[dict[str, Any]], after: str | None) -> Response:+ return _make_http_response({"object": "list", "data": webhooks, "list_metadata": {"before": None, "after": after}})+++class TestWorkOSWebhookManagement:+ @patch(WORKOS_SESSION_PATCH)+ def test_lookup_pages_past_the_first_page(self, MockSession: MagicMock) -> None:+ # WorkOS lists 10 endpoints per page by default, so an account with more than that would+ # report ours as missing — prompting a duplicate create, and a delete that removes nothing.+ session = MockSession.return_value+ session.get.side_effect = [+ _webhook_page([{"id": "we_1", "endpoint_url": "https://other.example"}], after="we_1"),+ _webhook_page(+ [{"id": "we_2", "endpoint_url": WEBHOOK_URL, "events": ["user.created"], "status": "enabled"}],+ after=None,+ ),+ ]++ info = get_webhook_info("sk_test_123", WEBHOOK_URL)++ assert info.exists is True+ assert info.enabled_events == ["user.created"]+ assert session.get.call_args_list[0].kwargs["params"] == {"limit": 100}+ assert session.get.call_args_list[1].kwargs["params"] == {"limit": 100, "after": "we_1"}++ @patch(WORKOS_SESSION_PATCH)+ def test_lookup_reports_absence(self, MockSession: MagicMock) -> None:+ MockSession.return_value.get.return_value = _webhook_page([], after=None)+ assert get_webhook_info("sk_test_123", WEBHOOK_URL).exists is False++ @patch(WORKOS_SESSION_PATCH)+ def test_create_persists_the_one_time_secret(self, MockSession: MagicMock) -> None:+ MockSession.return_value.post.return_value = _make_http_response({"id": "we_1", "secret": "whsec_abc"})++ result = create_webhook("sk_test_123", WEBHOOK_URL, ["user.created"])++ assert result.success is True+ assert result.extra_inputs == {"signing_secret": "whsec_abc"}+ assert MockSession.return_value.post.call_args.kwargs["json"] == {+ "endpoint_url": WEBHOOK_URL,+ "events": ["user.created"],+ }++ @patch(WORKOS_SESSION_PATCH)+ def test_create_without_a_secret_asks_for_manual_entry(self, MockSession: MagicMock) -> None:+ # Without the secret the hog function rejects every delivery, so success would be a lie.+ MockSession.return_value.post.return_value = _make_http_response({"id": "we_1"})++ result = create_webhook("sk_test_123", WEBHOOK_URL, ["user.created"])++ assert result.success is False+ assert result.pending_inputs == ["signing_secret"]++ @patch(WORKOS_SESSION_PATCH)+ def test_create_failure_is_reported_not_raised(self, MockSession: MagicMock) -> None:+ MockSession.return_value.post.side_effect = Exception("boom")+ assert create_webhook("sk_test_123", WEBHOOK_URL, ["user.created"]).success is False++ @patch(WORKOS_SESSION_PATCH)+ def test_sync_merges_missing_events_and_keeps_manual_ones(self, MockSession: MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _webhook_page(+ [{"id": "we_2", "endpoint_url": WEBHOOK_URL, "events": ["user.created", "invoice.paid"]}], after=None+ )+ session.patch.return_value = _make_http_response({})++ result = sync_webhook_events("sk_test_123", WEBHOOK_URL, ["user.created", "user.deleted"])++ assert result.success is True+ assert session.patch.call_args.args[0].endswith("/webhook_endpoints/we_2")+ assert session.patch.call_args.kwargs["json"] == {"events": ["invoice.paid", "user.created", "user.deleted"]}++ @patch(WORKOS_SESSION_PATCH)+ def test_sync_skips_the_write_when_events_already_match(self, MockSession: MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _webhook_page(+ [{"id": "we_2", "endpoint_url": WEBHOOK_URL, "events": ["user.created"]}], after=None+ )++ assert sync_webhook_events("sk_test_123", WEBHOOK_URL, ["user.created"]).success is True+ session.patch.assert_not_called()++ @patch(WORKOS_SESSION_PATCH)+ def test_delete_removes_only_the_matching_endpoint(self, MockSession: MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _webhook_page(+ [+ {"id": "we_1", "endpoint_url": "https://other.example"},+ {"id": "we_2", "endpoint_url": WEBHOOK_URL},+ ],+ after=None,+ )+ session.delete.return_value = _make_http_response({})++ result = delete_webhook("sk_test_123", WEBHOOK_URL)++ assert result.success is True+ assert [call.args[0] for call in session.delete.call_args_list] == [+ "https://api.workos.com/webhook_endpoints/we_2"+ ]++ @patch(WORKOS_SESSION_PATCH)+ def test_delete_surfaces_a_rejected_removal(self, MockSession: MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _webhook_page([{"id": "we_2", "endpoint_url": WEBHOOK_URL}], after=None)+ session.delete.return_value = _make_http_response({"message": "forbidden"}, status_code=403)++ assert delete_webhook("sk_test_123", WEBHOOK_URL).success is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos_source.pyindex 42a9ac169fe3..496d61ab64f9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos_source.py@@ -1,8 +1,11 @@import pytest+import pyarrow as pa+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.workos import WorkOSSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.workos.settings import ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.workos.source import WorkOSSource+from products.warehouse_sources.backend.temporal.data_imports.sources.workos.workos import _webhook_table_transformerclass TestWorkOSSource:@@ -63,3 +66,28 @@ class TestWorkOSSource:def test_get_schemas_filtered_unknown_name_returns_empty(self):schemas = self.source.get_schemas(self.config, self.team_id, names=["nonexistent"])assert schemas == []++ def test_webhook_transformer_extracts_rows_and_marks_deletes(self):+ table = pa.Table.from_pylist(+ [+ {+ "event": "user.updated",+ "created_at": "2026-01-01T00:00:00Z",+ "data": '{"id":"user_1","email":"[email protected]"}',+ },+ {+ "event": "user.deleted",+ "created_at": "2026-01-02T00:00:00Z",+ "data": '{"id":"user_1","email":"[email protected]"}',+ },+ ]+ )++ assert _webhook_table_transformer(table).to_pylist() == [+ {+ "id": "user_1",+ "email": "[email protected]",+ "workos_deleted": True,+ "workos_deleted_at": "2026-01-02T00:00:00Z",+ }+ ]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos_webhook_template.pynew file mode 100644index 000000000000..80d3bc6e1471--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/tests/test_workos_webhook_template.py@@ -0,0 +1,96 @@+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.workos.settings import WEBHOOK_EVENT_TO_SCHEMA+from products.warehouse_sources.backend.temporal.data_imports.sources.workos.webhook_template import template+++class TestWorkOSWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):+ template = template++ def createHogGlobals(self, globals=None) -> dict:+ data = {"request": {"method": "POST", "headers": {}, "body": {}, "query": {}, "stringBody": ""}}+ if globals and globals.get("request"):+ data["request"].update(globals["request"])+ return data++ def _request(self, secret: str, body: dict, timestamp: int | None = None) -> dict:+ payload = json.dumps(body)+ timestamp_string = str(timestamp if timestamp is not None else int(time.time() * 1000))+ signature = hmac.new(secret.encode(), f"{timestamp_string}.{payload}".encode(), hashlib.sha256).hexdigest()+ return {+ "request": {+ "method": "POST",+ "headers": {"workos-signature": f"t={timestamp_string},v1={signature}"},+ "body": body,+ "query": {},+ "stringBody": payload,+ }+ }++ @parameterized.expand(sorted(WEBHOOK_EVENT_TO_SCHEMA.items()))+ def test_routes_supported_events(self, event_type: str, resource: str) -> None:+ body = {"id": "event_1", "event": event_type, "data": {"id": "resource_1"}}+ globals = self._request("secret", body)+ self.run_function(+ {+ "signing_secret": "secret",+ "bypass_signature_check": False,+ "schema_mapping": {resource: "schema_1"},+ },+ globals=globals,+ )+ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(body, "schema_1")++ @parameterized.expand(+ [+ ("unhandled_event", "invoice.created", {"users": "schema_1"}, "Unhandled event type"),+ ("unmapped_resource", "user.created", {}, "No schema mapping"),+ ]+ )+ def test_acknowledges_events_it_does_not_store(+ self, _label: str, event_type: str, schema_mapping: dict, expected_body: str+ ) -> None:+ # A non-200 here makes WorkOS retry, then disable the endpoint, for events the user+ # never asked to sync.+ globals = self._request("secret", {"event": event_type, "data": {"id": "resource_1"}})+ result = self.run_function(+ {"signing_secret": "secret", "bypass_signature_check": False, "schema_mapping": schema_mapping},+ globals=globals,+ )++ assert result.result["httpResponse"]["status"] == 200+ assert expected_body in result.result["httpResponse"]["body"]+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_rejects_delivery_without_a_signature_header(self) -> None:+ body = {"event": "user.created", "data": {"id": "user_1"}}+ result = self.run_function(+ {"signing_secret": "secret", "bypass_signature_check": False, "schema_mapping": {"users": "schema_1"}},+ globals={"request": {"method": "POST", "headers": {}, "body": body, "stringBody": json.dumps(body)}},+ )++ assert result.result == {"httpResponse": {"status": 400, "body": "Missing signature"}}+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_rejects_invalid_signature(self) -> None:+ globals = self._request("wrong", {"event": "user.created", "data": {"id": "user_1"}})+ result = self.run_function(+ {"signing_secret": "correct", "bypass_signature_check": False, "schema_mapping": {}}, globals=globals+ )+ assert result.result == {"httpResponse": {"status": 400, "body": "Bad signature"}}++ def test_rejects_stale_signature(self) -> None:+ globals = self._request(+ "secret", {"event": "user.created", "data": {"id": "user_1"}}, int(time.time() * 1000) - 180001+ )+ result = self.run_function(+ {"signing_secret": "secret", "bypass_signature_check": False, "schema_mapping": {}}, globals=globals+ )+ assert result.result == {"httpResponse": {"status": 400, "body": "Timestamp outside tolerance"}}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/webhook_template.pynew file mode 100644index 000000000000..dacc28616b99--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/webhook_template.py@@ -0,0 +1,108 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-workos",+ name="WorkOS warehouse source webhook",+ description="Receive WorkOS webhook events for data warehouse ingestion",+ icon_url="/static/services/workos.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 signatureHeader := request.headers['workos-signature']+ if (empty(signatureHeader)) {+ return {'httpResponse': {'status': 400, 'body': 'Missing signature'}}+ }++ let parts := splitByString(',', signatureHeader)+ let timestamp := null+ let signature := null+ for (let _, part in parts) {+ let pair := splitByString('=', trim(part), 2)+ if (length(pair) = 2 and pair[1] = 't') { timestamp := pair[2] }+ if (length(pair) = 2 and pair[1] = 'v1') { signature := pair[2] }+ }++ if (empty(timestamp) or empty(signature)) {+ return {'httpResponse': {'status': 400, 'body': 'Could not parse signature'}}+ }++ let expected := sha256HmacChainHex([inputs.signing_secret, concat(timestamp, '.', request.stringBody)])+ if (expected != signature) {+ return {'httpResponse': {'status': 400, 'body': 'Bad signature'}}+ }++ let age := toUnixTimestampMilli(now()) - toInt(timestamp)+ if (age > 180000 or age < -180000) {+ return {'httpResponse': {'status': 400, 'body': 'Timestamp outside tolerance'}}+ }+}++let eventType := request.body.event+// Several event types feed one warehouse table, so the event is collapsed to a resource key+// before the schema lookup. Keep in sync with WEBHOOK_EVENTS_BY_SCHEMA in settings.py.+let resourceByEvent := {+ 'user.created': 'users', 'user.updated': 'users', 'user.deleted': 'users',+ 'organization.created': 'organizations', 'organization.updated': 'organizations', 'organization.deleted': 'organizations',+ 'dsync.user.created': 'directory_users', 'dsync.user.updated': 'directory_users', 'dsync.user.deleted': 'directory_users',+ 'dsync.group.created': 'directory_groups', 'dsync.group.updated': 'directory_groups', 'dsync.group.deleted': 'directory_groups',+}+let resource := resourceByEvent?.[eventType]+if (empty(resource)) {+ return {'httpResponse': {'status': 200, 'body': f'Unhandled event type: {eventType}, skipping'}}+}+let schemaId := inputs.schema_mapping?.[resource]+if (empty(schemaId)) {+ return {'httpResponse': {'status': 200, 'body': f'No schema mapping for event type: {eventType}, skipping'}}+}+produceToWarehouseWebhooks(request.body, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "Signing secret",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": "Used to verify WorkOS webhook deliveries",+ },+ {+ "type": "boolean",+ "key": "bypass_signature_check",+ "label": "Bypass signature check",+ "description": "If set, the WorkOS-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 WorkOS resources 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,+ },+ ],+)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/workos.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/workos.pyindex 3a64b5f377c9..3731ff59ec02 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/workos/workos.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workos/workos.py@@ -1,9 +1,20 @@import dataclasses+from collections.abc import Iteratorfrom typing import Any, Optional+import orjson+import pyarrow as pa+from asgiref.sync import async_to_syncfrom requests import Request, Responsefrom requests.exceptions import RequestException+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSyncResult,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,@@ -16,9 +27,24 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.workos.settings import WORKOS_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.workos.settings import (+ WEBHOOK_SCHEMA_NAMES,+ WORKOS_ENDPOINTS,+)BASE_URL = "https://api.workos.com"+WEBHOOK_ENDPOINTS_PATH = "/webhook_endpoints"+# WorkOS lists 10 endpoints per page by default, so an account with more than that can hide+# ours behind the first page. 100 is the documented maximum.+WEBHOOK_ENDPOINTS_PAGE_SIZE = 100++# Delete events carry a soft tombstone because a webhook sync merges on `id` and can never+# remove a row. On the tables that can switch to webhook sync, the polled backfill writes these+# columns too, so a query that filters on `workos_deleted` covers every row in the table rather+# than only the rows a webhook has touched.+DELETED_COLUMN = "workos_deleted"+DELETED_AT_COLUMN = "workos_deleted_at"@dataclasses.dataclass@@ -134,9 +160,9 @@ def validate_credentials(api_key: str) -> tuple[bool, str | None]:if response.status_code == 200:return True, None- # A valid key that lacks the Organizations scope still proves the key is- # genuine — accept it at source-create so users can sync only the- # endpoints they granted. Sync-time 403s are handled by+ # A 403 still proves the key is genuine, because WorkOS rejects an invalid key with a+ # 401. Accept it at source-create so an account that cannot reach Organizations can+ # still sync the endpoints it does have. Sync-time 403s are handled by# get_non_retryable_errors().if response.status_code == 403:return True, None@@ -157,12 +183,168 @@ def validate_credentials(api_key: str) -> tuple[bool, str | None]:return False, str(e)+def create_webhook(api_key: str, webhook_url: str, events: list[str]) -> WebhookCreationResult:+ """Register a WorkOS webhook and retain its one-time signing secret."""+ try:+ response = make_tracked_session().post(+ f"{BASE_URL}{WEBHOOK_ENDPOINTS_PATH}",+ headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},+ json={"endpoint_url": webhook_url, "events": events},+ timeout=10,+ )+ response.raise_for_status()+ signing_secret = response.json().get("secret")+ if not signing_secret:+ return WebhookCreationResult(+ success=False,+ error="WorkOS created the webhook but did not return a signing secret. Add the secret manually.",+ pending_inputs=["signing_secret"],+ )+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": signing_secret})+ except Exception as e:+ return WebhookCreationResult(+ success=False,+ error=f"Failed to create the WorkOS webhook: {e}. Please create it manually in WorkOS.",+ )+++def _webhook_headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}+++def _iterate_webhook_endpoints(api_key: str) -> Iterator[dict[str, Any]]:+ """Walk every registered webhook endpoint through WorkOS's `after` cursor."""+ session = make_tracked_session()+ after: Optional[str] = None+ while True:+ params: dict[str, Any] = {"limit": WEBHOOK_ENDPOINTS_PAGE_SIZE}+ if after:+ params["after"] = after++ response = session.get(+ f"{BASE_URL}{WEBHOOK_ENDPOINTS_PATH}", headers=_webhook_headers(api_key), params=params, timeout=10+ )+ response.raise_for_status()+ body = response.json()+ if not isinstance(body, dict):+ return++ yield from (webhook for webhook in body.get("data") or [] if isinstance(webhook, dict))++ metadata = body.get("list_metadata")+ after = metadata.get("after") if isinstance(metadata, dict) else None+ if not after:+ return+++def _matching_webhooks(api_key: str, webhook_url: str) -> list[dict[str, Any]]:+ return [webhook for webhook in _iterate_webhook_endpoints(api_key) if webhook.get("endpoint_url") == webhook_url]+++def get_webhook_info(api_key: str, webhook_url: str) -> ExternalWebhookInfo:+ try:+ matching = _matching_webhooks(api_key, webhook_url)+ if not matching:+ return ExternalWebhookInfo(exists=False)+ return ExternalWebhookInfo(+ exists=True,+ url=webhook_url,+ enabled_events=sorted({event for webhook in matching for event in webhook.get("events", [])}),+ status=str(matching[0].get("status")) if matching[0].get("status") else None,+ created_at=str(matching[0].get("created_at")) if matching[0].get("created_at") else None,+ )+ except Exception as e:+ return ExternalWebhookInfo(exists=False, error=str(e))+++def sync_webhook_events(api_key: str, webhook_url: str, desired_events: list[str]) -> WebhookSyncResult:+ """Add any missing `desired_events` to the endpoints pointing at `webhook_url`.++ Events are merged, never removed, so an endpoint a user broadened by hand keeps its extras.+ """+ if not desired_events:+ return WebhookSyncResult(success=True)++ try:+ session = make_tracked_session()+ for webhook in _matching_webhooks(api_key, webhook_url):+ current = webhook.get("events") or []+ merged = sorted(set(current) | set(desired_events))+ if merged == sorted(current):+ continue++ response = session.patch(+ f"{BASE_URL}{WEBHOOK_ENDPOINTS_PATH}/{webhook.get('id')}",+ headers=_webhook_headers(api_key),+ json={"events": merged},+ timeout=10,+ )+ response.raise_for_status()+ return WebhookSyncResult(success=True)+ except Exception as e:+ return WebhookSyncResult(+ success=False,+ error=(+ f"Failed to update the WorkOS webhook events: {e}. "+ f"Please add these events manually in WorkOS: {', '.join(desired_events)}"+ ),+ )+++def delete_webhook(api_key: str, webhook_url: str) -> WebhookDeletionResult:+ try:+ session = make_tracked_session()+ for webhook in _matching_webhooks(api_key, webhook_url):+ webhook_id = webhook.get("id")+ if webhook_id:+ response = session.delete(+ f"{BASE_URL}{WEBHOOK_ENDPOINTS_PATH}/{webhook_id}",+ headers=_webhook_headers(api_key),+ timeout=10,+ )+ response.raise_for_status()+ return WebhookDeletionResult(success=True)+ except Exception as e:+ return WebhookDeletionResult(success=False, error=f"Failed to delete the WorkOS webhook: {e}")+++def _webhook_table_transformer(table: pa.Table) -> pa.Table:+ """Extract full WorkOS resources and preserve delete events as soft tombstones."""+ rows_by_id: dict[str, tuple[str, dict[str, Any]]] = {}+ rows = table.to_pylist()+ for event in rows:+ event_type = event.get("event")+ resource = event.get("data")+ if isinstance(resource, str):+ try:+ resource = orjson.loads(resource)+ except orjson.JSONDecodeError:+ continue+ if not isinstance(event_type, str) or not isinstance(resource, dict) or not resource.get("id"):+ continue++ deleted = event_type.endswith(".deleted")+ raw_created_at = event.get("created_at")+ created_at = raw_created_at if isinstance(raw_created_at, str) else ""+ resource = {+ **resource,+ DELETED_COLUMN: deleted,+ DELETED_AT_COLUMN: raw_created_at if deleted else None,+ }+ current = rows_by_id.get(str(resource["id"]))+ if current is None or created_at >= current[0]:+ rows_by_id[str(resource["id"])] = (created_at, resource)++ return table_from_py_list([row for _, row in rows_by_id.values()])++def workos_source(api_key: str,endpoint: str,team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[WorkOSResumeConfig],+ webhook_source_manager: WebhookSourceManager,) -> SourceResponse:endpoint_config = WORKOS_ENDPOINTS[endpoint]@@ -196,6 +378,8 @@ def workos_source(if state and state.get("after"):resumable_source_manager.save_state(WorkOSResumeConfig(after=str(state["after"])))+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)()+resource = rest_api_resource(config,team_id,@@ -204,10 +388,16 @@ def workos_source(resume_hook=save_checkpoint,initial_paginator_state=initial_paginator_state,)+ if endpoint in WEBHOOK_SCHEMA_NAMES:+ resource = resource.add_map(lambda row: {**row, DELETED_COLUMN: False, DELETED_AT_COLUMN: None})return SourceResponse(name=endpoint,- items=lambda: resource,+ items=lambda: (+ webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)+ if webhook_enabled+ else resource+ ),primary_keys=["id"],partition_count=1,partition_size=1,