: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-sheets): treat a malformed service account key as non-reportable (#117512)
posthog[bot]6175af7725f0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.pyindex 014909ac1e5e..164a571bb0b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py@@ -13,6 +13,7 @@ from google.auth.transport.requests import AuthorizedSessionfrom google.oauth2 import service_accountfrom gspread.utils import numericise_all+from posthog.credentials_service.errors import CredentialsSecretErrorfrom posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention@@ -44,6 +45,20 @@ _REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (30.0, 120.0)GOOGLE_SHEETS_API_VERSION_V4 = "v4"+class GoogleSheetsServiceAccountKeyInvalidError(CredentialsSecretError):+ """PostHog's own Google Sheets service account key does not parse, for example it is not valid PEM.++ Not reportable: the key is PostHog's, so the customer can't fix it, and a bad read clears when+ the key is good again. The sync activities log it as a warning and Temporal retries them.+ """++ reportable = False++ def __init__(self) -> None:+ key = "GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY"+ super().__init__(key, f"{key} is not a valid service account key")++def google_sheets_client() -> gspread.Client:resolved = credentials_service.get_secrets([@@ -53,15 +68,19 @@ def google_sheets_client() -> gspread.Client:"GOOGLE_SHEETS_SERVICE_ACCOUNT_CLIENT_EMAIL",])- credentials = service_account.Credentials.from_service_account_info(- {- "private_key": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY"],- "private_key_id": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY_ID"],- "token_uri": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_TOKEN_URI"],- "client_email": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_CLIENT_EMAIL"],- },- scopes=["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"],- )+ try:+ credentials = service_account.Credentials.from_service_account_info(+ {+ "private_key": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY"],+ "private_key_id": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY_ID"],+ "token_uri": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_TOKEN_URI"],+ "client_email": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_CLIENT_EMAIL"],+ },+ scopes=["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"],+ )+ except ValueError as e:+ # google-auth raises a bare ValueError for a malformed key, for example not valid PEM.+ raise GoogleSheetsServiceAccountKeyInvalidError() from e# gspread skips wrapping any session you pass in with `AuthorizedSession`, so a plain# `requests.Session` would send unauthenticated requests and Google returns 403. Build the# `AuthorizedSession` ourselves and mount the tracked adapter to keep request metering.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.pyindex 4a5477756423..cb03273d96b7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)from products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets import (GOOGLE_SHEETS_API_VERSION_V4,+ GoogleSheetsServiceAccountKeyInvalidError,discover_worksheet_schemas,google_sheets_client,google_sheets_source,@@ -171,9 +172,8 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):) -> tuple[bool, str | None]:try:client = google_sheets_client()- except ValueError:- # google-auth raises ValueError when this instance's service account key is malformed,- # for example not valid PEM. The user can't fix that, so return a clear message, not a 500.+ except GoogleSheetsServiceAccountKeyInvalidError:+ # The user can't fix this instance's service account key, so return a clear message, not a 500.logger.exception("google_sheets_service_account_key_invalid", team_id=team_id)return (False,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.pyindex d70aea71ed2b..00e8508b3210 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py@@ -8,6 +8,8 @@ import gspreadimport requestsfrom google.auth import exceptions as google_auth_exceptions+from posthog.credentials_service.errors import CredentialsServiceFailure+from products.warehouse_sources.backend.models.external_data_schema import SCHEMA_RESOURCE_ID_METADATA_KEYfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googlesheets import (GoogleSheetsSourceConfig,@@ -15,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets import (_REQUEST_TIMEOUT_SECONDS,GOOGLE_SHEETS_API_VERSION_V4,+ GoogleSheetsServiceAccountKeyInvalidError,_assert_unique_normalized_column_names,_get_worksheet,_retry_on_transient_api_error,@@ -749,13 +752,32 @@ def test_validate_credentials_maps_google_auth_error(auth_error, expect_retry_hiassert "try again in a moment" not in (error_message or "").lower()-def test_validate_credentials_handles_malformed_service_account_key():- with mock.patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.source.google_sheets_client",- side_effect=ValueError("No key could be detected."),+def malformed_service_account_key():+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets"+ with (+ mock.patch(f"{module}.credentials_service.get_secrets", side_effect=lambda keys: dict.fromkeys(keys, "x")),+ mock.patch(+ f"{module}.service_account.Credentials.from_service_account_info",+ side_effect=ValueError("No key could be detected."),+ ),):- config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")- is_valid, error_message = GoogleSheetsSource().validate_credentials(config, team_id=1)+ yield++[email protected]("malformed_service_account_key")+def test_google_sheets_client_raises_non_reportable_error_for_malformed_service_account_key():+ with pytest.raises(GoogleSheetsServiceAccountKeyInvalidError) as exc_info:+ google_sheets_client()++ assert isinstance(exc_info.value, CredentialsServiceFailure)+ assert exc_info.value.reportable is False++[email protected]("malformed_service_account_key")+def test_validate_credentials_handles_malformed_service_account_key():+ config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")+ is_valid, error_message = GoogleSheetsSource().validate_credentials(config, team_id=1)assert is_valid is Falseassert "isn't configured correctly on this PostHog instance" in (error_message or "")