: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 zonka_feedback import source (#68590)
Tom Owers5dc783884196
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex fe4bb08bbdc6..6039e9a0b258 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -324,6 +324,7 @@ the row lists both.| wrike | HTTP | requests | ✅ || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ || zendesk_sell | HTTP | requests | ✅ |+| zonka_feedback | HTTP | requests | ✅ || zoom | HTTP | requests | ✅ || zuora | HTTP | requests | ✅ |@@ -744,7 +745,6 @@ doesn't conflict with concurrent PRs.- zoho_expense- zoho_inventory- zoho_invoice-- zonka_feedback- zoominfo---diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex b32a8a66d66e..f9af8cf2f2a0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3671,7 +3671,8 @@ class ZohoInvoiceSourceConfig(config.Config):@config.configclass ZonkaFeedbackSourceConfig(config.Config):- pass+ auth_token: str+ data_center: Literal["us1", "e", "in"] = config.value(default="us1")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/canonical_descriptions.pynew file mode 100644index 000000000000..81a57b5227be--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/canonical_descriptions.py@@ -0,0 +1,50 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Zonka Feedback API v2.1 docs (https://apidocs.zonkafeedback.com).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "responses": {+ "description": "A single feedback response submitted to a Zonka Feedback survey, including answers and respondent context.",+ "docs_url": "https://apidocs.zonkafeedback.com/",+ "columns": {+ "id": "The unique ID of the response.",+ "surveyId": "The ID of the survey this response was submitted to.",+ "contactId": "The ID of the contact who submitted the response, if known.",+ "channel": "The channel the response was collected through (email, SMS, web, kiosk, etc.).",+ "status": "The completion status of the response (e.g. complete, partial).",+ "language": "The language the survey was answered in.",+ "responseDate": "The timestamp the response was submitted, in ISO 8601 UTC.",+ "location": "The location associated with the response, if any.",+ "device": "The device the response was collected on, if any.",+ "answers": "The list of answers given to the survey's questions.",+ },+ },+ "surveys": {+ "description": "A Zonka Feedback survey — the questionnaire (CSAT, NPS, CES, etc.) distributed to collect feedback.",+ "docs_url": "https://apidocs.zonkafeedback.com/",+ "columns": {+ "id": "The unique ID of the survey.",+ "name": "The name of the survey.",+ "type": "The survey type (e.g. CSAT, NPS, CES).",+ "status": "Whether the survey is active or inactive.",+ "language": "The default language of the survey.",+ "createdOn": "The timestamp the survey was created, in ISO 8601 UTC.",+ "modifiedOn": "The timestamp the survey was last modified, in ISO 8601 UTC.",+ },+ },+ "contacts": {+ "description": "A contact in the Zonka Feedback account — a person surveys can be sent to and whose responses are attributed.",+ "docs_url": "https://apidocs.zonkafeedback.com/",+ "columns": {+ "id": "The unique ID of the contact.",+ "email": "The contact's email address.",+ "phone": "The contact's phone number.",+ "firstName": "The contact's first name.",+ "lastName": "The contact's last name.",+ "createdOn": "The timestamp the contact was created, in ISO 8601 UTC.",+ "modifiedOn": "The timestamp the contact was last modified, in ISO 8601 UTC.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/settings.pynew file mode 100644index 000000000000..d1f0954ac6ac--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/settings.py@@ -0,0 +1,26 @@+from dataclasses import dataclass, field+from typing import Optional+++@dataclass+class ZonkaFeedbackEndpointConfig:+ name: str+ path: str+ # Zonka Feedback object IDs are unique within an account, so `id` is a safe primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ partition_key: Optional[str] = None+++# Zonka Feedback v2.1 account-level list endpoints. All are full-refresh only: the public REST+# list endpoints expose page/page_size pagination but no documented server-side `updated_after`+# date cursor, so there is no genuine incremental cursor to advance.+ZONKA_FEEDBACK_ENDPOINTS: dict[str, ZonkaFeedbackEndpointConfig] = {+ "responses": ZonkaFeedbackEndpointConfig(name="responses", path="/responses"),+ "surveys": ZonkaFeedbackEndpointConfig(name="surveys", path="/surveys"),+ "contacts": ZonkaFeedbackEndpointConfig(name="contacts", path="/contacts"),+}++ENDPOINTS = tuple(ZONKA_FEEDBACK_ENDPOINTS.keys())++# Full refresh only — no endpoint exposes a server-side timestamp filter to drive incremental sync.+INCREMENTAL_FIELDS: dict[str, list] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.pyindex 44a6fed725c1..eb57f6fe318c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py@@ -1,19 +1,46 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ZonkaFeedbackSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.settings import (+ ENDPOINTS,+ ZONKA_FEEDBACK_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.zonka_feedback import (+ DATA_CENTER_IDS,+ ZonkaFeedbackResumeConfig,+ base_url,+ check_access,+ zonka_feedback_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ZonkaFeedbackSource(SimpleSource[ZonkaFeedbackSourceConfig]):+class ZonkaFeedbackSource(ResumableSource[ZonkaFeedbackSourceConfig, ZonkaFeedbackResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ZONKAFEEDBACK@@ -24,7 +51,116 @@ class ZonkaFeedbackSource(SimpleSource[ZonkaFeedbackSourceConfig]):name=SchemaExternalDataSourceType.ZONKA_FEEDBACK,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Zonka Feedback",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Zonka Feedback auth token to pull your survey and feedback data into the PostHog Data warehouse.++An Admin can generate an auth token under **Company Settings → Developers → API** in Zonka Feedback. Select the data center that matches your account's region (shown in the same settings area).+""",iconPath="/static/services/zonka_feedback.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/zonka-feedback",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="auth_token",+ label="Auth token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="data_center",+ label="Data center",+ required=True,+ defaultValue="us1",+ options=[+ SourceFieldSelectConfigOption(label="US (us1.apis.zonkafeedback.com)", value="us1"),+ SourceFieldSelectConfigOption(label="EU (e.apis.zonkafeedback.com)", value="e"),+ SourceFieldSelectConfigOption(label="India (in.apis.zonkafeedback.com)", value="in"),+ ],+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # An invalid or revoked auth token surfaces as a requests HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.+ # The API host varies by data center, so enumerate the known regional hosts; match the stable+ # status text and base host, not the per-request path/query.+ errors: dict[str, str | None] = {}+ for data_center in DATA_CENTER_IDS:+ host = base_url(data_center)+ errors[f"401 Client Error: Unauthorized for url: {host}"] = (+ "Your Zonka Feedback auth token is invalid or has been revoked. Generate a new token "+ "under Company Settings → Developers → API, then reconnect."+ )+ errors[f"403 Client Error: Forbidden for url: {host}"] = (+ "Your Zonka Feedback auth token does not have access to this data. Check the token's "+ "permissions, then reconnect."+ )+ return errors++ def get_schemas(+ self,+ config: ZonkaFeedbackSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Zonka Feedback's list endpoints expose no server-side+ # timestamp filter, so there is no incremental cursor to advance.+ 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: ZonkaFeedbackSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The auth token is account-wide, so a single probe validates access to every schema; there+ # is no per-endpoint scope to check.+ status, message = check_access(config.auth_token, config.data_center)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Zonka Feedback auth token"+ return False, message or "Could not validate Zonka Feedback auth token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZonkaFeedbackResumeConfig]:+ return ResumableSourceManager[ZonkaFeedbackResumeConfig](inputs, ZonkaFeedbackResumeConfig)++ def source_for_pipeline(+ self,+ config: ZonkaFeedbackSourceConfig,+ resumable_source_manager: ResumableSourceManager[ZonkaFeedbackResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in ZONKA_FEEDBACK_ENDPOINTS:+ raise ValueError(f"Unknown Zonka Feedback schema '{inputs.schema_name}'")++ return zonka_feedback_source(+ auth_token=config.auth_token,+ data_center=config.data_center,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback.pynew file mode 100644index 000000000000..e28fa6ba33b6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback.py@@ -0,0 +1,265 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback import zonka_feedback+from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.settings import (+ ENDPOINTS,+ ZONKA_FEEDBACK_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.zonka_feedback import (+ ZonkaFeedbackResumeConfig,+ ZonkaFeedbackRetryableError,+ base_url,+ check_access,+ get_rows,+ zonka_feedback_source,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = zonka_feedback._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: ZonkaFeedbackResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ZonkaFeedbackResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ZonkaFeedbackResumeConfig | None:+ return self._state++ def save_state(self, data: ZonkaFeedbackResumeConfig) -> None:+ self.saved.append(data)+++def _page(items: list[dict]) -> dict[str, Any]:+ return {"result": items}+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, dict], endpoint: str = "responses"+ ) -> list[dict]:+ def fake_fetch(session: Any, url: str, page: int, page_size: int, logger: Any) -> dict:+ return pages[page]++ monkeypatch.setattr(zonka_feedback, "_fetch_page", fake_fetch)+ monkeypatch.setattr(zonka_feedback, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ auth_token="zonka-token",+ data_center="us1",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_page_then_empty_page_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page([{"id": 1}, {"id": 2}]), 2: _page([])})+ assert rows == [{"id": 1}, {"id": 2}]+ # State is saved after page 1 (pointing at page 2); the terminating empty page saves nothing.+ assert [s.next_page for s in manager.saved] == [2]++ def test_follows_pagination_until_empty_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 1: _page([{"id": 1}]),+ 2: _page([{"id": 2}]),+ 3: _page([{"id": 3}]),+ 4: _page([]),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]++ def test_saves_next_page_after_yielding_each_batch(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {1: _page([{"id": 1}]), 2: _page([{"id": 2}]), 3: _page([])}+ self._collect(manager, monkeypatch, pages)+ assert [s.next_page for s in manager.saved] == [2, 3]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(ZonkaFeedbackResumeConfig(next_page=2))+ pages = {+ # Page 1 must never be fetched on resume.+ 2: _page([{"id": 2}]),+ 3: _page([]),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 2}]++ def test_first_page_empty_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page([])})+ assert rows == []+ assert manager.saved == []+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: dict | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body or {}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(ZonkaFeedbackRetryableError):+ _fetch_page_unwrapped(session, "https://us1.apis.zonkafeedback.com/responses", 1, 100, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "https://us1.apis.zonkafeedback.com/responses", 1, 100, MagicMock())++ def test_success_returns_json_body(self) -> None:+ body = _page([{"id": 1}])+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "https://us1.apis.zonkafeedback.com/responses", 1, 100, MagicMock())+ assert result == body++ def test_request_uses_page_and_page_size_params(self) -> None:+ session = self._session_returning(200, _page([]))+ _fetch_page_unwrapped(session, "https://e.apis.zonkafeedback.com/surveys", 3, 100, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"page": 3, "page_size": 100}+++class TestBaseUrl:+ @parameterized.expand(+ [+ ("us", "us1", "https://us1.apis.zonkafeedback.com"),+ ("eu", "e", "https://e.apis.zonkafeedback.com"),+ ("in", "in", "https://in.apis.zonkafeedback.com"),+ ]+ )+ def test_base_url_per_data_center(self, _name: str, data_center: str, expected: str) -> None:+ assert base_url(data_center) == expected++ @parameterized.expand(+ [+ ("path_delimiter", "us1/evil.com"),+ ("fragment", "us1#@evil.com"),+ ("userinfo", "[email protected]"),+ ("unknown_region", "au"),+ ("empty", ""),+ ]+ )+ def test_base_url_rejects_unlisted_data_center(self, _name: str, data_center: str) -> None:+ # A `data_center` outside the allowlist could otherwise retarget the credentialed request at+ # an attacker host and leak the bearer token.+ with pytest.raises(ValueError, match="Unknown Zonka Feedback data center"):+ base_url(data_center)+++class TestCheckAccess:+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ monkeypatch.setattr(zonka_feedback, "make_tracked_session", lambda **kwargs: session)+ return session++ @parameterized.expand(+ [+ ("reachable", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Zonka Feedback returned HTTP 500"),+ ]+ )+ def test_status_mapping(+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ # parameterized.expand can't also receive the `monkeypatch` fixture, so manage our own.+ with pytest.MonkeyPatch.context() as mp:+ self._patch_session(mp, response)+ assert check_access("zonka-token", "us1") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))+ status, message = check_access("zonka-token", "us1")+ assert status == 0+ assert message is not None and "boom" in message+++class TestZonkaFeedbackSourceResponse:+ @parameterized.expand([("responses",), ("surveys",), ("contacts",)])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = zonka_feedback_source(+ auth_token="zonka-token",+ data_center="us1",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # No endpoint exposes a stable creation timestamp we can safely partition on.+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in ZONKA_FEEDBACK_ENDPOINTS.values())+ assert set(ZONKA_FEEDBACK_ENDPOINTS) == set(ENDPOINTS)+++class TestSessionSecurity:+ """Credentialed requests must redact the token and pin redirects off so a 3xx from a+ compromised host can't retarget the bearer token at another origin."""++ def test_get_rows_pins_redirects_and_redacts_token(self, monkeypatch: Any) -> None:+ make_session = MagicMock(return_value=MagicMock())+ monkeypatch.setattr(zonka_feedback, "make_tracked_session", make_session)+ monkeypatch.setattr(zonka_feedback, "_fetch_page", lambda *a, **k: _page([]))++ manager = _FakeResumableManager()+ list(+ get_rows(+ auth_token="secret-token",+ data_center="us1",+ endpoint="responses",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ )+ assert make_session.call_args.kwargs["redact_values"] == ("secret-token",)+ assert make_session.call_args.kwargs["allow_redirects"] is False++ def test_check_access_pins_redirects_and_redacts_token(self, monkeypatch: Any) -> None:+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ session = MagicMock()+ session.get.return_value = response+ make_session = MagicMock(return_value=session)+ monkeypatch.setattr(zonka_feedback, "make_tracked_session", make_session)++ check_access("secret-token", "us1")+ assert make_session.call_args.kwargs["redact_values"] == ("secret-token",)+ assert make_session.call_args.kwargs["allow_redirects"] is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback_source.pynew file mode 100644index 000000000000..adf0095d31df--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback_source.py@@ -0,0 +1,171 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ZonkaFeedbackSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.source import ZonkaFeedbackSource+from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.zonka_feedback import (+ ZonkaFeedbackResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestZonkaFeedbackSource:+ def setup_method(self) -> None:+ self.source = ZonkaFeedbackSource()+ self.team_id = 123+ self.config = ZonkaFeedbackSourceConfig(auth_token="zonka-token", data_center="us1")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.ZONKAFEEDBACK++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Zonka Feedback"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible — it must not carry the scaffolding flag.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/zonka-feedback"++ input_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ select_names = [f.name for f in config.fields if isinstance(f, SourceFieldSelectConfig)]+ assert input_names == ["auth_token"]+ assert select_names == ["data_center"]++ def test_auth_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "auth_token")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_data_center_options_cover_known_regions(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "data_center")+ assert {o.value for o in field.options} == {"us1", "e", "in"}+ assert field.defaultValue == "us1"++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["surveys"])+ assert len(schemas) == 1+ assert schemas[0].name == "surveys"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ (+ "responses_401",+ "401 Client Error: Unauthorized for url: https://us1.apis.zonkafeedback.com/responses?page=1&page_size=100",+ ),+ (+ "surveys_403",+ "403 Client Error: Forbidden for url: https://e.apis.zonkafeedback.com/surveys?page=2&page_size=100",+ ),+ (+ "contacts_401",+ "401 Client Error: Unauthorized for url: https://in.apis.zonkafeedback.com/contacts?page=1&page_size=100",+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://us1.apis.zonkafeedback.com/responses",+ ),+ ("read_timeout", "HTTPSConnectionPool(host='us1.apis.zonkafeedback.com', port=443): Read timed out."),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://e.apis.zonkafeedback.com/surveys"),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @parameterized.expand(+ [+ ("reachable", 200, True, None),+ ("unauthorized", 401, False, "Invalid Zonka Feedback auth token"),+ ("forbidden", 403, False, "Invalid Zonka Feedback auth token"),+ ("server_error", 500, False, "Zonka Feedback returned HTTP 500"),+ ("connection_error", 0, False, "Could not connect to Zonka Feedback: boom"),+ ]+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.source.check_access")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_check: mock.MagicMock,+ ) -> None:+ message = (+ "Zonka Feedback returned HTTP 500"+ if status == 500+ else ("Could not connect to Zonka Feedback: boom" if status == 0 else None)+ )+ mock_check.return_value = (status, message)+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)+ assert is_valid is expected_valid+ assert returned == expected_message++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.source.check_access")+ def test_validate_credentials_probes_the_auth_token(self, mock_check: mock.MagicMock) -> None:+ # The auth token is account-wide, so validation probes the token, not a per-schema scope.+ mock_check.return_value = (200, None)+ self.source.validate_credentials(self.config, self.team_id, schema_name="surveys")+ mock_check.assert_called_once_with("zonka-token", "us1")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ZonkaFeedbackResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.source.zonka_feedback_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "responses"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["auth_token"] == "zonka-token"+ assert kwargs["data_center"] == "us1"+ assert kwargs["endpoint"] == "responses"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Zonka Feedback schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/zonka_feedback.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/zonka_feedback.pynew file mode 100644index 000000000000..199d03d2c9cb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/zonka_feedback.py@@ -0,0 +1,172 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.settings import (+ ZONKA_FEEDBACK_ENDPOINTS,+)++# Zonka Feedback hosts data per region; the account's data center is the subdomain of the API host.+# US=us1, EU=e, IN=in are the documented, verifiable identifiers.+DATA_CENTER_IDS: tuple[str, ...] = ("us1", "e", "in")+# The list endpoints default to 25 items per page and allow overriding the page size. We request a+# larger page to cut round trips; pagination terminates on the first empty page, so the request is+# correct whether or not the server honours the larger size.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an auth token is genuine. The admin-generated token is account-wide,+# so one probe validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/surveys"+++class ZonkaFeedbackRetryableError(Exception):+ pass+++class ZonkaFeedbackResumeConfig:+ # Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.+ next_page: int = 1+++def base_url(data_center: str) -> str:+ # Validate against the fixed allowlist before interpolating: a `data_center` carrying URL+ # delimiters (`/`, `#`, `@`) could otherwise retarget the request at an attacker host and leak+ # the bearer token during validation or sync.+ if data_center not in DATA_CENTER_IDS:+ raise ValueError("Unknown Zonka Feedback data center")+ return f"https://{data_center}.apis.zonkafeedback.com"+++def _headers(auth_token: str) -> dict[str, str]:+ # Zonka Feedback expects the admin-generated auth token as a Bearer credential.+ return {"Authorization": f"Bearer {auth_token}", "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((ZonkaFeedbackRetryableError, 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,+ page: int,+ page_size: int,+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(+ url,+ params={"page": page, "page_size": page_size},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise ZonkaFeedbackRetryableError(+ f"Zonka Feedback API error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ # Don't log `response.text`: error bodies from these endpoints can echo contact/feedback PII+ # into logs that sit outside the warehouse tables' access controls. Status and the redacted+ # URL are enough to diagnose.+ logger.error(f"Zonka Feedback API error: status={response.status_code}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ auth_token: str,+ data_center: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ZonkaFeedbackResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = ZONKA_FEEDBACK_ENDPOINTS[endpoint]+ url = f"{base_url(data_center)}{config.path}"+ # `redact_values` masks the auth token in logged URLs and captured samples. `allow_redirects=False`+ # pins the credentialed request to the validated Zonka Feedback host so a 3xx from a compromised+ # or misconfigured endpoint can't retarget the bearer token at another origin.+ session = make_tracked_session(headers=_headers(auth_token), redact_values=(auth_token,), allow_redirects=False)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume else 1+ if resume and resume.next_page > 1:+ logger.debug(f"Zonka Feedback: resuming {endpoint} from page {page}")++ while True:+ data = _fetch_page(session, url, page, PAGE_SIZE, logger)++ # `result` is the documented envelope key for paginated list endpoints; missing it means a+ # malformed response, so fail loudly rather than silently advancing past lost rows.+ rows = data["result"]++ # There is no `has_more` flag, and the server may cap the page size below what we request, so+ # short pages are not a reliable stop signal — terminate on the first empty page instead.+ if not rows:+ break++ yield rows++ page += 1+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(ZonkaFeedbackResumeConfig(next_page=page))+++def zonka_feedback_source(+ auth_token: str,+ data_center: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ZonkaFeedbackResumeConfig],+) -> SourceResponse:+ config = ZONKA_FEEDBACK_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ auth_token=auth_token,+ data_center=data_center,+ 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 check_access(auth_token: str, data_center: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single list endpoint to validate the auth token.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(auth_token), redact_values=(auth_token,), allow_redirects=False)+ try:+ response = session.get(f"{base_url(data_center)}{path}", params={"page": 1, "page_size": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Zonka Feedback: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Zonka Feedback returned HTTP {response.status_code}"++ return 200, None