:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement zendesk_sell import source (#65647)
Tom Owers3b56b55eca7c
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex ae0f3278f94e..22ed017d70c8 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -220,6 +220,7 @@ the row lists both.| workos | HTTP | requests + `rest_source.RESTClient` | ✅ || wrike | HTTP | requests | ✅ || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |+| zendesk_sell | HTTP | requests | ✅ || zoom | HTTP | requests | ✅ || zuora | HTTP | requests | ✅ |@@ -705,7 +706,6 @@ doesn't conflict with concurrent PRs.- youtube_data- zapier_supported_storage- zapsign-- zendesk_sell- zendesk_sunshine- zenefits- zenloopdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 65ba64d9125e..62dd788309f7 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -3423,7 +3423,7 @@ class ZapierSupportedStorageSourceConfig(config.Config):@config.configclass ZendeskSellSourceConfig(config.Config):- pass+ access_token: str@config.configdiff --git a/posthog/temporal/data_imports/sources/zendesk_sell/canonical_descriptions.py b/posthog/temporal/data_imports/sources/zendesk_sell/canonical_descriptions.pynew file mode 100644index 000000000000..6608632d6063--- /dev/null+++ b/posthog/temporal/data_imports/sources/zendesk_sell/canonical_descriptions.py@@ -0,0 +1,152 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Curated from the Zendesk Sell (Base CRM) Core API docs: https://developer.zendesk.com/api-reference/sales-crm/+# Partial coverage is fine — any endpoint/column not listed falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "contacts": {+ "description": "People and companies in your Sell account. A contact can be a person or an organization.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/contacts/",+ "columns": {+ "id": "Unique identifier of the contact.",+ "is_organization": "Whether the contact is an organization (true) or a person (false).",+ "name": "Organization name (set when is_organization is true).",+ "first_name": "Contact's first name (for people).",+ "last_name": "Contact's last name (for people).",+ "email": "Primary email address.",+ "phone": "Primary phone number.",+ "owner_id": "Identifier of the user that owns the contact.",+ "created_at": "Time the contact was created, in UTC ISO-8601.",+ "updated_at": "Time the contact was last updated, in UTC ISO-8601.",+ },+ },+ "deals": {+ "description": "Sales opportunities tracked through your pipeline.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/deals/",+ "columns": {+ "id": "Unique identifier of the deal.",+ "name": "Name of the deal.",+ "value": "Monetary value of the deal.",+ "currency": "Currency of the deal value (ISO 4217).",+ "stage_id": "Identifier of the pipeline stage the deal is in.",+ "contact_id": "Identifier of the primary contact for the deal.",+ "owner_id": "Identifier of the user that owns the deal.",+ "hot": "Whether the deal is marked as hot.",+ "created_at": "Time the deal was created, in UTC ISO-8601.",+ "updated_at": "Time the deal was last updated, in UTC ISO-8601.",+ },+ },+ "leads": {+ "description": "Prospects that have not yet been qualified into contacts and deals.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/leads/",+ "columns": {+ "id": "Unique identifier of the lead.",+ "first_name": "Lead's first name.",+ "last_name": "Lead's last name.",+ "organization_name": "Lead's organization name.",+ "status": "Current status of the lead.",+ "email": "Primary email address.",+ "owner_id": "Identifier of the user that owns the lead.",+ "created_at": "Time the lead was created, in UTC ISO-8601.",+ "updated_at": "Time the lead was last updated, in UTC ISO-8601.",+ },+ },+ "tasks": {+ "description": "To-do items associated with contacts, leads, or deals.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/tasks/",+ "columns": {+ "id": "Unique identifier of the task.",+ "content": "Task description.",+ "due_date": "When the task is due.",+ "completed": "Whether the task has been completed.",+ "owner_id": "Identifier of the user that owns the task.",+ "created_at": "Time the task was created, in UTC ISO-8601.",+ "updated_at": "Time the task was last updated, in UTC ISO-8601.",+ },+ },+ "notes": {+ "description": "Free-form notes attached to contacts, leads, or deals.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/notes/",+ "columns": {+ "id": "Unique identifier of the note.",+ "content": "Note text.",+ "resource_type": "Type of resource the note is attached to (contact, lead, or deal).",+ "resource_id": "Identifier of the resource the note is attached to.",+ "created_at": "Time the note was created, in UTC ISO-8601.",+ "updated_at": "Time the note was last updated, in UTC ISO-8601.",+ },+ },+ "calls": {+ "description": "Logged phone calls associated with contacts, leads, or deals.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/calls/",+ "columns": {+ "id": "Unique identifier of the call.",+ "duration": "Call duration in seconds.",+ "phone_number": "Phone number that was called.",+ "outcome_id": "Identifier of the call outcome.",+ "made_at": "When the call was made.",+ "created_at": "Time the call record was created, in UTC ISO-8601.",+ },+ },+ "orders": {+ "description": "Orders placed against a deal, grouping the line items sold.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/orders/",+ "columns": {+ "id": "Unique identifier of the order.",+ "deal_id": "Identifier of the deal the order belongs to.",+ "discount": "Order-level discount percentage.",+ "created_at": "Time the order was created, in UTC ISO-8601.",+ "updated_at": "Time the order was last updated, in UTC ISO-8601.",+ },+ },+ "products": {+ "description": "Catalog of products that can be added to deals as line items.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/products/",+ "columns": {+ "id": "Unique identifier of the product.",+ "name": "Product name.",+ "sku": "Stock keeping unit.",+ "active": "Whether the product is active in the catalog.",+ "created_at": "Time the product was created, in UTC ISO-8601.",+ "updated_at": "Time the product was last updated, in UTC ISO-8601.",+ },+ },+ "users": {+ "description": "Users (agents) in the Zendesk Sell account.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/users/",+ "columns": {+ "id": "Unique identifier of the user.",+ "name": "User's full name.",+ "email": "User's email address.",+ "role": "User's role in the account.",+ "status": "Whether the user is active or inactive.",+ "created_at": "Time the user was created, in UTC ISO-8601.",+ },+ },+ "pipelines": {+ "description": "Sales pipelines that group deal stages.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/pipelines/",+ "columns": {+ "id": "Unique identifier of the pipeline.",+ "name": "Pipeline name.",+ },+ },+ "stages": {+ "description": "Stages within a pipeline that deals move through.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/stages/",+ "columns": {+ "id": "Unique identifier of the stage.",+ "name": "Stage name.",+ "pipeline_id": "Identifier of the pipeline the stage belongs to.",+ "position": "Order of the stage within its pipeline.",+ },+ },+ "tags": {+ "description": "Tags used to label contacts, leads, and deals.",+ "docs_url": "https://developer.zendesk.com/api-reference/sales-crm/resources/tags/",+ "columns": {+ "id": "Unique identifier of the tag.",+ "name": "Tag name.",+ "resource_type": "Type of resource the tag applies to.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/zendesk_sell/settings.py b/posthog/temporal/data_imports/sources/zendesk_sell/settings.pynew file mode 100644index 000000000000..a4ac5898ec5e--- /dev/null+++ b/posthog/temporal/data_imports/sources/zendesk_sell/settings.py@@ -0,0 +1,60 @@+from dataclasses import dataclass, field+from typing import Optional+++@dataclass+class ZendeskSellEndpointConfig:+ name: str+ # Path under the v2 base URL, e.g. "/v2/contacts".+ path: str+ # Every Core API resource exposes a globally-unique integer `id`, so a single-column key is safe.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation timestamp to partition by. Set only for the high-volume transactional resources;+ # the small config/lookup tables (pipelines, stages, tags, sources, reasons, outcomes) are left+ # unpartitioned because partitioning a handful of rows buys nothing. Never `updated_at` — partitions+ # must not move when a record is edited.+ partition_key: Optional[str] = None+ # Whether the table is selected for sync by default in the connection wizard.+ should_sync_default: bool = True+++# Core API collection endpoints (https://api.getbase.com/v2/). Each returns the standard+# `{"items": [{"data": {...}}], "meta": {"links": {"next_page": ...}}}` envelope and is paginated by+# 1-based `page` + `per_page` (max 100). All are full-refresh: the Core API exposes `sort_by` but no+# server-side `updated_after`/`since` timestamp filter, so there is no cheap way to fetch only changed+# rows (see the module docstring in zendesk_sell.py).+ZENDESK_SELL_ENDPOINTS: dict[str, ZendeskSellEndpointConfig] = {+ "contacts": ZendeskSellEndpointConfig(name="contacts", path="/v2/contacts", partition_key="created_at"),+ "deals": ZendeskSellEndpointConfig(name="deals", path="/v2/deals", partition_key="created_at"),+ "leads": ZendeskSellEndpointConfig(name="leads", path="/v2/leads", partition_key="created_at"),+ "tasks": ZendeskSellEndpointConfig(name="tasks", path="/v2/tasks", partition_key="created_at"),+ "notes": ZendeskSellEndpointConfig(name="notes", path="/v2/notes", partition_key="created_at"),+ "calls": ZendeskSellEndpointConfig(name="calls", path="/v2/calls", partition_key="created_at"),+ "text_messages": ZendeskSellEndpointConfig(+ name="text_messages", path="/v2/text_messages", partition_key="created_at"+ ),+ "visits": ZendeskSellEndpointConfig(name="visits", path="/v2/visits", partition_key="created_at"),+ "orders": ZendeskSellEndpointConfig(name="orders", path="/v2/orders", partition_key="created_at"),+ "products": ZendeskSellEndpointConfig(name="products", path="/v2/products", partition_key="created_at"),+ "collaborations": ZendeskSellEndpointConfig(+ name="collaborations", path="/v2/collaborations", partition_key="created_at"+ ),+ "users": ZendeskSellEndpointConfig(name="users", path="/v2/users", partition_key="created_at"),+ # Small config / lookup resources — full refresh, no partitioning.+ "pipelines": ZendeskSellEndpointConfig(name="pipelines", path="/v2/pipelines"),+ "stages": ZendeskSellEndpointConfig(name="stages", path="/v2/stages"),+ "tags": ZendeskSellEndpointConfig(name="tags", path="/v2/tags"),+ "deal_sources": ZendeskSellEndpointConfig(name="deal_sources", path="/v2/deal_sources"),+ "lead_sources": ZendeskSellEndpointConfig(name="lead_sources", path="/v2/lead_sources"),+ "loss_reasons": ZendeskSellEndpointConfig(name="loss_reasons", path="/v2/loss_reasons"),+ "deal_unqualified_reasons": ZendeskSellEndpointConfig(+ name="deal_unqualified_reasons", path="/v2/deal_unqualified_reasons"+ ),+ "lead_unqualified_reasons": ZendeskSellEndpointConfig(+ name="lead_unqualified_reasons", path="/v2/lead_unqualified_reasons"+ ),+ "call_outcomes": ZendeskSellEndpointConfig(name="call_outcomes", path="/v2/call_outcomes"),+ "visit_outcomes": ZendeskSellEndpointConfig(name="visit_outcomes", path="/v2/visit_outcomes"),+}++ENDPOINTS = tuple(ZENDESK_SELL_ENDPOINTS.keys())diff --git a/posthog/temporal/data_imports/sources/zendesk_sell/source.py b/posthog/temporal/data_imports/sources/zendesk_sell/source.pyindex 2eea75dc227c..e97b9d5d2d20 100644--- a/posthog/temporal/data_imports/sources/zendesk_sell/source.py+++ b/posthog/temporal/data_imports/sources/zendesk_sell/source.py@@ -1,20 +1,34 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import ZendeskSellSourceConfig+from posthog.temporal.data_imports.sources.zendesk_sell.canonical_descriptions import CANONICAL_DESCRIPTIONS+from posthog.temporal.data_imports.sources.zendesk_sell.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.zendesk_sell.zendesk_sell import (+ ZendeskSellResumeConfig,+ validate_credentials as validate_zendesk_sell_credentials,+ zendesk_sell_source,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class ZendeskSellSource(SimpleSource[ZendeskSellSourceConfig]):+class ZendeskSellSource(ResumableSource[ZendeskSellSourceConfig, ZendeskSellResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ZENDESKSELL@@ -25,7 +39,86 @@ class ZendeskSellSource(SimpleSource[ZendeskSellSourceConfig]):name=SchemaExternalDataSourceType.ZENDESK_SELL,category=DataWarehouseSourceCategory.CRM,label="Zendesk Sell",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Zendesk Sell access token to pull your Sell (formerly Base CRM) data into the PostHog Data warehouse.++Create a personal access token under **Settings > Integrations > OAuth > Access Tokens** in Zendesk Sell. A read-only token is sufficient.""",iconPath="/static/services/zendesk_sell.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/zendesk-sell",+ # Alpha: ships hidden until the end-to-end sync is verified against a live account.unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A missing/expired/invalid token surfaces as a requests HTTPError once `raise_for_status`+ # runs. Match the stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.getbase.com": "Your Zendesk Sell access token is invalid or has expired. Create a new access token in your Zendesk Sell settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.getbase.com": "Your Zendesk Sell access token is missing the permissions needed to sync this data. Grant read access and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: ZendeskSellSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # All endpoints are full refresh: the Core API has no server-side timestamp filter, so there's+ # no cheap incremental sync. See zendesk_sell.py for details.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in ENDPOINTS+ ]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self, config: ZendeskSellSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_zendesk_sell_credentials(config.access_token):+ return True, None++ return False, "Invalid Zendesk Sell access token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZendeskSellResumeConfig]:+ return ResumableSourceManager[ZendeskSellResumeConfig](inputs, ZendeskSellResumeConfig)++ def source_for_pipeline(+ self,+ config: ZendeskSellSourceConfig,+ resumable_source_manager: ResumableSourceManager[ZendeskSellResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return zendesk_sell_source(+ access_token=config.access_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/zendesk_sell/tests/test_zendesk_sell.py b/posthog/temporal/data_imports/sources/zendesk_sell/tests/test_zendesk_sell.pynew file mode 100644index 000000000000..13553ef2c02c--- /dev/null+++ b/posthog/temporal/data_imports/sources/zendesk_sell/tests/test_zendesk_sell.py@@ -0,0 +1,294 @@+import json+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.zendesk_sell import zendesk_sell+from posthog.temporal.data_imports.sources.zendesk_sell.zendesk_sell import (+ PER_PAGE,+ ZendeskSellResumeConfig,+ ZendeskSellRetryableError,+ ZendeskSellUntrustedURLError,+ _build_initial_url,+ _extract_records,+ _fetch_page,+ _validate_pagination_url,+ get_rows,+ validate_credentials,+ zendesk_sell_source,+)+++class _FakeResumableManager:+ def __init__(self, state: ZendeskSellResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ZendeskSellResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ZendeskSellResumeConfig | None:+ return self._state++ def save_state(self, data: ZendeskSellResumeConfig) -> None:+ self.saved.append(data)+++def _envelope(records: list[dict[str, Any]], next_page: str | None) -> dict[str, Any]:+ """Build the Zendesk Sell collection envelope around a list of record dicts."""+ links: dict[str, Any] = {"self": "https://api.getbase.com/v2/contacts?page=1&per_page=100"}+ if next_page:+ links["next_page"] = next_page+ return {+ "items": [{"data": r, "meta": {"type": "contact"}} for r in records],+ "meta": {"type": "collection", "count": len(records), "links": links},+ }+++def _response_with(status_code: int, body: dict[str, Any] | None = None) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response._content = json.dumps(body or {}).encode()+ response.url = "https://api.getbase.com/v2/contacts"+ return response+++# The undecorated function behind tenacity's retry wrapper — call it to exercise status handling+# without the retry/backoff loop actually sleeping.+_fetch_page_unwrapped = _fetch_page.__wrapped__ # type: ignore[attr-defined]+++class TestExtractRecords:+ @parameterized.expand(+ [+ ("empty", {"items": []}, []),+ ("missing_items", {"meta": {}}, []),+ (+ "single",+ {"items": [{"data": {"id": 1, "name": "Acme"}, "meta": {"type": "contact"}}]},+ [{"id": 1, "name": "Acme"}],+ ),+ ]+ )+ def test_extract_records(self, _name: str, payload: dict[str, Any], expected: list[dict[str, Any]]) -> None:+ assert _extract_records(payload) == expected++ def test_item_without_data_fails_fast(self) -> None:+ # Every envelope item carries `data`; a missing key means a malformed response, which should+ # raise rather than silently drop the record.+ with pytest.raises(KeyError):+ _extract_records({"items": [{"meta": {"type": "contact"}}]})+++class TestBuildInitialUrl:+ def test_uses_base_url_and_max_page_size(self) -> None:+ assert _build_initial_url("/v2/deals") == f"https://api.getbase.com/v2/deals?per_page={PER_PAGE}"+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(status_code)+ with pytest.raises(ZendeskSellRetryableError):+ _fetch_page_unwrapped(session, "https://api.getbase.com/v2/contacts", {}, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_http_error(self, _name: str, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(status_code)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "https://api.getbase.com/v2/contacts", {}, MagicMock())++ def test_ok_returns_parsed_json(self) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(200, _envelope([{"id": 1}], next_page=None))+ result = _fetch_page_unwrapped(session, "https://api.getbase.com/v2/contacts", {}, MagicMock())+ assert result["items"][0]["data"] == {"id": 1}+++class TestGetRowsPagination:+ @staticmethod+ def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any]) -> list[dict[str, Any]]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict[str, Any]:+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(zendesk_sell, "_fetch_page", fake_fetch)++ rows: list[dict[str, Any]] = []+ for batch in get_rows(+ access_token="token",+ endpoint="contacts",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_yields_flattened_records_across_pages(self, monkeypatch: Any) -> None:+ page2 = "https://api.getbase.com/v2/contacts?page=2&per_page=100"+ pages = {+ f"https://api.getbase.com/v2/contacts?per_page={PER_PAGE}": _envelope(+ [{"id": 1}, {"id": 2}], next_page=page2+ ),+ page2: _envelope([{"id": 3}], next_page=None),+ }+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]++ def test_saves_state_only_when_more_pages_remain(self, monkeypatch: Any) -> None:+ page2 = "https://api.getbase.com/v2/contacts?page=2&per_page=100"+ pages = {+ f"https://api.getbase.com/v2/contacts?per_page={PER_PAGE}": _envelope([{"id": 1}], next_page=page2),+ page2: _envelope([{"id": 2}], next_page=None),+ }+ manager = _FakeResumableManager()+ self._collect(manager, monkeypatch, pages)+ # Exactly one checkpoint: after the first page (which had a next_page). The final page must not+ # persist state, so a completed sync leaves nothing to resume into.+ assert manager.saved == [ZendeskSellResumeConfig(next_url=page2)]++ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:+ page2 = "https://api.getbase.com/v2/contacts?page=2&per_page=100"+ pages = {+ page2: _envelope([{"id": 2}], next_page=None),+ }+ manager = _FakeResumableManager(ZendeskSellResumeConfig(next_url=page2))+ rows = self._collect(manager, monkeypatch, pages)+ # The initial page is never requested — only the saved next_url is fetched.+ assert rows == [{"id": 2}]++ def test_empty_collection_yields_nothing(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.getbase.com/v2/contacts?per_page={PER_PAGE}": _envelope([], next_page=None),+ }+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == []+ assert manager.saved == []++ def test_hostile_upstream_next_page_is_rejected(self, monkeypatch: Any) -> None:+ # An upstream response pointing next_page at another host must abort before the bearer token is+ # sent there, and must not be persisted as resume state.+ pages = {+ f"https://api.getbase.com/v2/contacts?per_page={PER_PAGE}": _envelope(+ [{"id": 1}], next_page="https://evil.example.com/v2/contacts"+ ),+ }+ manager = _FakeResumableManager()+ with pytest.raises(ZendeskSellUntrustedURLError):+ self._collect(manager, monkeypatch, pages)+ assert manager.saved == []++ def test_hostile_resumed_next_url_is_rejected(self, monkeypatch: Any) -> None:+ # A poisoned resume state from Redis must never be requested with the bearer token.+ manager = _FakeResumableManager(ZendeskSellResumeConfig(next_url="https://evil.example.com/v2/contacts"))+ with pytest.raises(ZendeskSellUntrustedURLError):+ self._collect(manager, monkeypatch, {})+++class TestValidatePaginationUrl:+ @parameterized.expand(+ [+ ("first_page", f"https://api.getbase.com/v2/contacts?per_page={PER_PAGE}"),+ ("next_page", "https://api.getbase.com/v2/contacts?page=2&per_page=100"),+ ("other_endpoint", "https://api.getbase.com/v2/deals?page=3"),+ ]+ )+ def test_trusted_urls_pass_through(self, _name: str, url: str) -> None:+ assert _validate_pagination_url(url) == url++ @parameterized.expand(+ [+ ("foreign_host", "https://evil.example.com/v2/contacts"),+ ("subdomain_lookalike", "https://api.getbase.com.evil.example.com/v2/contacts"),+ ("http_scheme", "http://api.getbase.com/v2/contacts"),+ ("wrong_path_prefix", "https://api.getbase.com/internal/contacts"),+ ("missing_path", "https://api.getbase.com"),+ ("metadata_endpoint", "http://169.254.169.254/latest/meta-data/"),+ ]+ )+ def test_untrusted_urls_raise(self, _name: str, url: str) -> None:+ with pytest.raises(ZendeskSellUntrustedURLError):+ _validate_pagination_url(url)+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(status_code)+ with patch.object(zendesk_sell, "make_tracked_session", return_value=session):+ assert validate_credentials("token") is expected++ def test_network_error_is_false(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(zendesk_sell, "make_tracked_session", return_value=session):+ assert validate_credentials("token") is False+++class TestTokenRedaction:+ """The bearer token must be registered for value-redaction in tracked transport so it can't leak+ into logged URLs or captured request samples."""++ def test_validate_credentials_redacts_token(self) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(200)+ with patch.object(zendesk_sell, "make_tracked_session", return_value=session) as make_session:+ validate_credentials("secret-token")+ assert make_session.call_args.kwargs["redact_values"] == ("secret-token",)+ assert make_session.call_args.kwargs["allow_redirects"] is False++ def test_get_rows_redacts_token(self, monkeypatch: Any) -> None:+ session = MagicMock()+ make_session = MagicMock(return_value=session)+ monkeypatch.setattr(zendesk_sell, "make_tracked_session", make_session)+ monkeypatch.setattr(+ zendesk_sell,+ "_fetch_page",+ lambda *a, **k: _envelope([], next_page=None),+ )+ list(+ get_rows(+ access_token="secret-token",+ endpoint="contacts",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert make_session.call_args.kwargs["redact_values"] == ("secret-token",)+ assert make_session.call_args.kwargs["allow_redirects"] is False+++class TestZendeskSellSource:+ def test_partitioned_endpoint_response(self) -> None:+ response = zendesk_sell_source(+ access_token="token",+ endpoint="contacts",+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == "contacts"+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ def test_unpartitioned_lookup_endpoint_response(self) -> None:+ response = zendesk_sell_source(+ access_token="token",+ endpoint="stages",+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == "stages"+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/zendesk_sell/tests/test_zendesk_sell_source.py b/posthog/temporal/data_imports/sources/zendesk_sell/tests/test_zendesk_sell_source.pynew file mode 100644index 000000000000..217a7c75eca9--- /dev/null+++ b/posthog/temporal/data_imports/sources/zendesk_sell/tests/test_zendesk_sell_source.py@@ -0,0 +1,135 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.zendesk_sell import source as source_module+from posthog.temporal.data_imports.sources.zendesk_sell.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.zendesk_sell.source import ZendeskSellSource+from posthog.temporal.data_imports.sources.zendesk_sell.zendesk_sell import ZendeskSellResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert ZendeskSellSource().source_type == ExternalDataSourceType.ZENDESKSELL++ def test_config_is_crm_alpha_and_unreleased(self) -> None:+ config = ZendeskSellSource().get_source_config+ assert config.category == DataWarehouseSourceCategory.CRM+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Alpha ships hidden until end-to-end sync is verified against a live account.+ assert config.unreleasedSource is True++ def test_config_exposes_single_password_access_token_field(self) -> None:+ fields = ZendeskSellSource().get_source_config.fields+ assert len(fields) == 1+ field = fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "access_token"+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.required is True+++class TestGetSchemas:+ def test_every_endpoint_is_full_refresh(self) -> None:+ schemas = ZendeskSellSource().get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_names_filter(self) -> None:+ schemas = ZendeskSellSource().get_schemas(MagicMock(), team_id=1, names=["deals", "leads"])+ assert {s.name for s in schemas} == {"deals", "leads"}+++class TestValidateCredentials:+ @parameterized.expand(+ [("valid", True, (True, None)), ("invalid", False, (False, "Invalid Zendesk Sell access token"))]+ )+ def test_validate_credentials(self, _name: str, probe_result: bool, expected: tuple[bool, str | None]) -> None:+ config = MagicMock(access_token="token")+ with patch.object(source_module, "validate_zendesk_sell_credentials", return_value=probe_result):+ assert ZendeskSellSource().validate_credentials(config, team_id=1) == expected+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.getbase.com/v2/contacts?per_page=100",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.getbase.com/v2/deals?per_page=100"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = ZendeskSellSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.getbase.com/v2/contacts"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.getbase.com/v2/deals"),+ ("read_timeout", "HTTPSConnectionPool(host='api.getbase.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = ZendeskSellSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestResumableManager:+ def test_manager_is_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = ZendeskSellSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ZendeskSellResumeConfig+++class TestSourceForPipeline:+ def test_plumbs_config_and_inputs_into_source_response(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}+ sentinel = SourceResponse(name="deals", items=lambda: iter(()), primary_keys=["id"])++ def fake_source(**kwargs: Any) -> SourceResponse:+ captured.update(kwargs)+ return sentinel++ monkeypatch.setattr(source_module, "zendesk_sell_source", fake_source)++ config = MagicMock(access_token="my-token")+ manager = MagicMock()+ inputs = MagicMock(schema_name="deals")+ inputs.logger = MagicMock()++ result = ZendeskSellSource().source_for_pipeline(config, manager, inputs)++ assert result is sentinel+ assert captured["access_token"] == "my-token"+ assert captured["endpoint"] == "deals"+ assert captured["resumable_source_manager"] is manager+++class TestCanonicalDescriptions:+ def test_descriptions_key_off_known_endpoints(self) -> None:+ descriptions = ZendeskSellSource().get_canonical_descriptions()+ assert descriptions # non-empty+ # Every documented entry must map to a real endpoint name so enrichment lands on the table.+ assert set(descriptions).issubset(set(ENDPOINTS))+ for entry in descriptions.values():+ assert entry["description"]+ assert entry["docs_url"].startswith("https://")diff --git a/posthog/temporal/data_imports/sources/zendesk_sell/zendesk_sell.py b/posthog/temporal/data_imports/sources/zendesk_sell/zendesk_sell.pynew file mode 100644index 000000000000..ee216a7017b4--- /dev/null+++ b/posthog/temporal/data_imports/sources/zendesk_sell/zendesk_sell.py@@ -0,0 +1,190 @@+"""Transport layer for the Zendesk Sell (Base CRM) Core API.++Zendesk Sell's Core API lives at https://api.getbase.com/v2/. It returns a uniform envelope+(`{"items": [{"data": {...}, "meta": {...}}], "meta": {"links": {"next_page": ...}}}`) and paginates+with a 1-based `page` parameter plus `per_page` (max 100). We follow `meta.links.next_page` verbatim+rather than constructing page URLs ourselves, as the API docs instruct — but only after validating+each URL is still pinned to the Zendesk Sell API origin, so a hostile response or poisoned resume+state can't retarget an authenticated request at another host (`_validate_pagination_url`).++Every endpoint is full refresh. The Core API supports `sort_by` ordering but exposes no server-side+`updated_after` / `since` timestamp filter on its list endpoints, so there is no way to fetch only+changed rows cheaply — an "incremental" sort-and-skip would still page through the entire history each+run. True change capture is only available via the separate, queue-based Sync API. We therefore ship+full refresh and leave incremental off until that can be verified against a live account.+"""++import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode, urlsplit++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.zendesk_sell.settings import ZENDESK_SELL_ENDPOINTS++ZENDESK_SELL_BASE_URL = "https://api.getbase.com"+ZENDESK_SELL_HOST = "api.getbase.com"+ZENDESK_SELL_PATH_PREFIX = "/v2/"+PER_PAGE = 100+REQUEST_TIMEOUT_SECONDS = 60+++class ZendeskSellRetryableError(Exception):+ pass+++class ZendeskSellUntrustedURLError(Exception):+ """A pagination URL (resumed or upstream) pointed somewhere other than the Zendesk Sell API."""+++def _validate_pagination_url(url: str) -> str:+ """Pin every authenticated request to the Zendesk Sell API origin.++ Both resumed `next_url` values (loaded from Redis) and upstream `meta.links.next_page` URLs are+ followed verbatim with the customer's bearer token. Validating the scheme, host, and `/v2/` path+ prefix keeps a poisoned resume state or a hostile upstream response from retargeting the request at+ another host and leaking the token (SSRF). Returns the URL unchanged when it is trusted.+ """+ parts = urlsplit(url)+ is_trusted = (+ parts.scheme == "https"+ and parts.netloc == ZENDESK_SELL_HOST+ and parts.path.startswith(ZENDESK_SELL_PATH_PREFIX)+ )+ if not is_trusted:+ raise ZendeskSellUntrustedURLError(+ f"Refusing to follow pagination URL outside {ZENDESK_SELL_BASE_URL}{ZENDESK_SELL_PATH_PREFIX}"+ )+ return url+++class ZendeskSellResumeConfig:+ # Full next-page URL returned by the API. None means "start the endpoint at its first page".+ next_url: str | None = None+++def _get_headers(access_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {access_token}",+ "Accept": "application/json",+ }+++def _build_initial_url(path: str) -> str:+ return f"{ZENDESK_SELL_BASE_URL}{path}?{urlencode({'per_page': PER_PAGE})}"+++@retry(+ retry=retry_if_exception_type((ZendeskSellRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # 429 (rate limit: 10 req/s, 36k/hour) and transient 5xx are safe to retry.+ if response.status_code == 429 or response.status_code >= 500:+ raise ZendeskSellRetryableError(f"Zendesk Sell API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error("Zendesk Sell API error", status=response.status_code, body=response.text, url=url)+ response.raise_for_status()++ return response.json()+++def _extract_records(payload: dict[str, Any]) -> list[dict[str, Any]]:+ """Unwrap each item's `data` object from the collection envelope.++ Every item in the Zendesk Sell envelope carries a `data` object — direct access fails fast on a+ malformed response rather than silently dropping records.+ """+ return [item["data"] for item in payload.get("items", [])]+++def get_rows(+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ZendeskSellResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = ZENDESK_SELL_ENDPOINTS[endpoint]+ headers = _get_headers(access_token)+ # One session reused across every page so urllib3 keeps the connection alive. `redact_values`+ # masks the bearer token in logged URLs and captured request samples. `allow_redirects=False`+ # stops a redirect response from sending the bearer token to another host.+ session = make_tracked_session(redact_values=(access_token,), allow_redirects=False)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ # Resume state comes from Redis — validate before sending the token to it.+ url: str | None = _validate_pagination_url(resume.next_url)+ logger.debug(f"Zendesk Sell: resuming {endpoint} from URL: {url}")+ else:+ url = _build_initial_url(config.path)++ while url:+ payload = _fetch_page(session, url, headers, logger)++ records = _extract_records(payload)+ next_url = payload.get("meta", {}).get("links", {}).get("next_page")+ # The upstream-supplied next-page URL is followed verbatim with the bearer token — pin it to+ # the Zendesk Sell API so a hostile response can't retarget the authenticated request.+ if next_url:+ next_url = _validate_pagination_url(next_url)++ if records:+ yield records++ # Save AFTER yielding so a crash re-yields the last page rather than skipping it; merge dedupes+ # on the primary key. Only persist when there's another page to resume to.+ if next_url:+ resumable_source_manager.save_state(ZendeskSellResumeConfig(next_url=next_url))++ url = next_url+++def zendesk_sell_source(+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ZendeskSellResumeConfig],+) -> SourceResponse:+ config = ZENDESK_SELL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_token=access_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(access_token: str) -> bool:+ """Cheap probe that the access token is genuine: list a single contact."""+ url = f"{ZENDESK_SELL_BASE_URL}/v2/contacts?{urlencode({'per_page': 1})}"+ try:+ session = make_tracked_session(redact_values=(access_token,), allow_redirects=False)+ response = session.get(url, headers=_get_headers(access_token), timeout=10)+ return response.status_code == 200+ except Exception:+ return False