Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement kustomer import source (#62905)

Tom Owers80a0d389085b
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 251ea5a9f9b0..6efcf8113644 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -95,6 +95,7 @@ the row lists both.
| jira | HTTP | requests | ✅ |
| klaviyo | HTTP | requests | ✅ |
| launchdarkly | HTTP | requests | ✅ |
+| kustomer | HTTP | requests | ✅ |
| linear | HTTP | requests | ✅ |
| lever | HTTP | requests | ✅ |
| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |
@@ -256,7 +257,6 @@ doesn't conflict with concurrent PRs.
- hibob
- instagram
- kafka
-- kustomer
- lattice
- lever
- lightspeed_retail
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 813308a4d788..769e4b87afb5 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -740,7 +740,8 @@ class KlaviyoSourceConfig(config.Config):
@config.config
class KustomerSourceConfig(config.Config):
- pass
+ org_name: str
+ api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/kustomer/kustomer.py b/posthog/temporal/data_imports/sources/kustomer/kustomer.py
new file mode 100644
index 000000000000..75bad9390177
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/kustomer/kustomer.py
@@ -0,0 +1,164 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode, urljoin, urlparse
+
+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.kustomer.settings import KUSTOMER_ENDPOINTS
+
+# Kustomer list pages cap at 100 items.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Default rate limit is 300 calls/min; 429s carry x-ratelimit headers but
+# exponential backoff is sufficient.
+MAX_RETRY_ATTEMPTS = 5
+
+
+class KustomerRetryableError(Exception):
+ pass
+
+
+class KustomerResumeConfig:
+ # Kustomer paginates via a JSON:API `links.next` URL (absolutized against
+ # the org host), so the URL is all we persist.
+ next_url: str
+
+
+def _get_session(api_key: str) -> requests.Session:
+ return make_tracked_session(headers={"Authorization": f"Bearer {api_key}"}, redact_values=(api_key,))
+
+
+def _clean_org_name(org_name: str) -> str:
+ """Accept either the bare org subdomain or a pasted full domain/URL."""
+ org = org_name.strip().removeprefix("https://").removeprefix("http://")
+ org = org.split(".")[0].split("/")[0]
+ if not re.fullmatch(r"[a-zA-Z0-9-]+", org):
+ raise ValueError(f"Invalid Kustomer organization name: {org_name}")
+ return org
+
+
+def _base_url(org_name: str) -> str:
+ return f"https://{_clean_org_name(org_name)}.api.kustomerapp.com"
+
+
+def _ensure_same_origin(url: str, base_url: str) -> str:
+ """Reject pagination/resume URLs that leave the org host.
+
+ `links.next` is server-controlled and `urljoin` follows absolute URLs
+ verbatim, so a tampered response could otherwise point our authenticated
+ request (which carries the API key in its Bearer header) at an external host
+ and leak the key. Compare the full origin (scheme + netloc), not a prefix, so
+ look-alike hosts like `org.api.kustomerapp.com.evil.com` are rejected too."""
+ parsed, base = urlparse(url), urlparse(base_url)
+ if (parsed.scheme, parsed.netloc) != (base.scheme, base.netloc):
+ raise ValueError(f"Kustomer URL {url!r} does not stay on the expected host {base_url!r}")
+ return url
+
+
+def validate_credentials(org_name: str, api_key: str) -> bool:
+ """Confirm the API key and org are valid with a cheap one-customer probe.
+
+ Role-scoped keys may lack individual read grants (403); only 401 means the
+ key itself is bad."""
+ try:
+ response = _get_session(api_key).get(
+ f"{_base_url(org_name)}/v1/customers?{urlencode({'page[size]': 1})}",
+ timeout=10,
+ )
+ return response.status_code != 401
+ except Exception:
+ return False
+
+
+def get_rows(
+ org_name: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KustomerResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = KUSTOMER_ENDPOINTS[endpoint]
+ session = _get_session(api_key)
+ base_url = _base_url(org_name)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ # Re-validate the persisted URL so a tampered Redis state can't redirect
+ # our authenticated request off-host.
+ url: str = _ensure_same_origin(resume_config.next_url, base_url)
+ logger.debug(f"Kustomer: resuming {endpoint} from URL: {url}")
+ else:
+ url = f"{base_url}{config.path}?{urlencode({'page[size]': PAGE_SIZE})}"
+
+ @retry(
+ retry=retry_if_exception_type((KustomerRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise KustomerRetryableError(
+ f"Kustomer API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Kustomer API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(url)
+ items = data.get("data", []) or []
+
+ if items:
+ yield items
+
+ next_link = (data.get("links") or {}).get("next")
+ if not next_link or not items:
+ break
+
+ # links.next is typically a relative path; absolutize against the org
+ # host and pin to that origin so an absolute off-host URL can't leak the
+ # API key.
+ next_url = _ensure_same_origin(urljoin(base_url, next_link), base_url)
+ # Save state AFTER yielding the page so a crash re-yields the last page
+ # (merge dedupes on primary key) rather than skipping it.
+ resumable_source_manager.save_state(KustomerResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def kustomer_source(
+ org_name: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KustomerResumeConfig],
+) -> SourceResponse:
+ config = KUSTOMER_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ org_name=org_name,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=[config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/kustomer/settings.py b/posthog/temporal/data_imports/sources/kustomer/settings.py
new file mode 100644
index 000000000000..f2c80f5bd6cf
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/kustomer/settings.py
@@ -0,0 +1,23 @@
+from dataclasses import dataclass
+
+
+@dataclass
+class KustomerEndpointConfig:
+ path: str
+ primary_key: str = "id"
+
+
+# Kustomer's GET list endpoints have no updated-since filter (incremental needs
+# the POST search API with updatedAt windows — a possible follow-up), so every
+# stream is an honest full refresh. JSON:API rows nest fields under
+# `attributes`, so no top-level timestamp is available for partitioning.
+KUSTOMER_ENDPOINTS: dict[str, KustomerEndpointConfig] = {
+ "customers": KustomerEndpointConfig(path="/v1/customers"),
+ "conversations": KustomerEndpointConfig(path="/v1/conversations"),
+ "users": KustomerEndpointConfig(path="/v1/users"),
+ "teams": KustomerEndpointConfig(path="/v1/teams"),
+ "tags": KustomerEndpointConfig(path="/v1/tags"),
+ "brands": KustomerEndpointConfig(path="/v1/brands"),
+}
+
+ENDPOINTS = tuple(KUSTOMER_ENDPOINTS.keys())
diff --git a/posthog/temporal/data_imports/sources/kustomer/source.py b/posthog/temporal/data_imports/sources/kustomer/source.py
index 6de02ef6ab89..04190ad72582 100644
--- a/posthog/temporal/data_imports/sources/kustomer/source.py
+++ b/posthog/temporal/data_imports/sources/kustomer/source.py
@@ -1,29 +1,127 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
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.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import KustomerSourceConfig
+from posthog.temporal.data_imports.sources.kustomer.kustomer import (
+ KustomerResumeConfig,
+ kustomer_source,
+ validate_credentials as validate_kustomer_credentials,
+)
+from posthog.temporal.data_imports.sources.kustomer.settings import ENDPOINTS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class KustomerSource(SimpleSource[KustomerSourceConfig]):
+class KustomerSource(ResumableSource[KustomerSourceConfig, KustomerResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.KUSTOMER
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `org_name` determines the host the stored API key is sent to;
+ # retargeting it must re-require the key.
+ return ["org_name"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Kustomer authentication failed. Please check your API key and organization name.",
+ "403 Client Error: Forbidden for url": "Kustomer denied access. Please check that your API key's roles grant read access to this dataset.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.KUSTOMER,
label="Kustomer",
+ caption="""Enter your Kustomer API credentials to pull your Kustomer support data into the PostHog Data warehouse.
+
+Your organization name is the first part of your Kustomer URL — for `myorg.kustomerapp.com` enter `myorg`. Create an API key in Kustomer under Settings > Security > API Keys with read roles for the data you want to sync (e.g. `org.user.read`).""",
iconPath="/static/services/kustomer.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/kustomer",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="org_name",
+ label="Organization name",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="myorg",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: KustomerSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # GET list endpoints have no updated-since filter; full refresh only.
+ 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: KustomerSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_kustomer_credentials(config.org_name, config.api_key):
+ return True, None
+
+ return False, "Invalid Kustomer API credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KustomerResumeConfig]:
+ return ResumableSourceManager[KustomerResumeConfig](inputs, KustomerResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: KustomerSourceConfig,
+ resumable_source_manager: ResumableSourceManager[KustomerResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return kustomer_source(
+ org_name=config.org_name,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/kustomer/tests/test_kustomer.py b/posthog/temporal/data_imports/sources/kustomer/tests/test_kustomer.py
new file mode 100644
index 000000000000..decdd89b9676
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/kustomer/tests/test_kustomer.py
@@ -0,0 +1,175 @@
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.kustomer.kustomer import (
+ KustomerResumeConfig,
+ _base_url,
+ _clean_org_name,
+ get_rows,
+ kustomer_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.kustomer.settings import ENDPOINTS, KUSTOMER_ENDPOINTS
+
+
+def _make_manager(resume_state: KustomerResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(items: list[dict[str, Any]], next_link: str | None = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ body: dict[str, Any] = {"data": items, "links": {}}
+ if next_link:
+ body["links"]["next"] = next_link
+ resp.json.return_value = body
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+class TestCleanOrgName:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ("myorg", "myorg"),
+ (" myorg ", "myorg"),
+ ("https://myorg.kustomerapp.com", "myorg"),
+ ("myorg.api.kustomerapp.com/v1", "myorg"),
+ ("my-org", "my-org"),
+ ],
+ )
+ def test_valid_org_names(self, value, expected):
+ assert _clean_org_name(value) == expected
+
+ @pytest.mark.parametrize("value", ["", "my org", "org?x=1", "../evil"])
+ def test_invalid_org_names_raise(self, value):
+ with pytest.raises(ValueError):
+ _clean_org_name(value)
+
+ def test_base_url(self):
+ assert _base_url("myorg") == "https://myorg.api.kustomerapp.com"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ # Role-scoped keys without the customers grant still 403; only 401
+ # means the key itself is bad.
+ (403, True),
+ (401, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.kustomer.kustomer.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("myorg", "key") is expected
+
+ @mock.patch("posthog.temporal.data_imports.sources.kustomer.kustomer.make_tracked_session")
+ def test_validate_credentials_rejects_bad_org_without_request(self, mock_session):
+ assert validate_credentials("my org!", "key") is False
+ mock_session.return_value.get.assert_not_called()
+
+
+class TestGetRows:
+ @mock.patch("posthog.temporal.data_imports.sources.kustomer.kustomer.make_tracked_session")
+ def test_paginates_via_links_next_and_absolutizes(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "1"}], next_link="/v1/customers?page%5Bafter%5D=abc&page%5Bsize%5D=100"),
+ _response([{"id": "2"}]),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("myorg", "key", "customers", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["1", "2"]
+ manager.save_state.assert_called_once()
+ saved_url = manager.save_state.call_args.args[0].next_url
+ assert saved_url.startswith("https://myorg.api.kustomerapp.com/v1/customers?")
+ assert mock_session.return_value.get.call_args_list[1].args[0] == saved_url
+
+ @mock.patch("posthog.temporal.data_imports.sources.kustomer.kustomer.make_tracked_session")
+ def test_first_request_uses_endpoint_path_and_page_size(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager()
+ list(get_rows("myorg", "key", "conversations", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ parsed = urlparse(url)
+ assert parsed.path == "/v1/conversations"
+ assert parse_qs(parsed.query)["page[size]"] == ["100"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.kustomer.kustomer.make_tracked_session")
+ def test_resumes_from_saved_state(self, mock_session):
+ mock_session.return_value.get.return_value = _response([{"id": "9"}])
+
+ resume_url = "https://myorg.api.kustomerapp.com/v1/customers?page%5Bafter%5D=resume"
+ manager = _make_manager(KustomerResumeConfig(next_url=resume_url))
+
+ list(get_rows("myorg", "key", "customers", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url
+
+ @pytest.mark.parametrize(
+ "next_link",
+ [
+ "https://attacker.com/steal",
+ "//attacker.com/steal",
+ "http://myorg.api.kustomerapp.com/v1/customers", # downgraded scheme
+ "https://myorg.api.kustomerapp.com.evil.com/v1/customers", # look-alike host
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.kustomer.kustomer.make_tracked_session")
+ def test_off_host_next_link_is_rejected(self, mock_session, next_link):
+ mock_session.return_value.get.return_value = _response([{"id": "1"}], next_link=next_link)
+
+ manager = _make_manager()
+ with pytest.raises(ValueError):
+ list(get_rows("myorg", "key", "customers", mock.MagicMock(), manager))
+
+ manager.save_state.assert_not_called()
+
+ @mock.patch("posthog.temporal.data_imports.sources.kustomer.kustomer.make_tracked_session")
+ def test_off_host_resume_state_is_rejected(self, mock_session):
+ manager = _make_manager(KustomerResumeConfig(next_url="https://attacker.com/steal"))
+
+ with pytest.raises(ValueError):
+ list(get_rows("myorg", "key", "customers", mock.MagicMock(), manager))
+
+ mock_session.return_value.get.assert_not_called()
+
+ @mock.patch("posthog.temporal.data_imports.sources.kustomer.kustomer.make_tracked_session")
+ def test_empty_page_with_next_link_stops(self, mock_session):
+ mock_session.return_value.get.return_value = _response([], next_link="/v1/customers?page%5Bafter%5D=loop")
+
+ manager = _make_manager()
+ batches = list(get_rows("myorg", "key", "customers", mock.MagicMock(), manager))
+
+ assert batches == []
+ assert mock_session.return_value.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+
+class TestKustomerSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = KUSTOMER_ENDPOINTS[endpoint]
+ response = kustomer_source("myorg", "key", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ assert response.sort_mode == "asc"
+ # JSON:API rows nest timestamps under attributes — no partitioning.
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/posthog/temporal/data_imports/sources/kustomer/tests/test_kustomer_source.py b/posthog/temporal/data_imports/sources/kustomer/tests/test_kustomer_source.py
new file mode 100644
index 000000000000..920d16e61119
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/kustomer/tests/test_kustomer_source.py
@@ -0,0 +1,120 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import KustomerSourceConfig
+from posthog.temporal.data_imports.sources.kustomer.kustomer import KustomerResumeConfig
+from posthog.temporal.data_imports.sources.kustomer.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.kustomer.source import KustomerSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestKustomerSource:
+ def setup_method(self):
+ self.source = KustomerSource()
+ self.team_id = 123
+ self.config = KustomerSourceConfig(org_name="myorg", api_key="api-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.KUSTOMER
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Kustomer"
+ assert config.label == "Kustomer"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/kustomer.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["org_name", "api_key"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ def test_org_name_is_a_connection_host_field(self):
+ # The stored API key is sent to the host derived from org_name, so
+ # retargeting it must force re-entry of the secret.
+ assert self.source.connection_host_fields == ["org_name"]
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://myorg.api.kustomerapp.com/v1/customers",
+ "403 Client Error: Forbidden for url: https://myorg.api.kustomerapp.com/v1/users",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ def test_non_retryable_errors_does_not_match_server_errors(self):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(
+ key in "500 Server Error for url: https://myorg.api.kustomerapp.com/v1/customers"
+ for key in non_retryable_errors
+ )
+
+ def test_get_schemas_are_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # GET list endpoints have no updated-since filter; full refresh only.
+ assert all(not schema.supports_incremental for schema in schemas)
+ assert all(not schema.supports_append for schema in schemas)
+ assert all(schema.incremental_fields == [] for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["customers"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "customers"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Kustomer API credentials"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.kustomer.source.validate_kustomer_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.org_name, self.config.api_key)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is KustomerResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.kustomer.source.kustomer_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_kustomer_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "customers"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_kustomer_source.assert_called_once()
+ kwargs = mock_kustomer_source.call_args.kwargs
+ assert kwargs["org_name"] == "myorg"
+ assert kwargs["api_key"] == "api-key"
+ assert kwargs["endpoint"] == "customers"
+ assert kwargs["resumable_source_manager"] is manager