: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): say why the Search Console property list is empty (#95545)
Tom Owersec1739eb348c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.pyindex 4998c2e6678a..41eb04ef6696 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.google_search_console import (GoogleSearchConsoleResumeConfig,+ _is_quota_error,google_search_console_session,google_search_console_source,list_sites,@@ -62,6 +63,27 @@ _LIST_SITES_ERROR = ("PostHog couldn't reach Google Search Console to list your properties. Please try again in a few minutes.")+# Listing properties fails three ways that need three different next steps, and Google reports the+# first two both as a 403: an exhausted quota, an account that can't read any property, and a token+# that no longer works. Telling a user to reconnect covers only the last one.+_PROPERTY_LIST_QUOTA_ERROR = "Google is rate limiting Search Console requests. Wait a minute, then try again."+_PROPERTY_LIST_ACCESS_ERROR = (+ "The connected Google account can't read any Search Console property. Reconnect and allow "+ "Search Console access, or use the account that owns the property."+)+_PROPERTY_LIST_CREDENTIALS_ERROR = (+ "Google rejected the credentials for this connection. Reconnect your Google account, then pick a property."+)+++def _property_list_http_error(error: requests.HTTPError) -> str:+ response = error.response+ if response is not None and _is_quota_error(response):+ return _PROPERTY_LIST_QUOTA_ERROR+ if response is not None and response.status_code == 403:+ return _PROPERTY_LIST_ACCESS_ERROR+ return _PROPERTY_LIST_CREDENTIALS_ERROR+@SourceRegistry.registerclass GoogleSearchConsoleSource(@@ -109,13 +131,10 @@ class GoogleSearchConsoleSource(except requests.HTTPError as e:status = e.response.status_code if e.response is not None else Noneif status in (401, 403):- # The token refreshed fine but the connected Google account isn't authorized to read- # Search Console — a customer-side connection issue. Surface an actionable message the- # endpoint turns into a 400 rather than an unhandled 500.- raise IntegrationAccountListingError(- "Google Search Console rejected the credentials. Please reconnect your account "- "and ensure it has read access to the property."- )+ # The token refreshed fine but Google still refused the listing — a customer-side+ # connection issue. Surface an actionable message the endpoint turns into a 400+ # rather than an unhandled 500.+ raise IntegrationAccountListingError(_property_list_http_error(e))raiseexcept RefreshError:# The stored OAuth token is revoked/expired/missing scopes — raised while AuthorizedSession@@ -252,10 +271,7 @@ class GoogleSearchConsoleSource(except requests.HTTPError as e:status = e.response.status_code if e.response is not None else Noneif status in (401, 403):- return (- False,- "Google Search Console rejected the credentials. Please reconnect your account and ensure it has read access to the property.",- )+ return False, _property_list_http_error(e)capture_exception(e)return False, _LIST_SITES_ERRORexcept RefreshError:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.pyindex c391a9890434..f92b6c618494 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py@@ -191,13 +191,15 @@ def test_missing_integration_is_non_retryable():@pytest.mark.parametrize(- "status_code,expected_substring",+ "status_code,body,expected_substring",[- (401, "rejected the credentials"),- (403, "rejected the credentials"),+ (401, {}, "Reconnect your Google account"),+ (403, {}, "can't read any Search Console property"),+ # A quota 403 says nothing about the connection, so it must not send the user reconnecting.+ (403, {"error": {"errors": [{"domain": "usageLimits", "reason": "rateLimitExceeded"}]}}, "rate limiting"),],)-def test_validate_credentials_handles_auth_failures(status_code, expected_substring):+def test_validate_credentials_handles_auth_failures(status_code, body, expected_substring):import requestswith mock.patch(@@ -205,6 +207,7 @@ def test_validate_credentials_handles_auth_failures(status_code, expected_substr) as mock_session_factory:response = mock.MagicMock()response.status_code = status_code+ response.json.return_value = bodyerr = requests.HTTPError(response=response)session = mock.MagicMock()session.get.return_value.raise_for_status.side_effect = err@@ -220,6 +223,40 @@ def test_validate_credentials_handles_auth_failures(status_code, expected_substrassert expected_substring in (message or "")+ "body,expected_substring",+ [+ ({}, "can't read any Search Console property"),+ ({"error": {"errors": [{"domain": "usageLimits", "reason": "rateLimitExceeded"}]}}, "rate limiting"),+ ],+)+def test_get_oauth_accounts_reports_why_the_property_list_failed(body, expected_substring):+ import requests++ from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (+ IntegrationAccountListingError,+ )++ response = mock.MagicMock()+ response.status_code = 403+ response.json.return_value = body+ err = requests.HTTPError(response=response)++ with (+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.source.google_search_console_session"+ ),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.source.list_sites",+ side_effect=err,+ ),+ pytest.raises(IntegrationAccountListingError) as raised,+ ):+ GoogleSearchConsoleSource().get_oauth_accounts(integration_id=1, team_id=1)++ assert expected_substring in str(raised.value)++def test_validate_credentials_missing_integration_returns_reconnect_message():from posthog.models.integration import Integrationdiff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex e83aa7c51f92..3e1da2462d13 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -13141,8 +13141,15 @@ class TestOAuthAccountsEndpoint(APIBaseTest):assert [a["value"] for a in response.json()["accounts"]] == ["PostHog/posthog"]mock_gh.return_value.list_cached_repositories.assert_called_once_with(search="posthog", limit=100, offset=0)- @parameterized.expand([(401,), (403,)])- def test_gsc_auth_error_returns_actionable_400(self, status_code: int):+ # A 401 is always a stale connection. A 403 without quota markers means the account can't read+ # any property, which is a different next step — see `_property_list_http_error`.+ @parameterized.expand(+ [+ (401, "reconnect your google account"),+ (403, "can't read any search console property"),+ ]+ )+ def test_gsc_auth_error_returns_actionable_400(self, status_code: int, expected_substring: str):integration = self._gsc_integration()with (patch(f"{self._GSC_MODULE}.google_search_console_session"),@@ -13151,7 +13158,7 @@ class TestOAuthAccountsEndpoint(APIBaseTest):response = self.client.get(self._url("GoogleSearchConsole", integration.id))assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content- assert "reconnect your account" in str(response.json()).lower()+ assert expected_substring in str(response.json()).lower()def _google_ads_integration(self) -> Integration:return Integration.objects.create(