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(google_search_console): return actionable 400 when sites listing is forbidden (#65286)

Tom Owers6b5a69c28621
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 8a635566352c..57c89fb7d059 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -10,6 +10,7 @@ from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils import timezone
+import requests
import structlog
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_serializer
@@ -1013,7 +1014,19 @@ class IntegrationViewSet(
return Response(cached)
session = google_search_console_session(instance.id, instance.team_id)
- sites = list_sites(session)
+ try:
+ sites = list_sites(session)
+ except requests.HTTPError as e:
+ status_code = e.response.status_code if e.response is not None else None
+ if status_code in (401, 403):
+ # The token refreshed fine but the connected Google account isn't authorized to
+ # read Search Console — a customer-side connection issue, not a PostHog bug. Return
+ # an actionable 400 rather than letting the HTTPError surface as an unhandled 500.
+ raise ValidationError(
+ "Google Search Console rejected the credentials. Please reconnect your account "
+ "and ensure it has read access to the property."
+ )
+ raise
response_data = {"sites": sites}
cache.set(cache_key, response_data, GSC_AUTOCOMPLETE_CACHE_TTL_SECONDS)
return Response(response_data)
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 77a44846b722..3fdd544eb3e6 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -15,6 +15,7 @@ from django.core.cache import cache
from django.test.client import Client as HttpClient
from django.utils import timezone
+import requests
from parameterized import parameterized
from rest_framework import status
@@ -3735,3 +3736,80 @@ class TestIntegrationRequestAccessAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
mock_task.delay.assert_not_called()
mock_report.assert_not_called()
+
+
+class TestGoogleSearchConsoleSitesEndpoint:
+ _SESSION_PATH = (
+ "posthog.temporal.data_imports.sources.google_search_console."
+ "google_search_console.google_search_console_session"
+ )
+ _LIST_SITES_PATH = "posthog.temporal.data_imports.sources.google_search_console.google_search_console.list_sites"
+
+ @pytest.fixture(autouse=True)
+ def setup_integration(self, db):
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+
+ def _create_gsc_integration(self) -> Integration:
+ # No refresh_token → `_ensure_oauth_token_valid` treats the access token as valid and skips refresh.
+ return Integration.objects.create(
+ team=self.team,
+ kind="google-search-console",
+ config={},
+ sensitive_config={"access_token": "ya29.test"},
+ integration_id="gsc_test",
+ created_by=self.user,
+ )
+
+ def _url(self, integration_id: int) -> str:
+ return f"/api/environments/{self.team.pk}/integrations/{integration_id}/google_search_console_sites/"
+
+ @staticmethod
+ def _http_error(status_code: int) -> requests.HTTPError:
+ response = requests.Response()
+ response.status_code = status_code
+ return requests.HTTPError(f"{status_code} Client Error", response=response)
+
+ @patch(_LIST_SITES_PATH)
+ @patch(_SESSION_PATH)
+ def test_auth_error_returns_actionable_400(self, mock_session, mock_list_sites, client: HttpClient):
+ # 401 and 403 both mean the connected account can't read Search Console — the endpoint should
+ # turn either into an actionable 400 rather than letting it surface as an unhandled 500.
+ integration = self._create_gsc_integration()
+ client.force_login(self.user)
+
+ for status_code in (401, 403):
+ mock_list_sites.side_effect = self._http_error(status_code)
+
+ response = client.get(self._url(integration.id))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "reconnect your account" in str(response.json()).lower()
+
+ @patch(_LIST_SITES_PATH)
+ @patch(_SESSION_PATH)
+ def test_success_returns_sites(self, mock_session, mock_list_sites, client: HttpClient):
+ integration = self._create_gsc_integration()
+ mock_list_sites.return_value = [{"siteUrl": "https://example.com/", "permissionLevel": "siteOwner"}]
+
+ client.force_login(self.user)
+ response = client.get(self._url(integration.id))
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["sites"] == [{"siteUrl": "https://example.com/", "permissionLevel": "siteOwner"}]
+
+ @patch(_LIST_SITES_PATH)
+ @patch(_SESSION_PATH)
+ def test_non_auth_http_error_is_not_swallowed(self, mock_session, mock_list_sites, client: HttpClient):
+ # Only 401/403 are converted to a 400 — any other status keeps surfacing as a server error so
+ # a genuine bug isn't masked by the auth handling.
+ integration = self._create_gsc_integration()
+ mock_list_sites.side_effect = self._http_error(500)
+
+ client.force_login(self.user)
+ response = client.get(self._url(integration.id))
+
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, response.content