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.

fix(data-warehouse): reject freshchat domains that serve html not json (#104173)

Tom Owers00ae96940bfc
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
index 4a6fe1f8fdd6..35de22f93b4f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/freshchat.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshchat/freshchat.py
@@ -1,6 +1,8 @@
import dataclasses
from typing import Any, Optional
+from requests import Response
+
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.rest_source import (
RESTAPIConfig,
@@ -11,8 +13,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
PageNumberPaginator,
SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ _looks_like_json,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.settings import (
FRESHCHAT_ENDPOINTS,
@@ -171,16 +175,37 @@ def freshchat_source(
)
-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.
+def _returned_json(response: Response) -> bool:
+ """Classify the probe body the way the sync path classifies a page body.
+
+ An empty body is not a mismatch: the REST client reads an empty 2xx as a valid empty page. A
+ body that starts as a JSON value but is cut short is a truncated read, which the sync path
+ retries, so it must not be reported here as the wrong host either.
+ """
+ if not response.content or not response.content.strip():
+ return True
+ return _looks_like_json(response.content)
+
+
+def validate_credentials(domain: str, api_key: str) -> tuple[Optional[int], bool]:
+ """Probe the Freshchat API. Returns ``(status code, whether the body was JSON)``.
- Hits the account-configuration endpoint — the cheapest resource any valid token can read.
+ The status is ``None`` on a connection error. A Freshworks portal domain serves the web app on
+ these paths and answers the probe with 200 and HTML, so the status alone cannot tell an API host
+ from a host that only serves a UI. The body has to be JSON for the domain to be usable.
+
+ Hits the account-configuration endpoint, the cheapest resource any valid token can read.
"""
- _ok, status = validate_via_probe(
+ try:
# Redirects pinned off on the session so a 3xx can't carry the token to another host.
- lambda: make_tracked_session(redact_values=(api_key,), allow_redirects=False),
- f"{_base_url(domain)}/accounts/configuration",
- headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
- timeout=VALIDATE_TIMEOUT,
- )
- return status
+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)
+ response = session.get(
+ f"{_base_url(domain)}/accounts/configuration",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ timeout=VALIDATE_TIMEOUT,
+ allow_redirects=False,
+ )
+ except Exception: # noqa: BLE001 — a credential probe must never raise; any failure means "not validated"
+ return None, False
+
+ return response.status_code, _returned_json(response)
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 bd3637ede493..0c3511a6791c 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
@@ -48,8 +48,13 @@ _DOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9.-]*\.[a-zA-Z]{2,}$")
_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."
+ "Freshchat account domain is invalid. Use the chat URL from your Freshchat API settings, "
+ "which ends in freshchat.com or myfreshworks.com."
+)
+_ERR_NON_JSON = (
+ "Your Freshchat account domain returned a web page instead of data, so it is not your Freshchat "
+ "API host. Open API settings in your Freshchat admin console and use the chat URL shown there. "
+ "It is not always the domain you sign in to."
)
@@ -79,6 +84,9 @@ class FreshchatSource(ResumableSource[FreshchatSourceConfig, FreshchatResumeConf
"401 Client Error": _ERR_AUTH_FAILED,
"403 Client Error: Forbidden for url": _ERR_FORBIDDEN,
HOST_NOT_ALLOWED_ERROR: _ERR_HOST_NOT_ALLOWED,
+ # The REST client raises this when a 2xx body isn't JSON, which is what the Freshworks
+ # portal domain returns: its web app, not the API.
+ "Non-JSON response from": _ERR_NON_JSON,
}
@property
@@ -89,7 +97,7 @@ class FreshchatSource(ResumableSource[FreshchatSourceConfig, FreshchatResumeConf
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 **account domain** is the host of your Freshchat chat URL, e.g. `acme.freshchat.com`. Find it under **API settings** in your Freshchat admin console. If your Freshchat came with the Freshsales Suite, the chat URL has its own host, e.g. `acme-123-4567.myfreshworks.com`, which is not the domain you sign in to.
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",
@@ -159,7 +167,12 @@ Your **API token** is generated by an account admin under **Admin settings → A
if not is_allowed_host(normalized):
return False, _ERR_HOST_NOT_ALLOWED
- status = validate_freshchat_credentials(config.domain, config.api_key)
+ status, returned_json = validate_freshchat_credentials(config.domain, config.api_key)
+
+ # A Freshworks portal domain answers these paths with the web app, so the status alone would
+ # accept (or mis-explain) a host that can never serve data.
+ if status is not None and not returned_json:
+ return False, _ERR_NON_JSON
if status == 200:
return True, None
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
index 0c27677af3cd..c6d125a46dc5 100644
--- 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
@@ -7,6 +7,9 @@ from unittest import mock
import requests
from requests import Response
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientNonRetryableError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.freshchat.freshchat import (
FreshchatHostNotAllowedError,
FreshchatResumeConfig,
@@ -31,6 +34,9 @@ FRESHCHAT_SESSION_PATCH = (
BASE_HOST = "acme.freshchat.com"
+# What a Freshworks portal domain answers with on these paths: the web app, not the API.
+HTML_BODY = b"<!DOCTYPE html><html><head><title>Freshworks</title></head><body></body></html>"
+
def _page(data_key: str, items: list[dict], current: int, total_pages: int) -> Response:
body = {
@@ -40,6 +46,13 @@ def _page(data_key: str, items: list[dict], current: int, total_pages: int) -> R
return _resp(body)
+def _raw_resp(content: bytes, status: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status
+ resp._content = content
+ return resp
+
+
def _resp(body: Any, status: int = 200, headers: Optional[dict] = None) -> Response:
resp = Response()
resp.status_code = status
@@ -270,6 +283,23 @@ class TestGetRows:
assert rows == [{"id": 1}]
assert session.send.call_count == 2
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_html_body_raises_the_mapped_non_retryable_error(self, MockSession) -> None:
+ # A domain that serves the web app answers 200 with HTML. That must fail the table once with
+ # the message the source maps, not retry a body that can never parse.
+ session = MockSession.return_value
+ _wire(session, [_raw_resp(HTML_BODY)])
+
+ with pytest.raises(RESTClientNonRetryableError) as exc:
+ _rows(
+ freshchat_source(
+ "key", BASE_HOST, "agents", team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ )
+ )
+
+ assert str(exc.value).startswith("Non-JSON response from")
+ assert session.send.call_count == 1
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_disallowed_host_raises_before_any_request(self, MockSession) -> None:
# A saved-then-edited domain must never receive the stored token at sync time (SSRF).
@@ -311,17 +341,31 @@ 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 = _resp(None, status=status_code)
+ session.get.return_value = _resp({"configuration": {"app_id": "a1"}}, status=status_code)
+
+ with mock.patch(FRESHCHAT_SESSION_PATCH, return_value=session):
+ assert validate_credentials(BASE_HOST, "key") == (status_code, True)
+
+ # A Freshworks portal domain answers the probe with its web app, not the API. An empty body and
+ # a truncated body stay acceptable, because the sync path reads an empty 2xx as an empty page
+ # and retries a truncated one, rather than calling either a broken host.
+ @pytest.mark.parametrize(
+ "body, returned_json",
+ [(HTML_BODY, False), (b"", True), (b'{"configuration": {"app_id"', True)],
+ )
+ def test_probe_reports_whether_the_body_is_json(self, body: bytes, returned_json: bool) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = _raw_resp(body)
with mock.patch(FRESHCHAT_SESSION_PATCH, return_value=session):
- assert validate_credentials(BASE_HOST, "key") == status_code
+ assert validate_credentials(BASE_HOST, "key") == (200, returned_json)
def test_connection_error_returns_none(self) -> None:
session = mock.MagicMock()
session.get.side_effect = requests.ConnectionError("nope")
with mock.patch(FRESHCHAT_SESSION_PATCH, return_value=session):
- assert validate_credentials(BASE_HOST, "key") is None
+ assert validate_credentials(BASE_HOST, "key") == (None, False)
def test_session_redacts_api_key_from_samples(self) -> None:
session = mock.MagicMock()
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
index c4ead4efd0cb..6e92bd3fef26 100644
--- 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
@@ -105,37 +105,51 @@ class TestFreshchatSource:
assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
@pytest.mark.parametrize(
- "domain, status, schema_name, expected_valid, expect_probe",
+ "domain, probe, 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
+ ("acme.freshchat.com", (200, True), None, True, True),
+ # A Freshworks portal domain answers 200 with the web app's HTML, so a status-only check
+ # accepts a domain no sync can read.
+ ("acme.myfreshworks.com", (200, False), None, False, True),
+ ("acme.myfreshworks.com", (200, False), "agents", False, True),
+ # A non-JSON 403 is the same wrong host, so it must not be accepted as a missing scope.
+ ("acme.myfreshworks.com", (403, False), None, False, True),
+ ("acme.freshchat.com", (403, True), None, True, True), # missing scope at source-create is accepted
+ ("acme.freshchat.com", (403, True), "agents", False, True), # missing scope for a specific schema fails
+ ("acme.freshchat.com", (401, True), None, False, True),
+ ("acme.freshchat.com", (None, False), None, False, True), # connection error
+ ("not a domain!", (200, True), 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
+ ("metadata.google.internal", (200, True), None, False, False),
+ ("api.default.svc.cluster.local", (200, True), None, False, False),
+ ("evilfreshchat.com", (200, True), None, False, False), # suffix match must not accept lookalikes
],
)
def test_validate_credentials(
self,
domain: str,
- status: Optional[int],
+ probe: tuple[Optional[int], bool],
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:
+ with mock.patch(PATCH_VALIDATE, return_value=probe) 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_non_json_response_message_matches_non_retryable_error(self) -> None:
+ # The classifier matches a substring of the raised message, so the variable URL must not stop
+ # the match; without it the user reads a raw parse failure instead of what to fix.
+ raised = "Non-JSON response from https://acme.myfreshworks.com/v2/agents"
+ matches = [friendly for key, friendly in self.source.get_non_retryable_errors().items() if key in raised]
+
+ assert matches and matches[0] is not None
+
def test_source_for_pipeline_plumbing(self) -> None:
inputs = _make_inputs("agents")
manager = self.source.get_resumable_source_manager(inputs)