: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 freshdesk import source (#61140)
Tom Owersfb7cb2fff07f
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex a20073b44a5d..869baf2fd26a 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -63,6 +63,7 @@ the row lists both.| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) || doit | HTTP | requests | ✅ || drip | HTTP | requests | ✅ |+| freshdesk | HTTP | requests | ✅ || eventbrite | HTTP | requests | ✅ || github | HTTP | requests | ✅ || google_ads | gRPC | google-ads (googleads.client) | ✅ |@@ -173,7 +174,6 @@ doesn't conflict with concurrent PRs.- elasticsearch- facebook_pages- firebase-- freshdesk- freshsales- front- fullstorydiff --git a/posthog/temporal/data_imports/sources/freshdesk/freshdesk.py b/posthog/temporal/data_imports/sources/freshdesk/freshdesk.pynew file mode 100644index 000000000000..d5226a51524d--- /dev/null+++ b/posthog/temporal/data_imports/sources/freshdesk/freshdesk.py@@ -0,0 +1,217 @@+import base64+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, 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.freshdesk.settings import (+ FRESHDESK_ENDPOINTS,+ PER_PAGE,+ FreshdeskEndpointConfig,+)++REQUEST_TIMEOUT = 60+VALIDATE_TIMEOUT = 10+MAX_RETRIES = 5+MAX_RETRY_WAIT = 60.0++_EXPONENTIAL_WAIT = wait_exponential_jitter(initial=1, max=MAX_RETRY_WAIT)+++class FreshdeskRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++def _parse_retry_after(value: str | None) -> float | None:+ """Parse a Retry-After header. Freshdesk sends an integer number of seconds."""+ if not value:+ return None+ try:+ return float(value)+ except ValueError:+ return None+++def _retry_wait(retry_state: RetryCallState) -> float:+ """Honor a server-provided Retry-After (capped); otherwise fall back to exponential jitter."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, FreshdeskRetryableError) and exc.retry_after is not None:+ return min(exc.retry_after, MAX_RETRY_WAIT)+ return _EXPONENTIAL_WAIT(retry_state)+++class FreshdeskResumeConfig:+ next_url: str+++def normalize_subdomain(domain: str) -> str:+ """Accept either a bare subdomain ("acme") or a full host ("acme.freshdesk.com")."""+ domain = domain.strip().removeprefix("https://").removeprefix("http://")+ domain = domain.split("/")[0]+ return domain.removesuffix(".freshdesk.com")+++def _base_url(subdomain: str) -> str:+ return f"https://{normalize_subdomain(subdomain)}.freshdesk.com"+++def _get_headers(api_key: str) -> dict[str, str]:+ # Freshdesk uses HTTP Basic auth with the API key as the username and any+ # non-empty string as the password.+ token = base64.b64encode(f"{api_key}:X".encode("ascii")).decode("ascii")+ return {"Authorization": f"Basic {token}", "Content-Type": "application/json"}+++def _format_updated_since(value: Any) -> str:+ """Format an incremental cursor value as the ISO 8601 UTC string Freshdesk expects."""+ if isinstance(value, datetime):+ utc = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def build_initial_url(+ subdomain: str,+ config: FreshdeskEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str:+ params: dict[str, str] = {"per_page": str(PER_PAGE)}+ params.update(config.extra_params)++ if should_use_incremental_field and config.updated_since_param and db_incremental_field_last_value:+ params[config.updated_since_param] = _format_updated_since(db_incremental_field_last_value)++ return f"{_base_url(subdomain)}{config.path}?{urlencode(params)}"+++def extract_items(data: Any, config: FreshdeskEndpointConfig) -> list[dict]:+ """Most Freshdesk list endpoints return a bare JSON array; a few wrap it in an object."""+ if isinstance(data, list):+ return data+ if isinstance(data, dict):+ if config.data_key and isinstance(data.get(config.data_key), list):+ return data[config.data_key]+ # `results` is used by Freshdesk's search endpoints; defensive fallback.+ if isinstance(data.get("results"), list):+ return data["results"]+ return []+++def get_rows(+ api_key: str,+ subdomain: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FreshdeskResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict]]:+ config = FRESHDESK_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ url: Optional[str] = resume.next_url+ logger.debug(f"Freshdesk: resuming from URL: {url}")+ else:+ url = build_initial_url(subdomain, config, should_use_incremental_field, db_incremental_field_last_value)++ @retry(+ retry=retry_if_exception_type((FreshdeskRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+ )+ def fetch_page(page_url: str) -> tuple[Any, Optional[str]]:+ response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT)++ # Freshdesk throttles with 429 and a Retry-After header; honor it when present.+ if response.status_code == 429:+ raise FreshdeskRetryableError(+ f"Freshdesk API rate limited: url={page_url}",+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),+ )++ # Transient upstream issues surface as 5xx.+ if response.status_code >= 500:+ raise FreshdeskRetryableError(+ f"Freshdesk API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ logger.error(f"Freshdesk API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ next_url = response.links.get("next", {}).get("url")+ return response.json(), next_url++ while url:+ data, next_url = fetch_page(url)++ items = extract_items(data, config)+ if items:+ yield items++ if not next_url:+ break++ # Save state AFTER yielding so a crash re-yields the last page (merge dedupes on+ # primary key) rather than skipping it.+ resumable_source_manager.save_state(FreshdeskResumeConfig(next_url=next_url))+ url = next_url+++def freshdesk_source(+ api_key: str,+ subdomain: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FreshdeskResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = FRESHDESK_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ subdomain=subdomain,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=["id"],+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(subdomain: str, api_key: str) -> Optional[int]:+ """Probe the Freshdesk API. Returns the HTTP status code, or ``None`` on a connection error."""+ url = f"{_base_url(subdomain)}/api/v2/tickets?per_page=1"+ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=VALIDATE_TIMEOUT)+ except Exception:+ return None++ return response.status_codediff --git a/posthog/temporal/data_imports/sources/freshdesk/settings.py b/posthog/temporal/data_imports/sources/freshdesk/settings.pynew file mode 100644index 000000000000..c4d13f7fda76--- /dev/null+++ b/posthog/temporal/data_imports/sources/freshdesk/settings.py@@ -0,0 +1,95 @@+"""Freshdesk source settings and endpoint catalog."""++from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++PER_PAGE = 100+++@dataclass+class FreshdeskEndpointConfig:+ name: str+ path: str+ # Server-side incremental filter param name (e.g. "updated_since", "_updated_since").+ # ``None`` means the endpoint has no server-side timestamp filter -> full refresh only.+ updated_since_param: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+ # Stable field used for datetime partitioning. Always a creation timestamp, never a+ # mutable field like ``updated_at`` (partitions must not rewrite on every sync).+ partition_key: Optional[str] = None+ # Extra static query params (e.g. ordering on incremental endpoints).+ extra_params: dict[str, str] = field(default_factory=dict)+ # Key the list lives under when the response is an object rather than a bare array.+ data_key: Optional[str] = None+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++# Top-level Freshdesk v2 endpoints. Fan-out resources (ticket conversations, solution+# articles) are intentionally omitted from this first cut — see source.py module note.+FRESHDESK_ENDPOINTS: dict[str, FreshdeskEndpointConfig] = {+ "tickets": FreshdeskEndpointConfig(+ name="tickets",+ path="/api/v2/tickets",+ # Freshdesk caps the tickets list at ~300 pages per query. Syncing incrementally on+ # `updated_since` keeps each window small and lets the watermark advance across runs,+ # which is the documented way to page beyond that cap.+ updated_since_param="updated_since",+ default_incremental_field="updated_at",+ incremental_fields=[_datetime_incremental_field("updated_at")],+ partition_key="created_at",+ # Force ascending updated_at so the incremental watermark advances monotonically.+ extra_params={"order_by": "updated_at", "order_type": "asc"},+ ),+ "contacts": FreshdeskEndpointConfig(+ name="contacts",+ path="/api/v2/contacts",+ # Freshdesk uses the underscore-prefixed `_updated_since` on the contacts endpoint.+ updated_since_param="_updated_since",+ default_incremental_field="updated_at",+ incremental_fields=[_datetime_incremental_field("updated_at")],+ partition_key="created_at",+ ),+ "companies": FreshdeskEndpointConfig(+ name="companies",+ path="/api/v2/companies",+ partition_key="created_at",+ ),+ "agents": FreshdeskEndpointConfig(name="agents", path="/api/v2/agents"),+ "groups": FreshdeskEndpointConfig(name="groups", path="/api/v2/groups"),+ "roles": FreshdeskEndpointConfig(name="roles", path="/api/v2/roles"),+ "products": FreshdeskEndpointConfig(name="products", path="/api/v2/products"),+ "skills": FreshdeskEndpointConfig(name="skills", path="/api/v2/skills", data_key="skills"),+ "ticket_fields": FreshdeskEndpointConfig(name="ticket_fields", path="/api/v2/ticket_fields"),+ "time_entries": FreshdeskEndpointConfig(+ name="time_entries",+ path="/api/v2/time_entries",+ partition_key="created_at",+ ),+ "satisfaction_ratings": FreshdeskEndpointConfig(+ name="satisfaction_ratings",+ path="/api/v2/surveys/satisfaction_ratings",+ partition_key="created_at",+ ),+ "sla_policies": FreshdeskEndpointConfig(name="sla_policies", path="/api/v2/sla_policies"),+ "business_hours": FreshdeskEndpointConfig(name="business_hours", path="/api/v2/business_hours"),+ "canned_response_folders": FreshdeskEndpointConfig(+ name="canned_response_folders", path="/api/v2/canned_response_folders"+ ),+}++ENDPOINTS = tuple(FRESHDESK_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in FRESHDESK_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/freshdesk/source.py b/posthog/temporal/data_imports/sources/freshdesk/source.pyindex 794f89651989..291b2d9ece54 100644--- a/posthog/temporal/data_imports/sources/freshdesk/source.py+++ b/posthog/temporal/data_imports/sources/freshdesk/source.py@@ -1,29 +1,162 @@-from typing import cast+import re+from typing import Optional, castfrom 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, ResumableSourcefrom 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.freshdesk.freshdesk import (+ FreshdeskResumeConfig,+ freshdesk_source,+ normalize_subdomain,+ validate_credentials as validate_freshdesk_credentials,+)+from posthog.temporal.data_imports.sources.freshdesk.settings import FRESHDESK_ENDPOINTSfrom posthog.temporal.data_imports.sources.generated_configs import FreshdeskSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType+# This first cut covers Freshdesk's top-level v2 endpoints only. Fan-out resources+# (ticket conversations, solution articles/folders/categories) and webhook-driven+# deltas are deliberately left out: Freshdesk has no documented public REST API for+# programmatic webhook management (webhooks are configured through admin automation+# rules), so they can't be wired up reliably without live verification.++_SUBDOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9-]+$")+@SourceRegistry.register-class FreshdeskSource(SimpleSource[FreshdeskSourceConfig]):+class FreshdeskSource(ResumableSource[FreshdeskSourceConfig, FreshdeskResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FRESHDESK+ @property+ def connection_host_fields(self) -> list[str]:+ # Freshdesk's connection target is the subdomain, not a `host` field. Editing it on an+ # existing source must force the API key to be re-entered.+ return ["subdomain"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Freshdesk authentication failed. Please check your API key and domain.",+ "403 Client Error: Forbidden for url": "Your Freshdesk API key does not have permission for this resource. Check the agent's role/scope.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FRESHDESK,label="Freshdesk",+ caption="""Enter your Freshdesk domain and API key to pull your Freshdesk support data into the PostHog Data warehouse.++Your **domain** is the subdomain in your Freshdesk URL — e.g. `acme` for `acme.freshdesk.com`.++Your **API key** is on your Freshdesk profile settings page (click your profile picture → **Profile settings**; the API key is shown in the right sidebar).""",iconPath="/static/services/freshdesk.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/freshdesk",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Freshdesk domain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: FreshdeskSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=name,+ # Only the endpoints with a genuine server-side `updated_since` filter+ # support incremental sync; everything else is full refresh.+ supports_incremental=endpoint.updated_since_param is not None,+ supports_append=endpoint.updated_since_param is not None,+ incremental_fields=endpoint.incremental_fields,+ )+ for name, endpoint in FRESHDESK_ENDPOINTS.items()+ ]+ 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: FreshdeskSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if not _SUBDOMAIN_REGEX.match(normalize_subdomain(config.subdomain)):+ return False, "Freshdesk domain is invalid"++ status = validate_freshdesk_credentials(config.subdomain, config.api_key)++ if status == 200:+ return True, None++ # A valid key that simply lacks scope for the probe endpoint returns 403. Accept it at+ # source-create (schema_name is None) — users may only grant the scopes they want to sync.+ if status == 403 and schema_name is None:+ return True, None++ # schema_name is set: a 403 means the key lacks permission for this specific resource.+ if status == 403:+ return (+ False,+ "Your Freshdesk API key does not have permission for this resource. Check the agent's role/scope.",+ )++ if status == 401:+ return False, "Freshdesk authentication failed. Please check your API key and domain."++ return False, "Could not connect to Freshdesk. Please check your domain and API key."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FreshdeskResumeConfig]:+ return ResumableSourceManager[FreshdeskResumeConfig](inputs, FreshdeskResumeConfig)++ def source_for_pipeline(+ self,+ config: FreshdeskSourceConfig,+ resumable_source_manager: ResumableSourceManager[FreshdeskResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return freshdesk_source(+ api_key=config.api_key,+ subdomain=config.subdomain,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/posthog/temporal/data_imports/sources/freshdesk/tests/test_freshdesk.py b/posthog/temporal/data_imports/sources/freshdesk/tests/test_freshdesk.pynew file mode 100644index 000000000000..8d482c71253a--- /dev/null+++ b/posthog/temporal/data_imports/sources/freshdesk/tests/test_freshdesk.py@@ -0,0 +1,224 @@+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest import mock++import requests+import structlog++from posthog.temporal.data_imports.sources.freshdesk.freshdesk import (+ FreshdeskResumeConfig,+ _format_updated_since,+ _parse_retry_after,+ build_initial_url,+ extract_items,+ get_rows,+ normalize_subdomain,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.freshdesk.settings import FRESHDESK_ENDPOINTS++logger = structlog.get_logger()++PATCH_SESSION = "posthog.temporal.data_imports.sources.freshdesk.freshdesk.make_tracked_session"+++class FakeResponse:+ def __init__(+ self,+ json_data: Any = None,+ status_code: int = 200,+ links: Optional[dict] = None,+ text: str = "",+ headers: Optional[dict] = None,+ ) -> None:+ self._json = json_data+ self.status_code = status_code+ self.ok = 200 <= status_code < 400+ self.links = links or {}+ self.text = text+ self.headers = headers or {}++ def json(self) -> Any:+ return self._json++ def raise_for_status(self) -> None:+ if not self.ok:+ real_response = requests.Response()+ real_response.status_code = self.status_code+ raise requests.HTTPError(f"{self.status_code} Client Error", response=real_response)+++class FakeResumableManager:+ def __init__(self, resume: Optional[FreshdeskResumeConfig] = None) -> None:+ self._resume = resume+ self.saved: list[FreshdeskResumeConfig] = []++ def can_resume(self) -> bool:+ return self._resume is not None++ def load_state(self) -> Optional[FreshdeskResumeConfig]:+ return self._resume++ def save_state(self, data: FreshdeskResumeConfig) -> None:+ self.saved.append(data)+++class TestNormalizeSubdomain:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("acme", "acme"),+ ("acme.freshdesk.com", "acme"),+ ("https://acme.freshdesk.com", "acme"),+ ("http://acme.freshdesk.com/", "acme"),+ (" acme ", "acme"),+ ("acme.freshdesk.com/a/tickets", "acme"),+ ],+ )+ def test_normalize_subdomain(self, raw: str, expected: str) -> None:+ assert normalize_subdomain(raw) == expected+++class TestFormatUpdatedSince:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ (date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("some-cursor", "some-cursor"),+ ],+ )+ def test_format_updated_since(self, value: Any, expected: str) -> None:+ assert _format_updated_since(value) == expected++ def test_no_offset_suffix(self) -> None:+ assert "+00:00" not in _format_updated_since(datetime(2026, 3, 4, tzinfo=UTC))+++class TestParseRetryAfter:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("30", 30.0),+ ("0", 0.0),+ (None, None),+ ("", None),+ ("not-a-number", None),+ ],+ )+ def test_parse_retry_after(self, value: Optional[str], expected: Optional[float]) -> None:+ assert _parse_retry_after(value) == expected+++class TestBuildInitialUrl:+ def test_full_refresh_has_per_page_only(self) -> None:+ url = build_initial_url("acme", FRESHDESK_ENDPOINTS["companies"], False, None)+ assert url.startswith("https://acme.freshdesk.com/api/v2/companies?")+ assert "per_page=100" in url+ assert "updated_since" not in url++ def test_tickets_incremental_uses_updated_since_and_ordering(self) -> None:+ url = build_initial_url("acme", FRESHDESK_ENDPOINTS["tickets"], True, datetime(2026, 3, 4, tzinfo=UTC))+ assert "updated_since=2026-03-04T00%3A00%3A00Z" in url+ assert "order_by=updated_at" in url+ assert "order_type=asc" in url++ def test_contacts_incremental_uses_underscore_param(self) -> None:+ url = build_initial_url("acme", FRESHDESK_ENDPOINTS["contacts"], True, datetime(2026, 3, 4, tzinfo=UTC))+ assert "_updated_since=2026-03-04T00%3A00%3A00Z" in url++ def test_incremental_without_last_value_omits_filter(self) -> None:+ url = build_initial_url("acme", FRESHDESK_ENDPOINTS["tickets"], True, None)+ assert "updated_since" not in url++ def test_full_refresh_endpoint_ignores_incremental_flag(self) -> None:+ # `companies` has no server-side filter, so it never gets an updated_since param.+ url = build_initial_url("acme", FRESHDESK_ENDPOINTS["companies"], True, datetime(2026, 3, 4, tzinfo=UTC))+ assert "updated_since" not in url+++class TestExtractItems:+ def test_bare_array(self) -> None:+ assert extract_items([{"id": 1}], FRESHDESK_ENDPOINTS["tickets"]) == [{"id": 1}]++ def test_data_key_object(self) -> None:+ assert extract_items({"skills": [{"id": 1}]}, FRESHDESK_ENDPOINTS["skills"]) == [{"id": 1}]++ def test_results_fallback(self) -> None:+ assert extract_items({"results": [{"id": 9}]}, FRESHDESK_ENDPOINTS["tickets"]) == [{"id": 9}]++ def test_unknown_shape_returns_empty(self) -> None:+ assert extract_items({"meta": {}}, FRESHDESK_ENDPOINTS["tickets"]) == []+++class TestGetRows:+ def test_paginates_via_link_header_and_saves_state(self) -> None:+ next_url = "https://acme.freshdesk.com/api/v2/tickets?per_page=100&page=2"+ responses = [+ FakeResponse([{"id": 1}], links={"next": {"url": next_url}}),+ FakeResponse([{"id": 2}], links={}),+ ]+ manager = FakeResumableManager()+ session = mock.MagicMock()+ session.get.side_effect = responses++ with mock.patch(PATCH_SESSION, return_value=session):+ rows = list(get_rows("key", "acme", "tickets", logger, manager)) # type: ignore[arg-type]++ assert rows == [[{"id": 1}], [{"id": 2}]]+ # State saved once, after the first (only non-terminal) page.+ assert manager.saved == [FreshdeskResumeConfig(next_url=next_url)]++ def test_single_page_saves_no_state(self) -> None:+ manager = FakeResumableManager()+ session = mock.MagicMock()+ session.get.side_effect = [FakeResponse([{"id": 1}], links={})]++ with mock.patch(PATCH_SESSION, return_value=session):+ rows = list(get_rows("key", "acme", "agents", logger, manager)) # type: ignore[arg-type]++ assert rows == [[{"id": 1}]]+ assert manager.saved == []++ def test_resumes_from_saved_state(self) -> None:+ resume_url = "https://acme.freshdesk.com/api/v2/tickets?per_page=100&page=5"+ manager = FakeResumableManager(resume=FreshdeskResumeConfig(next_url=resume_url))+ session = mock.MagicMock()+ session.get.side_effect = [FakeResponse([{"id": 50}], links={})]++ with mock.patch(PATCH_SESSION, return_value=session):+ rows = list(get_rows("key", "acme", "tickets", logger, manager)) # type: ignore[arg-type]++ assert rows == [[{"id": 50}]]+ # First request must hit the resumed URL, not a freshly-built initial URL.+ assert session.get.call_args_list[0].args[0] == resume_url++ @pytest.mark.parametrize("status_code", [401, 403, 404])+ def test_non_retryable_status_raises(self, status_code: int) -> None:+ manager = FakeResumableManager()+ session = mock.MagicMock()+ session.get.side_effect = [FakeResponse(status_code=status_code, text="boom")]++ with mock.patch(PATCH_SESSION, return_value=session):+ with pytest.raises(requests.HTTPError):+ list(get_rows("key", "acme", "tickets", logger, manager)) # type: ignore[arg-type]+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code", [200, 401, 403])+ def test_returns_status_code(self, status_code: int) -> None:+ session = mock.MagicMock()+ session.get.return_value = FakeResponse(status_code=status_code)++ with mock.patch(PATCH_SESSION, return_value=session):+ assert validate_credentials("acme", "key") == status_code++ def test_connection_error_returns_none(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = requests.ConnectionError("nope")++ with mock.patch(PATCH_SESSION, return_value=session):+ assert validate_credentials("acme", "key") is Nonediff --git a/posthog/temporal/data_imports/sources/freshdesk/tests/test_freshdesk_source.py b/posthog/temporal/data_imports/sources/freshdesk/tests/test_freshdesk_source.pynew file mode 100644index 000000000000..9f9f664048c7--- /dev/null+++ b/posthog/temporal/data_imports/sources/freshdesk/tests/test_freshdesk_source.py@@ -0,0 +1,150 @@+from typing import Optional++import pytest+from unittest import mock++import structlog++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.freshdesk.freshdesk import FreshdeskResumeConfig+from posthog.temporal.data_imports.sources.freshdesk.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.freshdesk.source import FreshdeskSource+from posthog.temporal.data_imports.sources.generated_configs import FreshdeskSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType++PATCH_VALIDATE = "posthog.temporal.data_imports.sources.freshdesk.source.validate_freshdesk_credentials"+++def _make_inputs(schema_name: str = "tickets") -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-1",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestFreshdeskSource:+ def setup_method(self) -> None:+ self.source = FreshdeskSource()+ self.team_id = 1+ self.config = FreshdeskSourceConfig(subdomain="acme", api_key="key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.FRESHDESK++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Freshdesk"+ assert config.label == "Freshdesk"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/freshdesk.png"++ fields = config.fields+ assert len(fields) == 2+ subdomain_field, api_key_field = fields+ assert isinstance(subdomain_field, SourceFieldInputConfig)+ assert subdomain_field.name == "subdomain"+ assert subdomain_field.type == SourceFieldInputConfigType.TEXT+ assert subdomain_field.secret is False+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error: Forbidden for url"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_covers_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "name, supports_incremental",+ [+ ("tickets", True),+ ("contacts", True),+ ("companies", False),+ ("agents", False),+ ("satisfaction_ratings", False),+ ],+ )+ def test_schema_incremental_support(self, name: str, supports_incremental: bool) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ schema = schemas[name]+ assert schema.supports_incremental is supports_incremental+ assert schema.supports_append is supports_incremental+ if supports_incremental:+ assert [f["field"] for f in schema.incremental_fields] == ["updated_at"]++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["tickets"])+ assert len(schemas) == 1+ assert schemas[0].name == "tickets"++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "subdomain, status, schema_name, expected_valid",+ [+ ("acme", 200, None, True),+ ("acme", 403, None, True), # missing scope at source-create is accepted+ ("acme", 403, "tickets", False), # missing scope for a specific schema fails+ ("acme", 401, None, False),+ ("acme", None, None, False), # connection error+ ("invalid domain!", 200, None, False), # domain regex rejects before probing+ ],+ )+ def test_validate_credentials(+ self, subdomain: str, status: Optional[int], schema_name: Optional[str], expected_valid: bool+ ) -> None:+ config = FreshdeskSourceConfig(subdomain=subdomain, api_key="key")+ with mock.patch(PATCH_VALIDATE, return_value=status) as mock_validate:+ is_valid, _ = self.source.validate_credentials(config, self.team_id, schema_name)++ assert is_valid is expected_valid+ if "!" in subdomain or " " in subdomain:+ mock_validate.assert_not_called()++ def test_get_resumable_source_manager_binds_data_class(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is FreshdeskResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = _make_inputs("tickets")+ manager = self.source.get_resumable_source_manager(inputs)++ response = self.source.source_for_pipeline(self.config, manager, inputs)++ assert response.name == "tickets"+ assert response.primary_keys == ["id"]+ # tickets partitions on its stable created_at field.+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ def test_source_for_pipeline_full_refresh_endpoint_has_no_partition(self) -> None:+ inputs = _make_inputs("agents")+ manager = self.source.get_resumable_source_manager(inputs)++ response = self.source.source_for_pipeline(self.config, manager, inputs)++ assert response.name == "agents"+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 9a044cf9c758..1c6652ab6193 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -348,7 +348,8 @@ class FirebaseSourceConfig(config.Config):@config.configclass FreshdeskSourceConfig(config.Config):- pass+ subdomain: str+ api_key: str@config.configdiff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex 569f023849d6..01cc0ed61409 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -763,8 +763,8 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer)# Some sources keep their connection target in a differently named field (e.g. Okta's- # `okta_domain`). Changing one would send the preserved credential to a new host — the same- # exfiltration risk as a `host` change — so require re-entry too.+ # `okta_domain`, Freshdesk's `subdomain`). Changing one would send the preserved credential+ # to a new host — the same exfiltration risk as a `host` change — so require re-entry too.connection_host_changed = connection_host_changed or any(field in incoming_job_inputs and incoming_job_inputs[field] != existing_job_inputs.get(field)for field in source.connection_host_fieldsdiff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex 2fa409048732..dd90eb79f803 100644--- a/products/data_warehouse/backend/api/test/test_external_data_source.py+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py@@ -4010,6 +4010,63 @@ class TestExternalDataSource(APIBaseTest):assert source.job_inputs["password"] == "new_password"mock_validate_credentials.assert_called_once()+ @patch(+ "posthog.temporal.data_imports.sources.freshdesk.source.FreshdeskSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_freshdesk_subdomain_change_without_api_key_is_rejected(self, mock_validate_credentials):+ # Freshdesk's connection target is `subdomain`, not `host`. Changing it without re-supplying+ # the API key must be rejected so the stored key can't be redirected to another tenant.+ source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Freshdesk",+ created_by=self.user,+ prefix="test_freshdesk_subdomain",+ job_inputs={"source_type": "Freshdesk", "subdomain": "acme", "api_key": "original_key"},+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"subdomain": "attacker"}},+ )++ assert response.status_code == 400+ assert "re-entering your credentials" in str(response.json())+ source.refresh_from_db()+ assert source.job_inputs["subdomain"] == "acme"+ assert source.job_inputs["api_key"] == "original_key"+ mock_validate_credentials.assert_not_called()++ @patch(+ "posthog.temporal.data_imports.sources.freshdesk.source.FreshdeskSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_freshdesk_subdomain_change_with_api_key_succeeds(self, mock_validate_credentials):+ source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Freshdesk",+ created_by=self.user,+ prefix="test_freshdesk_subdomain_creds",+ job_inputs={"source_type": "Freshdesk", "subdomain": "acme", "api_key": "original_key"},+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"subdomain": "newco", "api_key": "new_key"}},+ )++ assert response.status_code == 200, response.json()+ source.refresh_from_db()+ assert source.job_inputs["subdomain"] == "newco"+ assert source.job_inputs["api_key"] == "new_key"+ mock_validate_credentials.assert_called_once()+def _servicenow_source(self) -> ExternalDataSource:# ServiceNow's connection target is `instance_url` (not a top-level `host`) and its# secret lives nested inside the `auth_method` container.