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 freshchat import source (#71158)

Tom Owerse9a5046fb81a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 890dc2603d0b..70f6243b76b3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -192,6 +192,7 @@ the row lists both.
| easypromos | HTTP | requests | ✅ |
| elevenlabs | HTTP | requests | ✅ |
| freshcaller | HTTP | requests | ✅ |
+| freshchat | HTTP | requests | ✅ |
| freshdesk | HTTP | requests | ✅ |
| freshsales | HTTP | requests | ✅ |
| freshservice | HTTP | requests | ✅ |
@@ -708,7 +709,6 @@ doesn't conflict with concurrent PRs.
- freeagent
- freightview
- freshbooks
-- freshchat
- freshservice
- fulcrum
- gerrit
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/canonical_descriptions.py
new file mode 100644
index 000000000000..13140849a70f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/canonical_descriptions.py
@@ -0,0 +1,90 @@
+"""Canonical, documentation-sourced descriptions for Freshchat endpoints and columns.
+
+Sourced from the official Freshchat API reference (https://developers.freshchat.com/api/).
+Keyed by the endpoint names in `settings.py` `FRESHCHAT_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced Freshchat table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "agents": {
+ "description": "A team member (agent or admin) in your Freshchat account who handles conversations.",
+ "docs_url": "https://developers.freshchat.com/api/#agents",
+ "columns": {
+ "id": "Unique identifier for the agent.",
+ "first_name": "The agent's first name.",
+ "last_name": "The agent's last name.",
+ "email": "The agent's email address.",
+ "avatar": "The agent's profile image.",
+ "biography": "The agent's biography.",
+ "social_profiles": "The agent's linked social profiles.",
+ "groups": "The groups the agent belongs to.",
+ "skill_id": "Identifier of the skill assigned to the agent.",
+ "role_id": "Identifier of the agent's role.",
+ "role_name": "The agent's role name.",
+ "license_type": "The type of license assigned to the agent.",
+ "availability_status": "Whether the agent is currently available.",
+ "is_deactivated": "Whether the agent has been deactivated.",
+ "is_deleted": "Whether the agent has been deleted.",
+ "freshid_uuid": "The agent's Freshworks organisation identifier.",
+ },
+ },
+ "users": {
+ "description": "An end user (contact) who has interacted with your Freshchat messaging.",
+ "docs_url": "https://developers.freshchat.com/api/#users",
+ "columns": {
+ "id": "Unique identifier for the user, auto-generated when the user record is created.",
+ "created_time": "Time at which the user record was created.",
+ "updated_time": "Time at which the user record was last updated.",
+ "email": "The user's email address.",
+ "first_name": "The user's first name.",
+ "last_name": "The user's last name.",
+ "avatar": "The user's profile image.",
+ "phone": "The user's phone number.",
+ "reference_id": "An external identifier you associate with the user.",
+ "restore_id": "Identifier used to restore a user's conversation history across devices.",
+ "properties": "Custom user properties defined for your account.",
+ },
+ },
+ "groups": {
+ "description": "A group of agents used to route and organise Freshchat conversations.",
+ "docs_url": "https://developers.freshchat.com/api/#groups",
+ "columns": {
+ "id": "Unique identifier for the group.",
+ "name": "The group's name.",
+ "description": "The group's description.",
+ "routing_type": "How conversations are routed to agents in the group.",
+ "standard_response_ids": "Canned responses associated with the group.",
+ "business_calendar_id": "Identifier of the business calendar applied to the group.",
+ "sla_policy_ids": "SLA policies associated with the group.",
+ },
+ },
+ "channels": {
+ "description": "A topic (channel) that users can start a conversation under.",
+ "docs_url": "https://developers.freshchat.com/api/#channels",
+ "columns": {
+ "id": "Unique identifier for the channel.",
+ "name": "The channel's name.",
+ "icon": "The channel's icon.",
+ "welcome_message": "The message shown to users when they open the channel.",
+ "tags": "Tags associated with the channel.",
+ "locale": "The channel's language/locale.",
+ "enabled": "Whether the channel is enabled.",
+ "public": "Whether the channel is publicly visible to users.",
+ "updated_time": "Time at which the channel was last updated.",
+ },
+ },
+ "accounts_configuration": {
+ "description": "Account-level Freshchat configuration for your app.",
+ "docs_url": "https://developers.freshchat.com/api/#accounts",
+ "columns": {
+ "app_id": "Identifier of the Freshchat app (widget).",
+ "account_id": "Identifier of the Freshchat account.",
+ "organisation_id": "Identifier of the Freshworks organisation.",
+ "plan_type": "The account's Freshchat plan.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/freshchat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/freshchat.py
new file mode 100644
index 000000000000..a3260ce9f7ba
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/freshchat.py
@@ -0,0 +1,267 @@
+import dataclasses
+from collections.abc import Iterator
+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 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.freshchat.settings import (
+ FRESHCHAT_ENDPOINTS,
+ PER_PAGE,
+ PRIMARY_KEYS,
+ FreshchatEndpointConfig,
+)
+
+REQUEST_TIMEOUT = 60
+VALIDATE_TIMEOUT = 10
+MAX_RETRIES = 5
+MAX_RETRY_WAIT = 60.0
+
+# All documented Freshchat API hosts live under these Freshworks-owned domains: account
+# subdomains and regional hosts (api.freshchat.com, api.eu.freshchat.com, ...) under
+# freshchat.com, Freshsales Suite accounts under myfreshworks.com.
+ALLOWED_HOST_SUFFIXES = ("freshchat.com", "myfreshworks.com")
+
+HOST_NOT_ALLOWED_ERROR = "Freshchat domain is not allowed"
+
+_EXPONENTIAL_WAIT = wait_exponential_jitter(initial=1, max=MAX_RETRY_WAIT)
+
+
+class FreshchatRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class FreshchatHostNotAllowedError(Exception):
+ pass
+
+
+def _parse_retry_after(value: str | None) -> float | None:
+ """Parse a Retry-After header. Freshworks APIs send 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, FreshchatRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_RETRY_WAIT)
+ return _EXPONENTIAL_WAIT(retry_state)
+
+
+class FreshchatResumeConfig:
+ # The next page number to fetch. Freshchat uses page/items_per_page pagination, so a single
+ # integer is enough to pick back up. Endpoints are full refresh (no time window), so re-entering
+ # a page and deduping on the primary key is safe.
+ page: int
+
+
+def normalize_domain(domain: str) -> str:
+ """Normalize the Freshchat host the user supplied.
+
+ Accepts a bare account name ("acme" -> "acme.freshchat.com"), a full host
+ ("acme.freshchat.com", "acme.myfreshworks.com", "api.eu.freshchat.com"), or a URL with a
+ scheme/path. Freshchat's base host varies by account and data center, so we keep whatever
+ host the user gives and only default the domain when they pass a bare account name.
+ """
+ d = domain.strip().lower().removeprefix("https://").removeprefix("http://")
+ d = d.split("/")[0].strip().rstrip("/")
+ if "." not in d:
+ d = f"{d}.freshchat.com"
+ return d
+
+
+def is_allowed_host(host: str) -> bool:
+ """Only Freshworks-owned hosts are reachable: account subdomains and regional API hosts live
+ under freshchat.com, Freshsales Suite accounts under myfreshworks.com. The domain is fully
+ customer-controlled, so anything else (e.g. an internal hostname) is refused — the stored
+ token plus scheduled syncs would otherwise let a user aim authenticated GETs at arbitrary
+ hosts (SSRF)."""
+ return any(host == suffix or host.endswith(f".{suffix}") for suffix in ALLOWED_HOST_SUFFIXES)
+
+
+def _base_url(domain: str) -> str:
+ return f"https://{normalize_domain(domain)}/v2"
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ # Freshchat authenticates with a long-lived Bearer token. Accept is required so the API
+ # returns JSON rather than an HTML error page.
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+def build_base_params(config: FreshchatEndpointConfig) -> dict[str, str]:
+ """Query params shared across every page of one sync (everything except `page`)."""
+ params: dict[str, str] = {}
+ if config.paginated:
+ params["items_per_page"] = str(PER_PAGE)
+ # Explicit stable sort so page boundaries don't skip/duplicate rows if the API's implicit
+ # default order shifts while we page.
+ params["sort_order"] = "asc"
+ params.update(config.extra_params)
+ return params
+
+
+def extract_items(data: Any, config: FreshchatEndpointConfig) -> list[dict]:
+ """Freshchat's envelope is inconsistent: most lists wrap under a resource key, some return a
+ bare array, and single-object endpoints return one object. Handle all three shapes."""
+ if config.data_key and isinstance(data, dict):
+ value = data.get(config.data_key)
+ if isinstance(value, list):
+ return value
+ if isinstance(value, dict):
+ return [value]
+ if isinstance(data, list):
+ return data
+ if config.single_object and isinstance(data, dict):
+ return [data]
+ return []
+
+
+def _has_next_page(data: Any, items: list[dict], page: int) -> bool:
+ if not items:
+ return False
+ if isinstance(data, dict):
+ pagination = data.get("pagination")
+ if isinstance(pagination, dict) and isinstance(pagination.get("total_pages"), int):
+ total_pages = pagination["total_pages"]
+ current = pagination.get("current_page")
+ current_page = current if isinstance(current, int) else page
+ return current_page < total_pages
+ links = data.get("links")
+ if isinstance(links, dict):
+ next_page = links.get("next_page")
+ return isinstance(next_page, dict) and bool(next_page.get("href"))
+ # No usable pagination metadata -> a full page implies there may be more.
+ return len(items) >= PER_PAGE
+
+
+def get_rows(
+ api_key: str,
+ domain: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FreshchatResumeConfig],
+) -> Iterator[list[dict]]:
+ config = FRESHCHAT_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+
+ # Re-check at run time (not just at source-create) so an edited or previously-saved domain
+ # can't aim the stored token at a non-Freshworks host (SSRF).
+ if not is_allowed_host(normalize_domain(domain)):
+ raise FreshchatHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)
+
+ base = _base_url(domain)
+ base_params = build_base_params(config)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume is not None else 1
+ if resume is not None:
+ logger.debug(f"Freshchat: resuming {endpoint} from page {page}")
+
+ # One session reused across pages so urllib3 keeps the connection alive. `redact_values` masks
+ # the token from captured HTTP samples: it rides in the Authorization header, which the
+ # name-based sample scrubbers don't recognise.
+ session = make_tracked_session(redact_values=(api_key,))
+
+ @retry(
+ retry=retry_if_exception_type((FreshchatRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_retry_wait,
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> Any:
+ # Don't follow redirects: the allowed host could 3xx to an arbitrary address, defeating
+ # the host allowlist above (SSRF).
+ response = session.get(page_url, headers=headers, timeout=REQUEST_TIMEOUT, allow_redirects=False)
+
+ if response.is_redirect or response.is_permanent_redirect:
+ raise FreshchatHostNotAllowedError(f"{HOST_NOT_ALLOWED_ERROR}: redirect from url={page_url}")
+
+ # Freshchat throttles per plan tier with 429; honor Retry-After when present.
+ if response.status_code == 429:
+ raise FreshchatRetryableError(
+ f"Freshchat API rate limited: url={page_url}",
+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),
+ )
+
+ if response.status_code >= 500:
+ raise FreshchatRetryableError(
+ f"Freshchat API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Freshchat API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ params = dict(base_params)
+ if config.paginated:
+ params["page"] = str(page)
+ url = f"{base}{config.path}?{urlencode(params)}" if params else f"{base}{config.path}"
+
+ data = fetch_page(url)
+ items = extract_items(data, config)
+ if items:
+ yield items
+
+ if not config.paginated or not _has_next_page(data, items, page):
+ break
+
+ # Advance and save AFTER yielding so the just-written page is durable before we bookmark
+ # the next one; a crash re-fetches from `page` and merge dedupes on the primary key.
+ page += 1
+ resumable_source_manager.save_state(FreshchatResumeConfig(page=page))
+
+
+def freshchat_source(
+ api_key: str,
+ domain: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FreshchatResumeConfig],
+) -> SourceResponse:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ domain=domain,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=PRIMARY_KEYS[endpoint],
+ # All endpoints are full refresh; we page with an explicit ascending sort.
+ sort_mode="asc",
+ )
+
+
+def validate_credentials(domain: str, api_key: str) -> Optional[int]:
+ """Probe the Freshchat API. Returns the HTTP status code, or ``None`` on a connection error.
+
+ Hits the account-configuration endpoint — the cheapest resource any valid token can read.
+ """
+ url = f"{_base_url(domain)}/accounts/configuration"
+ try:
+ # No redirects here either — a 3xx would otherwise carry the token to another host.
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ url, headers=_get_headers(api_key), timeout=VALIDATE_TIMEOUT, allow_redirects=False
+ )
+ except Exception:
+ return None
+
+ return response.status_code
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/settings.py
new file mode 100644
index 000000000000..c824628cdc63
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/settings.py
@@ -0,0 +1,86 @@
+"""Freshchat source settings and endpoint catalog."""
+
+from dataclasses import dataclass, field
+from typing import Optional
+
+# Freshchat caps `items_per_page` at 50 (default 20). Pull the max to keep the request
+# count — and therefore rate-limit pressure — as low as possible.
+PER_PAGE = 50
+
+# The `GET /v2/users` list endpoint requires at least one filter parameter; a bare list
+# request errors. `created_from` is a stable creation-time floor that lets us page every
+# user without excluding anyone. This is a full-refresh floor, not an incremental cursor.
+USERS_CREATED_FROM = "2000-01-01T00:00:00.000Z"
+
+
+@dataclass
+class FreshchatEndpointConfig:
+ name: str
+ # Path relative to the `/v2` base (e.g. `/agents`).
+ path: str
+ # Freshchat wraps most list responses in an object keyed by the resource name
+ # (e.g. {"agents": [...], "pagination": {...}}); `data_key` is that key. The envelope is
+ # inconsistent across the API, so the extractor also falls back to a bare array / single
+ # object when the key is absent.
+ data_key: Optional[str] = None
+ # `True` for the paginated collection endpoints (page / items_per_page). `False` for
+ # single-object endpoints like accounts/configuration.
+ paginated: bool = True
+ # `True` when the endpoint returns a single object rather than a collection — we wrap it
+ # into a one-row list so it lands as a single warehouse row.
+ single_object: bool = False
+ # Extra static query params (e.g. the mandatory `created_from` filter on users).
+ extra_params: dict[str, str] = field(default_factory=dict)
+
+
+# Freshchat v2 top-level endpoints.
+#
+# The public REST API exposes no server-side updated_since / created_since cursor on these
+# core list endpoints, so every endpoint is full refresh only (no `supports_incremental`).
+# Pagination is resumable by page number via the ResumableSource manager. Conversations,
+# messages and per-user conversation fan-out require object IDs (there is no top-level list
+# endpoint for them) and are intentionally left out of this first cut; outbound-messages and
+# the raw report endpoints require time-window params and are likewise deferred.
+FRESHCHAT_ENDPOINTS: dict[str, FreshchatEndpointConfig] = {
+ "agents": FreshchatEndpointConfig(
+ name="agents",
+ path="/agents",
+ data_key="agents",
+ ),
+ "users": FreshchatEndpointConfig(
+ name="users",
+ path="/users",
+ data_key="users",
+ # At least one filter is mandatory on this endpoint; the created-time floor lists all users.
+ extra_params={"created_from": USERS_CREATED_FROM},
+ ),
+ "groups": FreshchatEndpointConfig(
+ name="groups",
+ path="/groups",
+ data_key="groups",
+ ),
+ "channels": FreshchatEndpointConfig(
+ name="channels",
+ path="/channels",
+ data_key="channels",
+ ),
+ "accounts_configuration": FreshchatEndpointConfig(
+ name="accounts_configuration",
+ path="/accounts/configuration",
+ data_key="configuration",
+ paginated=False,
+ single_object=True,
+ ),
+}
+
+ENDPOINTS = tuple(FRESHCHAT_ENDPOINTS.keys())
+
+# `id` is the auto-generated primary key on agents / users / groups / channels. The single
+# account-configuration row is keyed on its stable Freshchat app id.
+PRIMARY_KEYS: dict[str, list[str]] = {
+ "agents": ["id"],
+ "users": ["id"],
+ "groups": ["id"],
+ "channels": ["id"],
+ "accounts_configuration": ["app_id"],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/source.py
index d3908c3e76b8..8d0766fa00d0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/source.py
@@ -1,30 +1,193 @@
-from typing import cast
+import re
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-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 SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.freshchat import (
+ HOST_NOT_ALLOWED_ERROR,
+ FreshchatResumeConfig,
+ freshchat_source,
+ is_allowed_host,
+ normalize_domain,
+ validate_credentials as validate_freshchat_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.settings import (
+ FRESHCHAT_ENDPOINTS,
+ PRIMARY_KEYS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FreshchatSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+# This first cut covers Freshchat's top-level v2 list endpoints (Agents, Users, Groups, Channels)
+# plus the single-row account configuration. Conversations and messages require object IDs (no
+# top-level list endpoint exists), and outbound-messages / raw reports require time-window params;
+# all are intentionally left out of this first cut. Freshchat has no server-side incremental
+# cursor on the core list endpoints, so every endpoint is full refresh, resumable by page number.
+
+# Shape check on the normalized host (the Freshworks-suffix allowlist in `is_allowed_host` is the
+# actual security boundary).
+_DOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9.-]*\.[a-zA-Z]{2,}$")
+
+# User-facing auth/permission messages, shared between sync-time (get_non_retryable_errors) and
+# connect-time (validate_credentials) so the two can't drift.
+_ERR_AUTH_FAILED = "Freshchat authentication failed. Please check your API token and account domain."
+_ERR_FORBIDDEN = "Your Freshchat API token does not have permission for this resource. Check the token's scope."
+_ERR_HOST_NOT_ALLOWED = (
+ "Freshchat account domain is invalid. Use your freshchat.com account or regional API host, "
+ "or your myfreshworks.com domain."
+)
+
@SourceRegistry.register
-class FreshchatSource(SimpleSource[FreshchatSourceConfig]):
+class FreshchatSource(ResumableSource[FreshchatSourceConfig, FreshchatResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FRESHCHAT
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # Freshchat's connection target is the account domain, not a `host` field. Editing it on an
+ # existing source must force the API token to be re-entered.
+ return ["domain"]
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": _ERR_AUTH_FAILED,
+ "403 Client Error: Forbidden for url": _ERR_FORBIDDEN,
+ HOST_NOT_ALLOWED_ERROR: _ERR_HOST_NOT_ALLOWED,
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.FRESHCHAT,
category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
label="Freshchat",
+ caption="""Enter your Freshchat account domain and API token to pull your Freshchat messaging data into the PostHog Data warehouse.
+
+Your **account domain** is the host of your Freshchat account — e.g. `acme.freshchat.com`. Use the regional API host if your account lives in a specific data center (e.g. `api.eu.freshchat.com`).
+
+Your **API token** is generated by an account admin under **Admin settings → API tokens**. It is sent as a Bearer token.""",
iconPath="/static/services/freshchat.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/freshchat",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="domain",
+ label="Freshchat account domain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="acme.freshchat.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: FreshchatSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=name,
+ # No server-side incremental cursor on the core list endpoints -> full refresh only.
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ detected_primary_keys=PRIMARY_KEYS[name],
+ )
+ for name in FRESHCHAT_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: FreshchatSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ normalized = normalize_domain(config.domain)
+ if not _DOMAIN_REGEX.match(normalized):
+ return False, "Freshchat account domain is invalid"
+
+ # The domain is fully customer-controlled; refuse anything outside the Freshworks-owned
+ # suffixes so the stored token can't be aimed at an internal host (SSRF).
+ if not is_allowed_host(normalized):
+ return False, _ERR_HOST_NOT_ALLOWED
+
+ status = validate_freshchat_credentials(config.domain, config.api_key)
+
+ if status == 200:
+ return True, None
+
+ # A valid token that simply lacks scope for the probe 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
+
+ if status == 403:
+ return False, _ERR_FORBIDDEN
+
+ if status == 401:
+ return False, _ERR_AUTH_FAILED
+
+ return False, "Could not connect to Freshchat. Please check your account domain and API token."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FreshchatResumeConfig]:
+ return ResumableSourceManager[FreshchatResumeConfig](inputs, FreshchatResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FreshchatSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FreshchatResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return freshchat_source(
+ api_key=config.api_key,
+ domain=config.domain,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat.py
new file mode 100644
index 000000000000..8e0de33d0740
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat.py
@@ -0,0 +1,356 @@
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.freshchat import (
+ FreshchatHostNotAllowedError,
+ FreshchatResumeConfig,
+ _has_next_page,
+ _parse_retry_after,
+ build_base_params,
+ extract_items,
+ get_rows,
+ is_allowed_host,
+ normalize_domain,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.settings import (
+ FRESHCHAT_ENDPOINTS,
+ PER_PAGE,
+ USERS_CREATED_FROM,
+)
+
+logger = structlog.get_logger()
+
+PATCH_SESSION = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.freshchat.make_tracked_session"
+)
+
+
+class FakeResponse:
+ def __init__(
+ self,
+ json_data: Any = None,
+ status_code: int = 200,
+ text: str = "",
+ headers: Optional[dict] = None,
+ ) -> None:
+ self._json = json_data
+ self.status_code = status_code
+ self.ok = 200 <= status_code < 400
+ self.text = text
+ self.headers = headers or {}
+ self.is_redirect = status_code in (301, 302, 303, 307, 308) and "Location" in self.headers
+ self.is_permanent_redirect = status_code in (301, 308) and "Location" in self.headers
+
+ 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[FreshchatResumeConfig] = None) -> None:
+ self._resume = resume
+ self.saved: list[FreshchatResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._resume is not None
+
+ def load_state(self) -> Optional[FreshchatResumeConfig]:
+ return self._resume
+
+ def save_state(self, data: FreshchatResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(data_key: str, items: list[dict], current: int, total_pages: int) -> dict:
+ return {
+ data_key: items,
+ "pagination": {"current_page": current, "total_pages": total_pages, "total_items": 999},
+ }
+
+
+class TestNormalizeDomain:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("acme", "acme.freshchat.com"), # bare account name gets the default domain
+ ("acme.freshchat.com", "acme.freshchat.com"),
+ ("https://acme.freshchat.com", "acme.freshchat.com"),
+ ("http://acme.freshchat.com/", "acme.freshchat.com"),
+ (" acme.freshchat.com ", "acme.freshchat.com"),
+ ("acme.freshchat.com/v2/agents", "acme.freshchat.com"),
+ ("api.eu.freshchat.com", "api.eu.freshchat.com"), # regional host preserved
+ ("acme.myfreshworks.com", "acme.myfreshworks.com"), # Freshsales Suite host preserved
+ ],
+ )
+ def test_normalize_domain(self, raw: str, expected: str) -> None:
+ assert normalize_domain(raw) == expected
+
+
+class TestIsAllowedHost:
+ @pytest.mark.parametrize(
+ "host, allowed",
+ [
+ ("acme.freshchat.com", True),
+ ("api.eu.freshchat.com", True),
+ ("acme.myfreshworks.com", True),
+ # The domain is customer-controlled; non-Freshworks hosts must be refused (SSRF).
+ ("metadata.google.internal", False),
+ ("api.default.svc.cluster.local", False),
+ ("service.internal", False),
+ ("evilfreshchat.com", False), # suffix match must not accept lookalikes
+ ("freshchat.com.evil.com", False),
+ ],
+ )
+ def test_is_allowed_host(self, host: str, allowed: bool) -> None:
+ assert is_allowed_host(host) is allowed
+
+
+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 TestBuildBaseParams:
+ def test_paginated_endpoint_has_page_size_and_sort(self) -> None:
+ params = build_base_params(FRESHCHAT_ENDPOINTS["agents"])
+ assert params == {"items_per_page": str(PER_PAGE), "sort_order": "asc"}
+
+ def test_users_carries_mandatory_created_from_filter(self) -> None:
+ # `GET /v2/users` rejects a filter-less request, so the created-time floor must be sent.
+ params = build_base_params(FRESHCHAT_ENDPOINTS["users"])
+ assert params["created_from"] == USERS_CREATED_FROM
+
+ def test_non_paginated_endpoint_has_no_pagination_params(self) -> None:
+ params = build_base_params(FRESHCHAT_ENDPOINTS["accounts_configuration"])
+ assert params == {}
+
+
+class TestExtractItems:
+ @pytest.mark.parametrize("endpoint", ["agents", "users", "groups", "channels"])
+ def test_wrapper_key(self, endpoint: str) -> None:
+ config = FRESHCHAT_ENDPOINTS[endpoint]
+ assert extract_items({config.data_key: [{"id": 1}]}, config) == [{"id": 1}]
+
+ def test_wrong_wrapper_key_returns_empty(self) -> None:
+ assert extract_items({"something_else": [{"id": 1}]}, FRESHCHAT_ENDPOINTS["agents"]) == []
+
+ def test_bare_array_fallback(self) -> None:
+ assert extract_items([{"id": 1}], FRESHCHAT_ENDPOINTS["agents"]) == [{"id": 1}]
+
+ def test_single_object_wrapped(self) -> None:
+ # accounts/configuration wrapped under its resource key -> one row.
+ config = FRESHCHAT_ENDPOINTS["accounts_configuration"]
+ assert extract_items({"configuration": {"app_id": "a1"}}, config) == [{"app_id": "a1"}]
+
+ def test_single_object_bare(self) -> None:
+ # accounts/configuration returned as a bare object -> still one row.
+ config = FRESHCHAT_ENDPOINTS["accounts_configuration"]
+ assert extract_items({"app_id": "a1"}, config) == [{"app_id": "a1"}]
+
+ def test_unknown_shape_returns_empty(self) -> None:
+ assert extract_items({"pagination": {}}, FRESHCHAT_ENDPOINTS["agents"]) == []
+
+
+class TestHasNextPage:
+ @pytest.mark.parametrize(
+ "data, items, page, expected",
+ [
+ ({"pagination": {"current_page": 1, "total_pages": 3}}, [{"id": 1}], 1, True),
+ ({"pagination": {"current_page": 3, "total_pages": 3}}, [{"id": 1}], 3, False),
+ # links envelope with a next_page href -> more pages.
+ ({"links": {"next_page": {"href": "https://x/v2/agents?page=2"}}}, [{"id": 1}], 1, True),
+ # links envelope present but no next_page -> done.
+ ({"links": {"last_page": {"href": "https://x"}}}, [{"id": 1}], 1, False),
+ # no usable metadata: a full page implies there may be more.
+ ({}, [{"id": i} for i in range(PER_PAGE)], 1, True),
+ ({}, [{"id": 1}], 1, False), # short page, no meta -> done
+ ({"pagination": {"current_page": 1, "total_pages": 2}}, [], 1, False), # empty page terminates
+ ],
+ )
+ def test_has_next_page(self, data: dict, items: list[dict], page: int, expected: bool) -> None:
+ assert _has_next_page(data, items, page) is expected
+
+
+class TestGetRows:
+ def test_paginates_by_page_number_and_saves_state(self) -> None:
+ responses = [
+ FakeResponse(_page("agents", [{"id": 1}], current=1, total_pages=2)),
+ FakeResponse(_page("agents", [{"id": 2}], current=2, total_pages=2)),
+ ]
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ rows = list(get_rows("key", "acme.freshchat.com", "agents", logger, manager)) # type: ignore[arg-type]
+
+ assert rows == [[{"id": 1}], [{"id": 2}]]
+ # State saved once, pointing at page 2 (the next page after the first was written).
+ assert manager.saved == [FreshchatResumeConfig(page=2)]
+ first_url = session.get.call_args_list[0].args[0]
+ query = parse_qs(urlparse(first_url).query)
+ assert query["page"] == ["1"]
+ assert query["items_per_page"] == [str(PER_PAGE)]
+
+ def test_single_page_saves_no_state(self) -> None:
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = [FakeResponse(_page("groups", [{"id": 1}], current=1, total_pages=1))]
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ rows = list(get_rows("key", "acme.freshchat.com", "groups", logger, manager)) # type: ignore[arg-type]
+
+ assert rows == [[{"id": 1}]]
+ assert manager.saved == []
+
+ def test_non_paginated_endpoint_fetches_once(self) -> None:
+ # accounts/configuration is a single object: one request, no pagination params, no state.
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = [FakeResponse({"configuration": {"app_id": "a1"}})]
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ rows = list(
+ get_rows("key", "acme.freshchat.com", "accounts_configuration", logger, manager) # type: ignore[arg-type]
+ )
+
+ assert rows == [[{"app_id": "a1"}]]
+ assert manager.saved == []
+ assert session.get.call_count == 1
+ query = parse_qs(urlparse(session.get.call_args_list[0].args[0]).query)
+ assert "page" not in query
+
+ def test_resumes_from_saved_page(self) -> None:
+ manager = FakeResumableManager(resume=FreshchatResumeConfig(page=5))
+ session = mock.MagicMock()
+ session.get.side_effect = [FakeResponse(_page("agents", [{"id": 50}], current=5, total_pages=5))]
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ rows = list(get_rows("key", "acme.freshchat.com", "agents", logger, manager)) # type: ignore[arg-type]
+
+ assert rows == [[{"id": 50}]]
+ first_url = session.get.call_args_list[0].args[0]
+ assert parse_qs(urlparse(first_url).query)["page"] == ["5"]
+
+ def test_uses_bearer_auth_header(self) -> None:
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = [FakeResponse(_page("agents", [{"id": 1}], current=1, total_pages=1))]
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ list(get_rows("tok", "acme.freshchat.com", "agents", logger, manager)) # type: ignore[arg-type]
+
+ assert session.get.call_args.kwargs["headers"]["Authorization"] == "Bearer tok"
+
+ def test_session_redacts_api_key_from_samples(self) -> None:
+ # The token rides in the Authorization header, which the name-based sample scrubbers don't
+ # cover, so it must be value-redacted or it leaks into captured HTTP samples.
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = [FakeResponse(_page("agents", [{"id": 1}], current=1, total_pages=1))]
+
+ with mock.patch(PATCH_SESSION, return_value=session) as mock_make:
+ list(get_rows("secret-key", "acme.freshchat.com", "agents", logger, manager)) # type: ignore[arg-type]
+
+ assert mock_make.call_args.kwargs.get("redact_values") == ("secret-key",)
+
+ @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.freshchat.com", "agents", logger, manager)) # type: ignore[arg-type]
+
+ # A 429 (rate limit) and any 5xx are transient: the sync must retry rather than abort. The 429
+ # case also proves a server-provided Retry-After is honored (here 0, so the retry is immediate).
+ @pytest.mark.parametrize("status_code, headers", [(429, {"Retry-After": "0"}), (500, {})])
+ def test_retryable_status_is_retried_then_succeeds(self, status_code: int, headers: dict) -> None:
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = [
+ FakeResponse(status_code=status_code, headers=headers),
+ FakeResponse(_page("agents", [{"id": 1}], current=1, total_pages=1)),
+ ]
+
+ # Neutralize the exponential backoff so the 5xx retry doesn't actually sleep.
+ with (
+ mock.patch(PATCH_SESSION, return_value=session),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.freshchat._EXPONENTIAL_WAIT",
+ return_value=0,
+ ),
+ ):
+ rows = list(get_rows("key", "acme.freshchat.com", "agents", logger, manager)) # type: ignore[arg-type]
+
+ assert rows == [[{"id": 1}]]
+ assert session.get.call_count == 2
+
+ def test_disallowed_host_raises_before_any_request(self) -> None:
+ # A saved-then-edited domain must never receive the stored token at sync time (SSRF).
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ with pytest.raises(FreshchatHostNotAllowedError):
+ list(get_rows("key", "metadata.google.internal", "agents", logger, manager)) # type: ignore[arg-type]
+
+ session.get.assert_not_called()
+
+ def test_redirect_response_raises_and_is_not_followed(self) -> None:
+ # A 3xx from the allowed host could point anywhere; following it would defeat the host
+ # allowlist, so it must surface as a hard error instead.
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+ redirect = FakeResponse(status_code=302, headers={"Location": "http://169.254.169.254/"})
+ session.get.side_effect = [redirect]
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ with pytest.raises(FreshchatHostNotAllowedError):
+ list(get_rows("key", "acme.freshchat.com", "agents", logger, manager)) # type: ignore[arg-type]
+
+ assert session.get.call_args.kwargs.get("allow_redirects") is False
+
+
+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.freshchat.com", "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.freshchat.com", "key") is None
+
+ def test_session_redacts_api_key_from_samples(self) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = FakeResponse(status_code=200)
+
+ with mock.patch(PATCH_SESSION, return_value=session) as mock_make:
+ validate_credentials("acme.freshchat.com", "secret-key")
+
+ assert mock_make.call_args.kwargs.get("redact_values") == ("secret-key",)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat_source.py
new file mode 100644
index 000000000000..73088c8419e9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/tests/test_freshchat_source.py
@@ -0,0 +1,166 @@
+from typing import Optional
+
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.freshchat import FreshchatResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.source import FreshchatSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FreshchatSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+PATCH_VALIDATE = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.source.validate_freshchat_credentials"
+)
+
+
+def _make_inputs(schema_name: str = "agents") -> 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 TestFreshchatSource:
+ def setup_method(self) -> None:
+ self.source = FreshchatSource()
+ self.team_id = 1
+ self.config = FreshchatSourceConfig(domain="acme.freshchat.com", api_key="key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.FRESHCHAT
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Freshchat"
+ assert config.label == "Freshchat"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/freshchat"
+ # A finished source is visible: the unreleased flag must never be re-added.
+ assert not config.unreleasedSource
+
+ fields = config.fields
+ assert len(fields) == 2
+ domain_field, api_key_field = fields
+ assert isinstance(domain_field, SourceFieldInputConfig)
+ assert domain_field.name == "domain"
+ assert domain_field.type == SourceFieldInputConfigType.TEXT
+ assert domain_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
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static endpoint catalog -> the public docs Supported-tables section can render.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_connection_host_fields(self) -> None:
+ # The domain is where the stored token is sent; editing it must re-require the secret.
+ assert self.source.connection_host_fields == ["domain"]
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ ["401 Client Error", "403 Client Error: Forbidden for url", "Freshchat domain is not allowed"],
+ )
+ 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_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Freshchat has no server-side incremental cursor -> every endpoint is full refresh.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+
+ @pytest.mark.parametrize(
+ "name, primary_keys",
+ [
+ ("agents", ["id"]),
+ ("users", ["id"]),
+ ("groups", ["id"]),
+ ("channels", ["id"]),
+ ("accounts_configuration", ["app_id"]),
+ ],
+ )
+ def test_schema_primary_keys(self, name: str, primary_keys: list[str]) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas[name].detected_primary_keys == primary_keys
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["agents"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "agents"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_canonical_descriptions_cover_endpoints(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "domain, status, schema_name, expected_valid, expect_probe",
+ [
+ ("acme.freshchat.com", 200, None, True, True),
+ ("acme.freshchat.com", 403, None, True, True), # missing scope at source-create is accepted
+ ("acme.freshchat.com", 403, "agents", False, True), # missing scope for a specific schema fails
+ ("acme.freshchat.com", 401, None, False, True),
+ ("acme.freshchat.com", None, None, False, True), # connection error
+ ("not a domain!", 200, None, False, False), # domain regex rejects before probing
+ # Non-Freshworks hosts are refused before probing — the stored token must never be
+ # sent to a customer-chosen internal host (SSRF).
+ ("metadata.google.internal", 200, None, False, False),
+ ("api.default.svc.cluster.local", 200, None, False, False),
+ ("evilfreshchat.com", 200, None, False, False), # suffix match must not accept lookalikes
+ ],
+ )
+ def test_validate_credentials(
+ self,
+ domain: str,
+ status: Optional[int],
+ schema_name: Optional[str],
+ expected_valid: bool,
+ expect_probe: bool,
+ ) -> None:
+ config = FreshchatSourceConfig(domain=domain, 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 not expect_probe:
+ 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 FreshchatResumeConfig
+
+ def test_source_for_pipeline_plumbing(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.primary_keys == ["id"]
+ # Full refresh, paged with an explicit ascending sort.
+ assert response.sort_mode == "asc"
+ assert response.partition_mode is None
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.py
index 6164f803ad63..18097cea8378 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
@@ -1677,7 +1677,8 @@ class FreshcallerSourceConfig(config.Config):
@config.config
class FreshchatSourceConfig(config.Config):
- pass
+ domain: str
+ api_key: str
@config.config