: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(clerk): return actionable copy when validating a bad Clerk key (#84061)
Tom Owersa836367bc984
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.pyindex d1a8842d95b5..70dd2bba7a66 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/clerk.py@@ -7,6 +7,8 @@ from requests import Request, Responsefrom requests.exceptions import HTTPError, RequestExceptionfrom structlog.types import FilteringBoundLogger+from posthog.exceptions_capture import capture_exception+from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import (CLERK_ENDPOINTS,RETIRED_ENDPOINTS,@@ -224,6 +226,20 @@ def _strip_sensitive_fields(item: dict[str, Any], paths: tuple[str, ...]) -> dicreturn item+# Curated copy shared with the sync path's non-retryable-error map in source.py, so a bad key is+# explained the same way whether it's caught at create time or on a running sync. The previous+# behaviour forwarded Clerk's raw response body (and requests' exception string) straight to the+# wizard, which the user can't act on.+_INVALID_KEY_MESSAGE = (+ "Your Clerk secret key is invalid or has been revoked. Please update the secret key in your "+ "Clerk dashboard and reconnect."+)+_FORBIDDEN_KEY_MESSAGE = (+ "Your Clerk secret key does not have permission to access this endpoint. Please check the "+ "key's permissions in your Clerk dashboard."+)++def validate_credentials(secret_key: str) -> tuple[bool, str | None]:"""Validate Clerk API credentials by making a test request."""url = "https://api.clerk.com/v1/users"@@ -234,20 +250,21 @@ def validate_credentials(secret_key: str) -> tuple[bool, str | None]:try:response = make_tracked_session().get(url, headers=headers, params={"limit": 1}, timeout=10)-- if response.status_code == 200:- return True, None-- try:- error_data = response.json()- if error_data.get("errors"):- return False, error_data["errors"][0].get("message", response.text)- except Exception:- pass-- return False, response.textexcept RequestException as e:- return False, str(e)+ capture_exception(e)+ return False, "Couldn't reach Clerk to validate your secret key. Please try again in a moment."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, _INVALID_KEY_MESSAGE+ if response.status_code == 403:+ return False, _FORBIDDEN_KEY_MESSAGE++ # Any other status is unexpected for this endpoint; keep the raw detail for us instead of+ # surfacing it to the user.+ capture_exception(Exception(f"Unexpected Clerk credential validation response ({response.status_code})"))+ return False, "Couldn't validate your Clerk secret key. Please check the key and try again."# Clerk error codes meaning "this account has not switched the feature on". Paired with thediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.pyindex 88e558182459..392d733e461b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clerk/tests/test_clerk.py@@ -7,7 +7,7 @@ import pytestfrom unittest.mock import MagicMock, patchfrom requests import Request, Response-from requests.exceptions import HTTPError+from requests.exceptions import HTTPError, RequestExceptionfrom products.warehouse_sources.backend.temporal.data_imports.sources.clerk.clerk import (ClerkPaginator,@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.cler_strip_sensitive_fields,clerk_source,get_resources,+ validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.clerk.settings import (CLERK_ENDPOINTS,@@ -559,3 +560,38 @@ class TestClerkRetiredEndpoints:resumable_source_manager=manager,logger=MagicMock(),)+++_VALIDATE_SESSION = "products.warehouse_sources.backend.temporal.data_imports.sources.clerk.clerk.make_tracked_session"+++class TestClerkValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected_substring"),+ [+ (401, "invalid or has been revoked"),+ (403, "does not have permission"),+ (500, "Couldn't validate your Clerk secret key"),+ ],+ )+ def test_maps_status_to_curated_message_without_leaking_raw_body(+ self, status_code: int, expected_substring: str+ ) -> None:+ # A regression that forwards Clerk's response body (or errors[0].message) back to the wizard+ # would surface this sentinel; the curated copy must not.+ sentinel = "RAW-CLERK-BODY-SENTINEL"+ response = _make_http_response({"errors": [{"message": sentinel}]}, status_code=status_code)+ with patch(_VALIDATE_SESSION) as mock_session:+ mock_session.return_value.get.return_value = response+ is_valid, message = validate_credentials("sk_test_key")+ assert is_valid is False+ assert expected_substring in (message or "")+ assert sentinel not in (message or "")++ def test_network_error_returns_actionable_message_without_leaking_exception(self) -> None:+ with patch(_VALIDATE_SESSION) as mock_session:+ mock_session.return_value.get.side_effect = RequestException("connection reset by peer")+ is_valid, message = validate_credentials("sk_test_key")+ assert is_valid is False+ assert "Couldn't reach Clerk" in (message or "")+ assert "connection reset by peer" not in (message or "")