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(warehouse-sources): validate the BigQuery key file token endpoint (#98498)

Daniel RCeefd642d6109
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 6e2203a2115a..1a51d1f8cb39 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
@@ -173,6 +173,31 @@ 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."
+)
+
+
+class BigQueryInvalidTokenUriError(Exception):
+ pass
+
+
+def _require_google_token_uri(token_uri: str) -> str:
+ token_uri = token_uri.strip()
+ if token_uri not in GOOGLE_SERVICE_ACCOUNT_TOKEN_URIS:
+ raise BigQueryInvalidTokenUriError(BIGQUERY_INVALID_TOKEN_URI_ERROR)
+ return token_uri
+
+
# Onboarding-time messages. Unlike the sync-path classifier these are only reached during credential
# validation, where the fix is to correct the input and try again rather than re-enable a sync.
BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR = (
@@ -425,6 +450,7 @@ def bigquery_client(
) -> typing.Iterator[bigquery.Client]:
"""Manage a BigQuery client."""
project_id = _normalize_identifier(project_id)
+ token_uri = _require_google_token_uri(token_uri)
credentials = service_account.Credentials.from_service_account_info(
{
"private_key": private_key,
@@ -483,6 +509,7 @@ def bigquery_storage_read_client(
):
"""Manage a BigQuery Storage client."""
project_id = _normalize_identifier(project_id)
+ token_uri = _require_google_token_uri(token_uri)
credentials = service_account.Credentials.from_service_account_info(
{
"private_key": private_key,
@@ -652,6 +679,10 @@ def validate_bigquery_credentials(
if not project_id or not private_key or not private_key_id or not client_email or not token_uri:
return False, BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR
+ try:
+ _require_google_token_uri(token_uri)
+ except BigQueryInvalidTokenUriError as e:
+ return False, str(e)
# Trim copy-paste whitespace from the identifiers before they reach BigQuery,
# which otherwise rejects them with an opaque `Invalid project ID`/`Invalid dataset ID`.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py
index e03a3d8bed5a..7c35de9ce09c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py
@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b
BIGQUERY_DATASET_NOT_FOUND_ERROR,
BIGQUERY_INVALID_IDENTIFIER_ERROR,
BIGQUERY_INVALID_KEY_FILE_ERROR,
+ BIGQUERY_INVALID_TOKEN_URI_ERROR,
BIGQUERY_ON_DEMAND_RATIO_EXCEEDED_ERROR,
BIGQUERY_RESOURCES_EXCEEDED_ERROR,
BIGQUERY_TOKEN_RESPONSE_ERROR,
@@ -75,6 +76,9 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
# be repaired by retrying — the user must re-upload an intact JSON key file. Matched on the
# stable "Unable to load PEM file" wording rather than the volatile InvalidData detail.
"Unable to load PEM file": BIGQUERY_INVALID_KEY_FILE_ERROR,
+ # Raised before any request when the key file's token endpoint is not Google's. The key
+ # file is the problem, so retrying cannot help; the user must re-upload an unedited key.
+ BIGQUERY_INVALID_TOKEN_URI_ERROR: BIGQUERY_INVALID_TOKEN_URI_ERROR,
# Writing query results into the `__posthog_import_...` temp tables PostHog creates
# (`WRITE_TRUNCATE` in `_run_destination_query_with_job_retry`, on incremental / view /
# row-filtered reads) needs write access on the dataset those tables live in. When the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
index 5a796b9709bf..2411304c1c7e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b
BIGQUERY_DATASET_NOT_FOUND_ERROR,
BIGQUERY_INVALID_IDENTIFIER_ERROR,
BIGQUERY_INVALID_KEY_FILE_ERROR,
+ BIGQUERY_INVALID_TOKEN_URI_ERROR,
BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR,
BIGQUERY_QUERY_CREATE_RETRY,
BIGQUERY_QUERY_JOB_RETRY,
@@ -39,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b
BigQueryDatasetNotFoundError,
BigQueryImplementation,
BigQueryInvalidIdentifierError,
+ BigQueryInvalidTokenUriError,
BigQueryTokenRefreshError,
_bq_select_clause,
_get_primary_keys_for_table,
@@ -108,7 +110,7 @@ def _make_config(
private_key="private-key",
private_key_id="private-key-id",
client_email="client-email",
- token_uri="token-uri",
+ token_uri="https://oauth2.googleapis.com/token",
),
dataset_id=dataset_id,
dataset_project=dataset_project,
@@ -867,7 +869,7 @@ def _run_delete_all_temp_destination_tables(side_effect, logger):
private_key="private-key",
private_key_id="private-key-id",
client_email="client-email",
- token_uri="token-uri",
+ token_uri="https://oauth2.googleapis.com/token",
logger=logger,
)
return mock_capture
@@ -1103,7 +1105,7 @@ def test_bigquery_validate_credentials_trims_whitespace_before_calling_bigquery(
"private_key": "private-key",
"private_key_id": "private-key-id",
"client_email": "client-email",
- "token_uri": "token-uri",
+ "token_uri": "https://oauth2.googleapis.com/token",
},
dataset_project_id=None,
location=None,
@@ -1119,7 +1121,7 @@ def _valid_key_file() -> dict[str, str]:
"private_key": "private-key",
"private_key_id": "private-key-id",
"client_email": "client-email",
- "token_uri": "token-uri",
+ "token_uri": "https://oauth2.googleapis.com/token",
}
@@ -1138,6 +1140,65 @@ def test_bigquery_validate_credentials_missing_fields_reports_actionable_message
mock_client.assert_not_called()
+_NON_GOOGLE_TOKEN_URIS = [
+ "https://attacker.example.com/relay",
+ "http://oauth2.googleapis.com/token",
+ "https://oauth2.googleapis.com.example.com/token",
+ "http://169.254.169.254/latest/meta-data/",
+]
+
+
+ "token_uri",
+ ["https://oauth2.googleapis.com/token", "https://accounts.google.com/o/oauth2/token"],
+)
+def test_bigquery_validate_credentials_accepts_both_google_token_endpoints(token_uri):
+ key_file = {**_valid_key_file(), "token_uri": token_uri}
+
+ with mock.patch.object(bq_module, "bigquery_client") as mock_client:
+ ok, message = validate_bigquery_credentials(
+ dataset_id="my_dataset", key_file=key_file, dataset_project_id=None, location=None
+ )
+
+ assert (ok, message) == (True, None)
+ assert mock_client.call_args.args[5] == token_uri
+
+
[email protected]("token_uri", _NON_GOOGLE_TOKEN_URIS)
+def test_bigquery_validate_credentials_rejects_non_google_token_uri_before_any_request(token_uri):
+ key_file = {**_valid_key_file(), "token_uri": token_uri}
+
+ with mock.patch.object(bq_module, "bigquery_client") as mock_client:
+ ok, message = validate_bigquery_credentials(
+ dataset_id="my_dataset", key_file=key_file, dataset_project_id=None, location=None
+ )
+
+ assert ok is False
+ assert message == BIGQUERY_INVALID_TOKEN_URI_ERROR
+ mock_client.assert_not_called()
+
+
[email protected]("token_uri", _NON_GOOGLE_TOKEN_URIS)
[email protected]("client_factory", ["bigquery_client", "bigquery_storage_read_client"])
+def test_bigquery_clients_refuse_non_google_token_uri_before_building_credentials(client_factory, token_uri):
+ kwargs = {"location": None} if client_factory == "bigquery_client" else {}
+
+ with mock.patch.object(bq_module.service_account.Credentials, "from_service_account_info") as mock_creds:
+ with pytest.raises(BigQueryInvalidTokenUriError) as exc_info:
+ with getattr(bq_module, client_factory)(
+ project_id="project-id",
+ private_key="private-key",
+ private_key_id="private-key-id",
+ client_email="client-email",
+ token_uri=token_uri,
+ **kwargs,
+ ):
+ pass
+
+ mock_creds.assert_not_called()
+ assert str(exc_info.value) in BigQuerySource().get_non_retryable_errors()
+
+
@pytest.mark.parametrize(
"exception,expected_message,should_capture",
[
@@ -1211,7 +1272,7 @@ def test_bigquery_source_validate_credentials_wires_config_and_region(use_custom
dataset_id, key_file, dataset_project_id, region = mock_validate.call_args.args
assert dataset_id == "dataset-id"
assert key_file["project_id"] == "project-id"
- assert key_file["token_uri"] == "token-uri"
+ assert key_file["token_uri"] == "https://oauth2.googleapis.com/token"
assert dataset_project_id is None
# A custom region only flows through when the toggle is enabled and non-empty.
assert region == expected_region
@@ -1940,7 +2001,7 @@ def test_bigquery_storage_read_client_disables_grpc_message_size_limit():
private_key="private-key",
private_key_id="private-key-id",
client_email="client-email",
- token_uri="token-uri",
+ token_uri="https://oauth2.googleapis.com/token",
):
pass
@@ -1967,7 +2028,7 @@ def test_bigquery_client_retries_transient_token_refresh_failures():
private_key="private-key",
private_key_id="private-key-id",
client_email="client-email",
- token_uri="token-uri",
+ token_uri="https://oauth2.googleapis.com/token",
) as client:
auth_request_session = client._http._auth_request.session
adapter = cast(HTTPAdapter, auth_request_session.get_adapter("https://oauth2.googleapis.com"))