: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(bigquery): surface a clear error when Google rejects the credentials (#65121)
Tom Owers6e6b7d501288
diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.pyindex 052e103f83c5..956c0222f8b3 100644--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py@@ -24,6 +24,7 @@ from typing import Anyimport pyarrow as paimport structlogfrom google.api_core.exceptions import BadRequest, Forbidden, NotFound+from google.auth.exceptions import RefreshErrorfrom google.auth.transport.requests import AuthorizedSessionfrom google.cloud import bigquery, bigquery_storagefrom google.cloud.bigquery.job import QueryJobConfig@@ -58,6 +59,7 @@ from products.data_warehouse.backend.types import IncrementalFieldType, Partitio__all__ = ["BIGQUERY_TOKEN_RESPONSE_ERROR",+ "BigQueryCredentialsRejectedError","BigQueryImplementation","BigQueryTokenRefreshError","bigquery_client",@@ -92,6 +94,17 @@ class BigQueryTokenRefreshError(Exception):"""+class BigQueryCredentialsRejectedError(Exception):+ """Raised when Google rejects the service-account grant with `invalid_grant`.++ google-auth raises a `RefreshError` whose `str()` is an opaque tuple repr+ (`('invalid_grant: Invalid JWT Signature.', {...})`). A rotated/revoked key or deleted+ service account can't be recovered by retrying, so we re-raise it as this clear message+ rather than leaking the repr to the source-creation wizard. The message keeps the+ `invalid_grant` marker so `get_non_retryable_errors` still matches it on the sync path.+ """++def build_destination_table_prefix(schema_id: str | None) -> str:return f"__posthog_import_{schema_id.replace('-', '_') if schema_id else ''}"@@ -710,6 +723,18 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigquraise BigQueryTokenRefreshError(f"{BIGQUERY_TOKEN_RESPONSE_ERROR}. Please re-upload your service account key file and verify its token_uri.") from e+ except RefreshError as e:+ # google-auth rejects the service-account grant here with an `invalid_grant`+ # `RefreshError` whose `str()` is an opaque tuple repr. Surface the actionable message+ # instead of leaking it to the wizard. Other RefreshErrors (offline token_uri, transient+ # token-endpoint failures) carry their own diagnoses, so let them propagate unchanged.+ if "invalid_grant" not in str(e):+ raise+ raise BigQueryCredentialsRejectedError(+ "Your BigQuery service account credentials were rejected by Google (invalid_grant). "+ "The key may have been rotated or revoked, or the service account deleted. "+ "Please upload a new Google Cloud JSON key file."+ ) from efor row in rows:schema_list[row.table_name].append((row.column_name, row.data_type, row.is_nullable == "YES"))diff --git a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.pyindex 9a3cb472c110..820584c1d916 100644--- a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py+++ b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py@@ -6,11 +6,13 @@ from unittest import mockfrom dateutil import parserfrom google.api_core.exceptions import BadRequest, Forbidden, InvalidArgument, NotFound, PermissionDenied+from google.auth.exceptions import RefreshErrorfrom posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputsfrom posthog.temporal.data_imports.sources.bigquery import bigquery as bq_modulefrom posthog.temporal.data_imports.sources.bigquery.bigquery import (BIGQUERY_TOKEN_RESPONSE_ERROR,+ BigQueryCredentialsRejectedError,BigQueryImplementation,BigQueryTokenRefreshError,_bq_select_clause,@@ -132,6 +134,37 @@ def test_bigquery_get_columns_typeerror_handling(error_message, expected_type, iassert error_message in str(exc_info.value)+ "error_message,expected_type,is_rejected",+ [+ # An `invalid_grant` RefreshError means Google rejected the service-account grant (rotated+ # key, deleted account). `get_columns` must surface a clear message instead of the tuple repr.+ (+ "('invalid_grant: Invalid JWT Signature.', {'error': 'invalid_grant', 'error_description': 'Invalid JWT Signature.'})",+ BigQueryCredentialsRejectedError,+ True,+ ),+ # Transient/other RefreshErrors carry their own diagnoses and must propagate unchanged.+ ("('Failed to retrieve token', {'error': 'internal_failure'})", RefreshError, False),+ ],+)+def test_bigquery_get_columns_refresh_error_handling(error_message, expected_type, is_rejected):+ """`invalid_grant` RefreshErrors are wrapped as `BigQueryCredentialsRejectedError`; others propagate."""+ fake_client = mock.MagicMock()+ fake_client.query.side_effect = RefreshError(error_message)++ with pytest.raises(expected_type) as exc_info:+ BigQueryImplementation().get_columns(fake_client, _make_config(), names=None)++ assert isinstance(exc_info.value, BigQueryCredentialsRejectedError) == is_rejected+ if is_rejected:+ # The wizard shows this str() directly, and it must keep the `invalid_grant` marker so the+ # sync schema-discovery path still recognises it as non-retryable.+ assert "invalid_grant" in str(exc_info.value)+ assert "rejected by Google" in str(exc_info.value)+ assert any(key in str(exc_info.value) for key in BigQuerySource().get_non_retryable_errors())++@pytest.mark.parametrize("dataset_project,temporary_dataset,expected_dataset_project_id,expected_destination_dataset_id",[