: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(google-search-console): normalize property URL before validation (#64221)
Tom Owers41dd55a6dbac
diff --git a/posthog/temporal/data_imports/sources/google_search_console/google_search_console.py b/posthog/temporal/data_imports/sources/google_search_console/google_search_console.pyindex e79c9807209f..5aa86b2e59f8 100644--- a/posthog/temporal/data_imports/sources/google_search_console/google_search_console.py+++ b/posthog/temporal/data_imports/sources/google_search_console/google_search_console.py@@ -4,7 +4,7 @@ import threadingimport dataclassesimport collections.abcfrom typing import Any-from urllib.parse import quote+from urllib.parse import parse_qs, quote, unquote, urlparsefrom django.conf import settingsfrom django.db import close_old_connections@@ -104,6 +104,36 @@ class GoogleSearchConsoleResumeConfig:start_row: int # next startRow within current_date+def normalize_site_url(raw: str) -> str:+ """Coerce a user-entered property URL toward Google's canonical form.++ Search Console identifies a property as either ``https://example.com/`` (URL-prefix,+ trailing slash required) or ``sc-domain:example.com`` (domain). The API matches these+ strings byte-for-byte, but users routinely enter values that don't: a percent-encoded+ string copied from a URL bar (``sc-domain%3Aexample.com``), the full Search Console UI+ URL, or a URL-prefix property with the trailing slash dropped. Resolve the cases we can+ handle unambiguously and leave the rest untouched — a bare hostname (no scheme, no+ ``sc-domain:`` prefix) stays as-is because we can't tell which property type was meant.+ """+ site = raw.strip()++ # The Search Console UI URL carries the property in its `resource_id` query param.+ if site.startswith("https://search.google.com/"):+ resource_id = parse_qs(urlparse(site).query).get("resource_id")+ if resource_id:+ site = resource_id[0].strip()++ # Decode percent-encoding ('sc-domain%3A...', 'https%3A%2F%2F...%2F') copied from a URL.+ if "%" in site:+ site = unquote(site).strip()++ # URL-prefix properties are canonically stored with a trailing slash.+ if site.startswith(("http://", "https://")) and not site.endswith("/"):+ site = site + "/"++ return site++def _credentials(integration_id: int, team_id: int) -> OAuthCredentials:# Temporal activities run in a thread pool where Django DB connections can go# stale between uses (Postgres closes the connection server-side). This is@@ -308,6 +338,10 @@ def google_search_console_source(dimensions = schema["dimensions"]primary_keys = list(schema["primary_key"])+ # Match the canonicalization done at validation time so a property that validated (e.g. a+ # percent-encoded or trailing-slash-less entry) resolves to the same string Google expects.+ site_url = normalize_site_url(config.site_url)+name = NamingConvention.normalize_identifier(resource_name)def get_rows() -> collections.abc.Iterator[list[dict[str, Any]]]:@@ -338,7 +372,7 @@ def google_search_console_source(while True:rows = _query_search_analytics(session=session,- site_url=config.site_url,+ site_url=site_url,start_date=iso,end_date=iso,dimensions=dimensions,diff --git a/posthog/temporal/data_imports/sources/google_search_console/source.py b/posthog/temporal/data_imports/sources/google_search_console/source.pyindex 88932633404a..35ec729b8756 100644--- a/posthog/temporal/data_imports/sources/google_search_console/source.py+++ b/posthog/temporal/data_imports/sources/google_search_console/source.py@@ -26,6 +26,7 @@ from posthog.temporal.data_imports.sources.google_search_console.google_search_cgoogle_search_console_session,google_search_console_source,list_sites,+ normalize_site_url,)from posthog.temporal.data_imports.sources.google_search_console.settings import (SEARCH_ANALYTICS_INCREMENTAL_FIELD,@@ -149,7 +150,7 @@ class GoogleSearchConsoleSource(return False, f"Failed to list Google Search Console sites: {e}"normalized = {site.get("siteUrl"): site.get("permissionLevel") for site in sites}- site_url = config.site_url+ site_url = normalize_site_url(config.site_url)if site_url not in normalized:return (False,diff --git a/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py b/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.pyindex acff8363ae66..7cce5dff18e2 100644--- a/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py+++ b/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py@@ -23,6 +23,7 @@ from posthog.temporal.data_imports.sources.google_search_console.google_search_c_resolve_window,_row_to_dict,google_search_console_source,+ normalize_site_url,)TODAY = dt.date(2026, 4, 30)@@ -425,3 +426,33 @@ def test_throttle_spaces_requests_per_site(monkeypatch):gsc._throttle("sc-domain:example.com")assert sleeps == [pytest.approx(gsc._MIN_REQUEST_INTERVAL_SECONDS)]+++ "raw,expected",+ [+ # Already canonical — left untouched.+ ("https://example.com/", "https://example.com/"),+ ("sc-domain:example.com", "sc-domain:example.com"),+ # Percent-encoded values copied from a URL bar.+ ("sc-domain%3Abidsstack.com", "sc-domain:bidsstack.com"),+ ("sc-domain%3Atopol.io", "sc-domain:topol.io"),+ ("https%3A%2F%2Fexample.com%2F", "https://example.com/"),+ # URL-prefix property missing its trailing slash.+ ("https://agentic30.app", "https://agentic30.app/"),+ ("https://docebo.com", "https://docebo.com/"),+ # Surrounding whitespace.+ (" https://example.com/ ", "https://example.com/"),+ # The full Search Console UI URL — the property lives in resource_id.+ (+ "https://search.google.com/search-console/performance/search-analytics"+ "?resource_id=https%3A%2F%2Fwww.viamar.ca%2F&metrics=CLICKS%2CIMPRESSIONS",+ "https://www.viamar.ca/",+ ),+ # Bare hostname is ambiguous (URL-prefix vs domain) — left untouched.+ ("agentic30.app", "agentic30.app"),+ ("agentic30.app/", "agentic30.app/"),+ ],+)+def test_normalize_site_url(raw, expected):+ assert normalize_site_url(raw) == expecteddiff --git a/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py b/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.pyindex 09fac726c374..36c055296740 100644--- a/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py+++ b/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py@@ -198,6 +198,36 @@ def test_validate_credentials_rejects_unverified_user():assert "verified access" in (message or "")+ "entered,site_url",+ [+ # Percent-encoded domain property copied from a URL bar.+ ("sc-domain%3Aexample.com", "sc-domain:example.com"),+ # URL-prefix property missing its trailing slash.+ ("https://example.com", "https://example.com/"),+ # Full Search Console UI URL pasted in.+ (+ "https://search.google.com/search-console/performance/search-analytics"+ "?resource_id=https%3A%2F%2Fexample.com%2F",+ "https://example.com/",+ ),+ ],+)+def test_validate_credentials_normalizes_site_url_before_lookup(entered, site_url):+ config = GoogleSearchConsoleSourceConfig(site_url=entered, google_search_console_integration_id=1)+ with (+ mock.patch("posthog.temporal.data_imports.sources.google_search_console.source.google_search_console_session"),+ mock.patch(+ "posthog.temporal.data_imports.sources.google_search_console.source.list_sites",+ return_value=[{"siteUrl": site_url, "permissionLevel": "siteOwner"}],+ ),+ ):+ ok, message = GoogleSearchConsoleSource().validate_credentials(config, team_id=1)++ assert ok is True+ assert message is None++def test_validate_credentials_succeeds_for_verified_site():with (mock.patch("posthog.temporal.data_imports.sources.google_search_console.source.google_search_console_session"),