: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
fix(data-warehouse): report distinct Gladly credential failures (#78034)
jake sciotto518ebb764cfb
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.pyindex 54b13483fc04..4053c6718faf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py@@ -44,12 +44,19 @@ def _clean_organization(organization: str) -> str:org = organization.strip().removeprefix("https://").removeprefix("http://")org = org.split(".")[0].split("/")[0]if not re.fullmatch(r"[a-zA-Z0-9-]+", org):- raise ValueError(f"Invalid Gladly organization: {organization}")+ raise ValueError(+ "Invalid Gladly organization. Use the first part of your Gladly URL, "+ "with letters, digits, and hyphens only. For myorg.gladly.com enter myorg."+ )return org+def _host(organization: str) -> str:+ return f"{_clean_organization(organization)}.gladly.com"++def _base_url(organization: str) -> str:- return f"https://{_clean_organization(organization)}.gladly.com/api/v1"+ return f"https://{_host(organization)}/api/v1"def _format_timestamp(value: Any) -> str:@@ -61,19 +68,42 @@ def _format_timestamp(value: Any) -> str:return str(value)-def validate_credentials(organization: str, agent_email: str, api_token: str) -> bool:- """Confirm the credentials are valid with a cheap agents probe."""- # Resolve the org first so a malformed organization surfaces its own ValueError- # rather than being mislabelled as a credentials problem by the caller.- base_url = _base_url(organization)+def validate_credentials(organization: str, agent_email: str, api_token: str) -> tuple[bool, str | None]:+ """Confirm the credentials are valid with a cheap agents probe.++ A wrong subdomain, an agent missing the API User permission, and a bad token each+ need a different fix, so they are reported separately. Returning one generic+ message for every outcome leaves the user nothing to act on, and hides an+ unreachable host or a Gladly outage behind a credentials error.+ """+ try:+ base_url = _base_url(organization)+ host = _host(organization)+ except ValueError as e:+ return False, str(e)+try:response = _get_session(agent_email, api_token).get(f"{base_url}/agents",timeout=15,)- return response.status_code == 200except Exception:- return False+ # The tracked session already logs the URL and exception class, so the message+ # stays readable instead of surfacing urllib3 retry and TLS internals.+ return False, f"Could not connect to Gladly at {host}. Check your organization subdomain."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Gladly authentication failed. Check your agent email and API token."+ if response.status_code == 403:+ return False, (+ "Gladly denied access. Check that the agent has the API User permission, "+ "under Settings > API Tokens in Gladly."+ )+ if response.status_code == 404:+ return False, f"No Gladly organization found at {host}. Check your organization subdomain."+ return False, f"Gladly returned an unexpected status: {response.status_code}"def get_rows(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.pyindex 4e22b1b7d3bc..62004c3d966c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py@@ -125,15 +125,7 @@ Your organization is the first part of your Gladly URL — for `myorg.gladly.comschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- try:- if validate_gladly_credentials(config.organization, config.agent_email, config.api_token):- return True, None- except ValueError as e:- # A malformed organization is a distinct, actionable error — surface it- # instead of the generic credentials message.- return False, str(e)-- return False, "Invalid Gladly credentials"+ return validate_gladly_credentials(config.organization, config.agent_email, config.api_token)def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GladlyResumeConfig]:return ResumableSourceManager[GladlyResumeConfig](inputs, GladlyResumeConfig)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.pyindex 8adbd355e871..a298cf1cca6e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py@@ -4,6 +4,8 @@ from typing import Anyimport pytestfrom unittest import mock+import requests+from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.gladly import (CHUNK_SIZE,GladlyResumeConfig,@@ -70,20 +72,47 @@ class TestCleanOrganization:class TestValidateCredentials:@pytest.mark.parametrize(- "status_code, expected",+ "status_code, expected_valid, expected_message_fragment",[- (200, True),- (401, False),- (403, False),+ (200, True, None),+ (401, False, "agent email and API token"),+ (403, False, "API User permission"),+ (404, False, "No Gladly organization found at myorg.gladly.com"),+ (500, False, "unexpected status: 500"),],)@mock.patch(f"{_MODULE}.make_tracked_session")- def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):+ def test_validate_credentials_status_mapping(+ self, mock_session, status_code, expected_valid, expected_message_fragment+ ):response = mock.MagicMock()response.status_code = status_codemock_session.return_value.get.return_value = response- assert validate_credentials("myorg", "[email protected]", "token") is expected+ is_valid, message = validate_credentials("myorg", "[email protected]", "token")++ assert is_valid is expected_valid+ if expected_message_fragment is None:+ assert message is None+ else:+ assert expected_message_fragment in (message or "")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_unreachable_host_is_not_reported_as_bad_credentials(self, mock_session):+ mock_session.return_value.get.side_effect = requests.ConnectionError("nodename nor servname provided")++ is_valid, message = validate_credentials("myorg", "[email protected]", "token")++ assert is_valid is False+ assert "Could not connect to Gladly at myorg.gladly.com" in (message or "")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_malformed_organization_is_reported_without_a_probe(self, mock_session):+ is_valid, message = validate_credentials("my org", "[email protected]", "token")++ assert is_valid is False+ assert "Invalid Gladly organization" in (message or "")+ mock_session.assert_not_called()@mock.patch(f"{_MODULE}.make_tracked_session")def test_session_uses_basic_auth(self, mock_session):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.pyindex a26bdaab432b..c3826f5173f5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py@@ -82,36 +82,21 @@ class TestGladlySource:assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []@pytest.mark.parametrize(- "mock_return, expected_valid",+ "mock_return",[- (True, True),- (False, False),+ (True, None),+ (False, "probe failure message"),],)@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gladly.source.validate_gladly_credentials")- def test_validate_credentials(self, mock_validate, mock_return, expected_valid):+ def test_validate_credentials_passes_the_probe_result_through(self, mock_validate, mock_return):mock_validate.return_value = mock_return- is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)-- assert is_valid is expected_valid- if not expected_valid:- assert error_message == "Invalid Gladly credentials"+ assert self.source.validate_credentials(self.config, self.team_id) == mock_returnmock_validate.assert_called_once_with("myorg", "[email protected]", "token")- @mock.patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.gladly.source.validate_gladly_credentials"- )- def test_validate_credentials_surfaces_invalid_organization(self, mock_validate):- mock_validate.side_effect = ValueError("Invalid Gladly organization: bad org")-- is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)-- assert is_valid is False- assert error_message == "Invalid Gladly organization: bad org"-def test_get_resumable_source_manager_binds_resume_config(self):inputs = mock.MagicMock()manager = self.source.get_resumable_source_manager(inputs)