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(integrations): reject a Google Cloud key file token endpoint that is not Google's (#102485)

Daniel RC6d135b4afa5c
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 4cb3f5d64a18..46346f8e98a4 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -683,6 +683,38 @@ class TestDatabricksIntegration:
assert not Integration.objects.filter(team=self.team, kind="databricks").exists()
+class TestGoogleCloudServiceAccountIntegration:
+ @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 test_rejects_key_file_token_uri_that_is_not_google(self, client: HttpClient):
+ client.force_login(self.user)
+
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {
+ "kind": "google-cloud-service-account",
+ "config": {
+ "service_account_email": "[email protected]",
+ "project_id": "proj",
+ "private_key": "key",
+ "private_key_id": "key-id",
+ "token_uri": "https://relay.example.com/token",
+ },
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "not Google's OAuth token endpoint" in response.json()["detail"]
+ assert not Integration.objects.filter(team=self.team, kind="google-cloud-service-account").exists()
+
+
class TestAWSIntegration:
@pytest.fixture(
params=[
@@ -6591,7 +6623,11 @@ class TestPushIdentityVerificationAPI(APIBaseTest):
{
"kind": "firebase",
"config": {
- "key_info": {"type": "service_account", "project_id": "my-firebase-project"},
+ "key_info": {
+ "type": "service_account",
+ "project_id": "my-firebase-project",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ },
"push_identity_verification": "required",
},
},
@@ -6763,7 +6799,7 @@ class TestIntegrationMembershipPermissions(APIBaseTest):
"project_id": "hijacked-project",
"private_key": "new",
"private_key_id": "new",
- "token_uri": "new",
+ "token_uri": "https://oauth2.googleapis.com/token",
},
},
format="json",
diff --git a/posthog/cdp/templates/google_cloud_storage/test_template_google_cloud_storage.py b/posthog/cdp/templates/google_cloud_storage/test_template_google_cloud_storage.py
index e1157b2f1fdc..9bf1de7d0252 100644
--- a/posthog/cdp/templates/google_cloud_storage/test_template_google_cloud_storage.py
+++ b/posthog/cdp/templates/google_cloud_storage/test_template_google_cloud_storage.py
@@ -33,7 +33,10 @@ class TestTemplateMigration(BaseTest):
obj.team = self.team
obj.save()
PluginAttachment.objects.create(
- plugin_config=obj, contents=b'{"cloud": "key"}', key="googleCloudKeyJson", file_size=10
+ plugin_config=obj,
+ contents=b'{"cloud": "key", "token_uri": "https://oauth2.googleapis.com/token"}',
+ key="googleCloudKeyJson",
+ file_size=10,
)
template = TemplateGoogleCloudStorageMigrator.migrate(obj)
@@ -55,7 +58,10 @@ class TestTemplateMigration(BaseTest):
integration = Integration.objects.last()
assert integration is not None
assert integration.kind == "google-cloud-storage"
- assert integration.sensitive_config["key_info"] == {"cloud": "key"}
+ assert integration.sensitive_config["key_info"] == {
+ "cloud": "key",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ }
assert integration.sensitive_config.get("access_token") == "ACCESS_TOKEN"
@patch("google.oauth2.service_account.Credentials.from_service_account_info")
@@ -77,7 +83,10 @@ class TestTemplateMigration(BaseTest):
obj.team = self.team
obj.save()
PluginAttachment.objects.create(
- plugin_config=obj, contents=b'{"cloud": "key"}', key="googleCloudKeyJson", file_size=10
+ plugin_config=obj,
+ contents=b'{"cloud": "key", "token_uri": "https://oauth2.googleapis.com/token"}',
+ key="googleCloudKeyJson",
+ file_size=10,
)
template = TemplateGoogleCloudStorageMigrator.migrate(obj)
diff --git a/posthog/cdp/templates/google_pubsub/test_template_google_pubsub.py b/posthog/cdp/templates/google_pubsub/test_template_google_pubsub.py
index dc79257df646..7440153cd371 100644
--- a/posthog/cdp/templates/google_pubsub/test_template_google_pubsub.py
+++ b/posthog/cdp/templates/google_pubsub/test_template_google_pubsub.py
@@ -33,7 +33,10 @@ class TestTemplateMigration(BaseTest):
obj.team = self.team
obj.save()
PluginAttachment.objects.create(
- plugin_config=obj, contents=b'{"cloud": "key"}', key="googleCloudKeyJson", file_size=10
+ plugin_config=obj,
+ contents=b'{"cloud": "key", "token_uri": "https://oauth2.googleapis.com/token"}',
+ key="googleCloudKeyJson",
+ file_size=10,
)
template = TemplateGooglePubSubMigrator.migrate(obj)
@@ -61,7 +64,10 @@ class TestTemplateMigration(BaseTest):
integration = Integration.objects.last()
assert integration is not None
assert integration.kind == "google-pubsub"
- assert integration.sensitive_config["key_info"] == {"cloud": "key"}
+ assert integration.sensitive_config["key_info"] == {
+ "cloud": "key",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ }
assert integration.sensitive_config.get("access_token") == "ACCESS_TOKEN"
@patch("google.oauth2.service_account.Credentials.from_service_account_info")
@@ -83,7 +89,10 @@ class TestTemplateMigration(BaseTest):
obj.team = self.team
obj.save()
PluginAttachment.objects.create(
- plugin_config=obj, contents=b'{"cloud": "key"}', key="googleCloudKeyJson", file_size=10
+ plugin_config=obj,
+ contents=b'{"cloud": "key", "token_uri": "https://oauth2.googleapis.com/token"}',
+ key="googleCloudKeyJson",
+ file_size=10,
)
template = TemplateGooglePubSubMigrator.migrate(obj)
diff --git a/posthog/models/integration/google_cloud.py b/posthog/models/integration/google_cloud.py
index 25678f46cbe1..0cbb015b78b5 100644
--- a/posthog/models/integration/google_cloud.py
+++ b/posthog/models/integration/google_cloud.py
@@ -15,6 +15,34 @@ from . import model, refresh_tracking
logger = structlog.get_logger(__name__)
+# google-auth posts the signed service-account grant to whatever URL `token_uri` names, so a stored
+# key file decides where a worker sends an outbound request. Google issues service-account keys with
+# only these two endpoints, so any other value is hand-edited.
+GOOGLE_SERVICE_ACCOUNT_TOKEN_URIS = frozenset(
+ {"https://oauth2.googleapis.com/token", "https://accounts.google.com/o/oauth2/token"}
+)
+
+GOOGLE_SERVICE_ACCOUNT_INVALID_TOKEN_URI_ERROR = (
+ "The token_uri in your Google Cloud JSON key file is not Google's OAuth token endpoint. Please download "
+ "a fresh service account key from Google Cloud and re-upload the JSON file without editing it."
+)
+
+
+class InvalidGoogleTokenUriError(ValidationError):
+ """Still a 400 through DRF, and named so the batch-export retry classifier can match it."""
+
+ def __init__(self) -> None:
+ super().__init__(GOOGLE_SERVICE_ACCOUNT_INVALID_TOKEN_URI_ERROR)
+
+ def __str__(self) -> str:
+ return GOOGLE_SERVICE_ACCOUNT_INVALID_TOKEN_URI_ERROR
+
+
+def require_google_token_uri(token_uri: object) -> str:
+ if not isinstance(token_uri, str) or token_uri.strip() not in GOOGLE_SERVICE_ACCOUNT_TOKEN_URIS:
+ raise InvalidGoogleTokenUriError()
+ return token_uri.strip()
+
def is_unique_service_account_by_organization_id(service_account_email: str, organization_id: str) -> bool:
"""Check if the service account is only in one organization.
@@ -67,7 +95,7 @@ class GoogleCloudServiceAccountIntegration:
if isinstance(private_key, str) and isinstance(private_key_id, str) and isinstance(token_uri, str):
sensitive_config["private_key"] = private_key
sensitive_config["private_key_id"] = private_key_id
- sensitive_config["token_uri"] = token_uri
+ sensitive_config["token_uri"] = require_google_token_uri(token_uri)
is_impersonated = False
@@ -115,10 +143,12 @@ class GoogleCloudServiceAccountIntegration:
@property
def service_account_info(self) -> dict[str, str]:
+ # Rows written before the factory validated the field, or by another write path, still
+ # carry whatever the key file said. Every credential build reads through here.
return {
"private_key": self.integration.sensitive_config["private_key"],
"private_key_id": self.integration.sensitive_config["private_key_id"],
- "token_uri": self.integration.sensitive_config["token_uri"],
+ "token_uri": require_google_token_uri(self.integration.sensitive_config["token_uri"]),
"client_email": self.service_account_email,
"project_id": self.project_id,
}
@@ -142,6 +172,8 @@ class GoogleCloudIntegration:
else:
raise NotImplementedError(f"Google Cloud integration kind {kind} not implemented")
+ key_info["token_uri"] = require_google_token_uri(key_info.get("token_uri"))
+
try:
credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])
credentials.refresh(GoogleRequest())
@@ -194,6 +226,14 @@ class GoogleCloudIntegration:
raise NotImplementedError(f"Google Cloud integration kind {self.integration.kind} not implemented")
key_info = self.integration.sensitive_config.get("key_info", self.integration.sensitive_config)
+ try:
+ key_info["token_uri"] = require_google_token_uri(key_info.get("token_uri"))
+ except InvalidGoogleTokenUriError:
+ refresh_tracking.record_refresh_failure(
+ self.integration, reason=refresh_tracking.REFRESH_FAILURE_REASON_INVALID_TOKEN_URI
+ )
+ self.integration.save(update_fields=["config"])
+ raise
credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])
try:
diff --git a/posthog/models/integration/push.py b/posthog/models/integration/push.py
index f71febaabd23..15a65a93254e 100644
--- a/posthog/models/integration/push.py
+++ b/posthog/models/integration/push.py
@@ -16,6 +16,7 @@ from posthog.models.user import User
from posthog.plugins.plugin_server_api import reload_integrations_on_workers
from . import model, refresh_tracking
+from .google_cloud import InvalidGoogleTokenUriError, require_google_token_uri
logger = structlog.get_logger(__name__)
@@ -134,6 +135,8 @@ class FirebaseIntegration:
) -> "model.Integration":
scope = "https://www.googleapis.com/auth/firebase.messaging"
+ key_info["token_uri"] = require_google_token_uri(key_info.get("token_uri"))
+
try:
credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])
credentials.refresh(GoogleRequest())
@@ -191,6 +194,14 @@ class FirebaseIntegration:
scope = "https://www.googleapis.com/auth/firebase.messaging"
key_info = self.integration.sensitive_config.get("key_info", {})
+ try:
+ key_info["token_uri"] = require_google_token_uri(key_info.get("token_uri"))
+ except InvalidGoogleTokenUriError:
+ refresh_tracking.record_refresh_failure(
+ self.integration, reason=refresh_tracking.REFRESH_FAILURE_REASON_INVALID_TOKEN_URI
+ )
+ self.integration.save(update_fields=["config"])
+ raise
credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])
try:
diff --git a/posthog/models/integration/refresh_tracking.py b/posthog/models/integration/refresh_tracking.py
index dd05c37aa513..b16a393572e8 100644
--- a/posthog/models/integration/refresh_tracking.py
+++ b/posthog/models/integration/refresh_tracking.py
@@ -59,6 +59,7 @@ REFRESH_FAILURE_REASON_OTHER = "other"
# Not a provider response: the stored refresh token itself can't be decrypted, so no request was
# made. Terminal on the first occurrence, since no later attempt can make the secret readable.
REFRESH_FAILURE_REASON_UNREADABLE_SECRET = "unreadable_secret"
+REFRESH_FAILURE_REASON_INVALID_TOKEN_URI = "invalid_token_uri"
# Failures that say nothing about the grant: the provider was unavailable or throttling us. The
# credentials in hand are still good, so a caller refreshing on use must not flag the connection
@@ -112,9 +113,9 @@ def record_refresh_failure(integration: "model.Integration", *, reason: str = RE
itself is dead and only a customer re-auth can fix it, so after an unbroken streak of them the
integration goes terminal and the sweep stops retrying entirely. The streak is tracked
separately from the total failure count and resets on any other reason, so one transient
- invalid_grant amid e.g. a 5xx outage can't brick the integration. `unreadable_secret` goes
- terminal on the first occurrence - we never even reached the provider, and retrying can't make
- an undecryptable token readable. Other reasons (invalid_client, 5xx, network, rate_limited)
+ invalid_grant amid e.g. a 5xx outage can't brick the integration. `unreadable_secret` and
+ `invalid_token_uri` go terminal on the first occurrence - we never even reached the provider,
+ and retrying can't make an undecryptable token readable or an edited key file valid. Other reasons (invalid_client, 5xx, network, rate_limited)
never go terminal - a platform-side credential fix must let the fleet self-recover.
Returns "first"/"retry" for the metric's `attempt` label - a spike in first failures means
@@ -127,7 +128,7 @@ def record_refresh_failure(integration: "model.Integration", *, reason: str = RE
integration.config["refresh_next_attempt_at"] = int(time.time()) + min(
REFRESH_BACKOFF_BASE_SECONDS * 2 ** (count - 1), REFRESH_BACKOFF_MAX_SECONDS
)
- if reason == REFRESH_FAILURE_REASON_UNREADABLE_SECRET:
+ if reason in (REFRESH_FAILURE_REASON_UNREADABLE_SECRET, REFRESH_FAILURE_REASON_INVALID_TOKEN_URI):
integration.config.pop("refresh_invalid_grant_count", None)
if not integration.config.get("refresh_terminal"):
integration.config["refresh_terminal"] = True
diff --git a/posthog/models/test/integration/test_google_cloud.py b/posthog/models/test/integration/test_google_cloud.py
index 6115057c15bf..cb7551e2a38b 100644
--- a/posthog/models/test/integration/test_google_cloud.py
+++ b/posthog/models/test/integration/test_google_cloud.py
@@ -7,14 +7,23 @@ from typing import Optional
import pytest
import time_machine
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
+from parameterized import parameterized
from rest_framework.exceptions import ValidationError
from posthog.models.integration import GoogleCloudIntegration, GoogleCloudServiceAccountIntegration, Integration
+from posthog.models.integration.google_cloud import GOOGLE_SERVICE_ACCOUNT_INVALID_TOKEN_URI_ERROR
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+NON_GOOGLE_TOKEN_URIS = [
+ ("relay", "https://relay.example.com/token"),
+ ("plain_http_google", "http://oauth2.googleapis.com/token"),
+ ("lookalike_host", "https://oauth2.googleapis.com.example.com/token"),
+ ("link_local", "http://169.254.169.254/latest/meta-data/"),
+]
+
class TestGoogleCloudIntegrationModel(BaseTest):
mock_keyfile = {
@@ -165,8 +174,87 @@ class TestGoogleCloudIntegrationModel(BaseTest):
assert token == "ACCESS_TOKEN"
assert "access_token" not in integration.config
+ @parameterized.expand(NON_GOOGLE_TOKEN_URIS)
+ @patch("google.oauth2.service_account.Credentials.from_service_account_info")
+ def test_rejects_key_file_token_uri_that_is_not_google(
+ self, _name: str, token_uri: str, mock_credentials: MagicMock
+ ) -> None:
+ with pytest.raises(ValidationError):
+ GoogleCloudIntegration.integration_from_key(
+ "google-pubsub", {**self.mock_keyfile, "token_uri": token_uri}, self.team.id, self.user
+ )
+
+ mock_credentials.assert_not_called()
+ assert not Integration.objects.filter(team=self.team, kind="google-pubsub").exists()
+
+ @parameterized.expand(NON_GOOGLE_TOKEN_URIS)
+ @patch("google.oauth2.service_account.Credentials.from_service_account_info")
+ def test_stored_key_file_with_non_google_token_uri_never_refreshes(
+ self, _name: str, token_uri: str, mock_credentials: MagicMock
+ ) -> None:
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="google-pubsub",
+ integration_id="stored-before-validation",
+ config={"refreshed_at": 0, "expires_in": 1},
+ sensitive_config={"key_info": {**self.mock_keyfile, "token_uri": token_uri}, "access_token": "OLD"},
+ )
+
+ with pytest.raises(ValidationError):
+ GoogleCloudIntegration(integration).refresh_access_token()
+
+ mock_credentials.assert_not_called()
+ integration.refresh_from_db()
+ assert integration.config["refresh_failure_count"] == 1
+ assert integration.config["refresh_terminal"] is True
+
class TestGoogleCloudServiceAccountIntegration(BaseTest):
+ @parameterized.expand(NON_GOOGLE_TOKEN_URIS)
+ def test_rejects_key_file_token_uri_that_is_not_google(self, _name: str, token_uri: str) -> None:
+ with pytest.raises(ValidationError):
+ GoogleCloudServiceAccountIntegration.integration_from_service_account(
+ team_id=self.team.pk,
+ organization_id=str(self.team.organization.id),
+ service_account_email="[email protected]",
+ project_id="test",
+ private_key="something",
+ private_key_id="something",
+ token_uri=token_uri,
+ )
+
+ assert not Integration.objects.filter(team_id=self.team.pk, kind="google-cloud-service-account").exists()
+
+ @parameterized.expand(NON_GOOGLE_TOKEN_URIS)
+ def test_stored_key_file_with_non_google_token_uri_never_builds_credentials(
+ self, _name: str, token_uri: str
+ ) -> None:
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="google-cloud-service-account",
+ integration_id="stored-before-validation",
+ config={"project_id": "test", "service_account_email": "[email protected]"},
+ sensitive_config={"private_key": "something", "private_key_id": "something", "token_uri": token_uri},
+ )
+
+ with pytest.raises(ValidationError) as exc_info:
+ _ = GoogleCloudServiceAccountIntegration(integration).service_account_info
+
+ assert str(exc_info.value) == GOOGLE_SERVICE_ACCOUNT_INVALID_TOKEN_URI_ERROR
+
+ def test_stores_key_file_token_uri_stripped(self) -> None:
+ integration = GoogleCloudServiceAccountIntegration.integration_from_service_account(
+ team_id=self.team.pk,
+ organization_id=str(self.team.organization.id),
+ service_account_email="[email protected]",
+ project_id="test",
+ private_key="something",
+ private_key_id="something",
+ token_uri=" https://oauth2.googleapis.com/token ",
+ )
+
+ assert integration.sensitive_config["token_uri"] == "https://oauth2.googleapis.com/token"
+
def test_raises_on_duplicate_service_account_email(self):
_ = GoogleCloudServiceAccountIntegration.integration_from_service_account(
team_id=self.team.pk,
@@ -190,7 +278,7 @@ class TestGoogleCloudServiceAccountIntegration(BaseTest):
project_id="test",
private_key="something",
private_key_id="something",
- token_uri="something",
+ token_uri="https://oauth2.googleapis.com/token",
)
other_org = Organization.objects.create(name="other org")
@@ -209,7 +297,7 @@ class TestGoogleCloudServiceAccountIntegration(BaseTest):
project_id="test",
private_key="something",
private_key_id="something",
- token_uri="something",
+ token_uri="https://oauth2.googleapis.com/token",
)
assert (
diff --git a/posthog/models/test/test_firebase_integration.py b/posthog/models/test/test_firebase_integration.py
index 689313a8184b..807996b9a8e4 100644
--- a/posthog/models/test/test_firebase_integration.py
+++ b/posthog/models/test/test_firebase_integration.py
@@ -129,6 +129,34 @@ class TestFirebaseIntegration(BaseTest):
with self.assertRaises(ValidationError):
FirebaseIntegration.integration_from_key(key_info_no_project, self.team.id)
+ @patch("posthog.models.integration.push.GoogleRequest")
+ @patch("posthog.models.integration.push.service_account.Credentials.from_service_account_info")
+ def test_rejects_key_file_token_uri_that_is_not_google(self, mock_from_sa, mock_google_request) -> None:
+ with self.assertRaises(ValidationError):
+ FirebaseIntegration.integration_from_key(
+ {**FAKE_KEY_INFO, "token_uri": "https://relay.example.com/token"}, self.team.id
+ )
+
+ mock_from_sa.assert_not_called()
+
+ @patch("posthog.models.integration.push.GoogleRequest")
+ @patch("posthog.models.integration.push.service_account.Credentials.from_service_account_info")
+ def test_stored_key_file_with_non_google_token_uri_never_refreshes(self, mock_from_sa, mock_google_request) -> None:
+ integration = self._create_firebase_integration()
+ integration.sensitive_config = {
+ **integration.sensitive_config,
+ "key_info": {**FAKE_KEY_INFO, "token_uri": "https://relay.example.com/token"},
+ }
+ integration.save()
+
+ with self.assertRaises(ValidationError):
+ FirebaseIntegration(integration).refresh_access_token()
+
+ mock_from_sa.assert_not_called()
+ integration.refresh_from_db()
+ assert integration.config["refresh_failure_count"] == 1
+ assert integration.config["refresh_terminal"] is True
+
def test_wrapper_properties(self):
integration = self._create_firebase_integration()
wrapper = FirebaseIntegration(integration)
diff --git a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
index 4b8e54f66b31..639f09b9da03 100644
--- a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
@@ -37,6 +37,7 @@ from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
from posthog.models.integration import GoogleCloudServiceAccountIntegration, Integration
+from posthog.models.integration.google_cloud import InvalidGoogleTokenUriError, require_google_token_uri
from posthog.models.team import Team
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import Heartbeater
@@ -81,6 +82,8 @@ from products.batch_exports.backend.temporal.utils import (
NON_RETRYABLE_ERROR_TYPES = (
# Raised on missing permissions.
"Forbidden",
+ # The stored key file names a token endpoint that is not Google's; only a re-upload fixes it.
+ "InvalidGoogleTokenUriError",
# Invalid token.
"RefreshError",
# Usually means the dataset or project_id doesn't exist.
@@ -635,6 +638,7 @@ class BigQueryClient:
def from_service_account_inputs(
cls, private_key: str, private_key_id: str, token_uri: str, client_email: str, project_id: str
) -> typing.Self:
+ token_uri = require_google_token_uri(token_uri)
credentials = service_account.Credentials.from_service_account_info(
{
"private_key": private_key,
@@ -1521,6 +1525,8 @@ async def insert_into_bigquery_activity_from_stage(inputs: BigQueryInsertInputs)
await ensure_our_google_cloud_credentials_are_valid()
try:
bq_client = BigQueryClient.from_service_account_integration(google_cloud_integration)
+ except InvalidGoogleTokenUriError:
+ raise
except Exception:
LOGGER.exception("Initialize client from service account failed")
# TODO: Migrate everyone and remove this
diff --git a/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_client.py b/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_client.py
index 948dbc316ba3..d608cdf5224f 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_client.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_client.py
@@ -6,6 +6,8 @@ from unittest.mock import MagicMock
from google.cloud import bigquery
+from posthog.models.integration.google_cloud import InvalidGoogleTokenUriError
+
from products.batch_exports.backend.temporal.destinations.bigquery_batch_export import (
BigQueryClient,
BigQueryField,
@@ -179,3 +181,14 @@ async def test_from_service_account_integration(
results = list(client.sync_client.query("SELECT 1").result())
assert results[0].values()[0] == 1
+
+
+def test_from_service_account_inputs_rejects_token_uri_that_is_not_google():
+ with pytest.raises(InvalidGoogleTokenUriError):
+ BigQueryClient.from_service_account_inputs(
+ private_key="key",
+ private_key_id="key-id",
+ token_uri="https://relay.example.com/token",
+ client_email="[email protected]",
+ project_id="proj",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
index e20c5073be9c..af9d149be1de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
@@ -48,6 +48,11 @@ from google.oauth2 import service_account
from structlog.types import FilteringBoundLogger
from posthog.exceptions_capture import capture_exception
+from posthog.models.integration.google_cloud import (
+ GOOGLE_SERVICE_ACCOUNT_INVALID_TOKEN_URI_ERROR,
+ InvalidGoogleTokenUriError,
+ require_google_token_uri,
+)
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_TABLE_SIZE_BYTES
@@ -173,18 +178,8 @@ BIGQUERY_INVALID_KEY_FILE_ERROR = (
"corrupted. Please download a fresh service account key from Google Cloud and re-upload the JSON file."
)
-# `token_uri` comes from the uploaded key file, and google-auth posts the service-account grant to
-# whatever URL it names, so the field decides where a worker sends an outbound request. Google
-# issues service-account keys with only these two endpoints, so any other value is hand-edited.
-GOOGLE_SERVICE_ACCOUNT_TOKEN_URIS = frozenset(
- {"https://oauth2.googleapis.com/token", "https://accounts.google.com/o/oauth2/token"}
-)
-
# Matched in `BigQuerySource.get_non_retryable_errors`, so it must stay free of volatile data.
-BIGQUERY_INVALID_TOKEN_URI_ERROR = (
- "The token_uri in your Google Cloud JSON key file is not Google's OAuth token endpoint. Please download "
- "a fresh service account key from Google Cloud and re-upload the JSON file without editing it."
-)
+BIGQUERY_INVALID_TOKEN_URI_ERROR = GOOGLE_SERVICE_ACCOUNT_INVALID_TOKEN_URI_ERROR
class BigQueryInvalidTokenUriError(Exception):
@@ -192,10 +187,10 @@ class BigQueryInvalidTokenUriError(Exception):
def _require_google_token_uri(token_uri: str) -> str:
- token_uri = token_uri.strip()
- if token_uri not in GOOGLE_SERVICE_ACCOUNT_TOKEN_URIS:
+ try:
+ return require_google_token_uri(token_uri)
+ except InvalidGoogleTokenUriError:
raise BigQueryInvalidTokenUriError(BIGQUERY_INVALID_TOKEN_URI_ERROR)
- return token_uri
# Onboarding-time messages. Unlike the sync-path classifier these are only reached during credential