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.

feat(data-warehouse): support service account integrations for bigquery imports (#102891)

Tom Owers108303a31014
diff --git a/products/warehouse_sources/backend/management/commands/generate_source_configs.py b/products/warehouse_sources/backend/management/commands/generate_source_configs.py
index ce9610eb140c..1a01733e8c04 100644
--- a/products/warehouse_sources/backend/management/commands/generate_source_configs.py
+++ b/products/warehouse_sources/backend/management/commands/generate_source_configs.py
@@ -1,4 +1,5 @@
import os
+import re
import logging
from typing import Any, Optional
@@ -488,6 +489,38 @@ class {class_name}(config.Config):
return line.split("class ")[1].split("(")[0]
return ""
+ def _nested_config_names_in_dependency_order(self) -> list[str]:
+ """Nested config class names, alphabetical except that a class follows the ones it references.
+
+ Python evaluates an annotation when the class body runs, so a nested config that names a
+ sibling declared later raises `NameError` on import. That happens whenever a field which
+ generates its own nested class (a file upload) sits inside another one (a select option).
+ """
+ names = sorted(self.nested_configs)
+ ordered: list[str] = []
+ remaining = list(names)
+
+ while remaining:
+ for name in remaining:
+ if self._referenced_nested_configs(name, names) <= set(ordered):
+ ordered.append(name)
+ remaining.remove(name)
+ break
+ else:
+ # A reference cycle cannot be expressed in Python here either, so leave the
+ # remainder alphabetical and let the import error name the offending class.
+ ordered.extend(remaining)
+ break
+
+ return ordered
+
+ def _referenced_nested_configs(self, name: str, candidates: list[str]) -> set[str]:
+ body = self.nested_configs[name]
+ # Skip the declaration line: a parent's class name is a prefix of its children's, and the
+ # word-boundary match below only separates them once the declaration is out of the way.
+ field_lines = "\n".join(line for line in body.splitlines() if not line.startswith("class "))
+ return {other for other in candidates if other != name and re.search(rf"\b{other}\b", field_lines)}
+
def _build_module(self) -> str:
parts = []
@@ -509,7 +542,7 @@ class {class_name}(config.Config):
parts.append("")
parts.append("")
- for class_name in sorted(self.nested_configs.keys()):
+ for class_name in self._nested_config_names_in_dependency_order():
parts.append(self.nested_configs[class_name])
parts.append("")
parts.append("")
diff --git a/products/warehouse_sources/backend/migrations/0165_migrate_bigquery_job_inputs_to_auth_type.py b/products/warehouse_sources/backend/migrations/0165_migrate_bigquery_job_inputs_to_auth_type.py
new file mode 100644
index 000000000000..09e1666cc5c8
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0165_migrate_bigquery_job_inputs_to_auth_type.py
@@ -0,0 +1,76 @@
+from typing import Any
+
+from django.db import migrations
+
+
+def nest_key_file_under_auth_type(job_inputs: dict[str, Any]) -> dict[str, Any] | None:
+ """Move a BigQuery source's flat `key_file` under the `auth_type` selection, or None if it is
+ already migrated."""
+ if "auth_type" in job_inputs:
+ return None
+
+ migrated = dict(job_inputs)
+ key_file = migrated.pop("key_file", None)
+ migrated["auth_type"] = {
+ "selection": "key_file",
+ "key_file": key_file if isinstance(key_file, dict) else {},
+ }
+ return migrated
+
+
+def flatten_auth_type_to_key_file(job_inputs: dict[str, Any]) -> dict[str, Any] | None:
+ """Undo `nest_key_file_under_auth_type`, or None if there is nothing to undo.
+
+ A source set up on a service account integration has no key file to restore, so it comes back
+ with only the integration id, which the pre-migration code ignores. Reversing is a rollback
+ path: such a source has to be reconnected rather than silently syncing on a stale key.
+ """
+ auth_type = job_inputs.get("auth_type")
+ if not isinstance(auth_type, dict):
+ return None
+
+ flattened = dict(job_inputs)
+ flattened.pop("auth_type")
+
+ key_file = auth_type.get("key_file")
+ if isinstance(key_file, dict):
+ flattened["key_file"] = key_file
+
+ integration_id = auth_type.get("google_cloud_service_account_integration_id")
+ if integration_id not in (None, ""):
+ flattened["google_cloud_service_account_integration_id"] = integration_id
+
+ return flattened
+
+
+def _rewrite_bigquery_job_inputs(apps, rewrite):
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ for source in ExternalDataSource.objects.filter(source_type="BigQuery").iterator():
+ if not isinstance(source.job_inputs, dict):
+ continue
+
+ rewritten = rewrite(source.job_inputs)
+ if rewritten is None:
+ continue
+
+ source.job_inputs = rewritten
+ source.save(update_fields=["job_inputs"])
+
+
+def migrate_bigquery_job_inputs(apps, schema_editor):
+ _rewrite_bigquery_job_inputs(apps, nest_key_file_under_auth_type)
+
+
+def reverse_migrate_bigquery_job_inputs(apps, schema_editor):
+ _rewrite_bigquery_job_inputs(apps, flatten_auth_type_to_key_file)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources", "0164_repin_factorial_api_version"),
+ ]
+
+ operations = [
+ migrations.RunPython(migrate_bigquery_job_inputs, reverse_migrate_bigquery_job_inputs),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index c19bad42fc65..5b98b51424e4 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0164_repin_factorial_api_version
+0165_migrate_bigquery_job_inputs_to_auth_type
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 af9d149be1de..ba594dea3fec 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
@@ -23,8 +23,11 @@ from decimal import Decimal
from typing import Any
from urllib.parse import urlparse
+from django.conf import settings
+
import pyarrow as pa
import structlog
+from asgiref.sync import async_to_sync
from google.api_core.exceptions import (
BadRequest,
DeadlineExceeded,
@@ -34,6 +37,10 @@ from google.api_core.exceptions import (
ServiceUnavailable,
)
from google.api_core.retry import Retry, if_exception_type
+from google.auth import (
+ credentials as google_auth_credentials,
+ impersonated_credentials as google_auth_impersonated_credentials,
+)
from google.auth.exceptions import RefreshError
from google.auth.transport.requests import (
AuthorizedSession,
@@ -47,7 +54,9 @@ from google.cloud.bigquery_storage_v1.services.big_query_read.transports.grpc im
from google.oauth2 import service_account
from structlog.types import FilteringBoundLogger
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
+from posthog.models.integration import GoogleCloudServiceAccountIntegration, Integration
from posthog.models.integration.google_cloud import (
GOOGLE_SERVICE_ACCOUNT_INVALID_TOKEN_URI_ERROR,
InvalidGoogleTokenUriError,
@@ -101,6 +110,7 @@ __all__ = [
"BIGQUERY_DATASET_NOT_FOUND_ERROR",
"BIGQUERY_INVALID_IDENTIFIER_ERROR",
"BIGQUERY_TOKEN_RESPONSE_ERROR",
+ "BigQueryAuthInfo",
"BigQueryCredentialsRejectedError",
"BigQueryDatasetNotFoundError",
"BigQueryImplementation",
@@ -109,9 +119,11 @@ __all__ = [
"bigquery_client",
"bigquery_storage_read_client",
"build_destination_table_prefix",
+ "classify_bigquery_validation_error",
"delete_all_temp_destination_tables",
"delete_table",
"filter_bigquery_incremental_fields",
+ "resolve_bigquery_auth",
"validate_bigquery_credentials",
]
@@ -119,6 +131,13 @@ __all__ = [
# tracked gRPC transport's logs/metrics.
BIGQUERY_STORAGE_HOST = "bigquerystorage.googleapis.com"
+# `drive` is needed alongside `cloud-platform` because BigQuery external tables can be backed by
+# Google Sheets or Drive files, and reading those goes out under the caller's Drive scope.
+BIGQUERY_SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/cloud-platform"]
+
+# Matches what batch exports mint for the same impersonation chain.
+_IMPERSONATION_CREDENTIALS_LIFETIME_SECONDS = 3600
+
# The core BigQuery REST API is stable at v2 — every resource path is served under /bigquery/v2/ —
# so both the legacy unversioned pin and the explicit v2 label resolve to the same REST endpoint.
# `_REST_API_VERSION_BY_LABEL` is the single place to extend should BigQuery ever ship a new REST
@@ -168,7 +187,8 @@ BIGQUERY_INVALID_IDENTIFIER_ERROR = (
# phrasing like "re-enable the sync".
BIGQUERY_CREDENTIALS_REJECTED_ERROR = (
"Your BigQuery service account credentials were rejected by Google. The key may have been "
- "rotated or revoked, or the service account deleted. Please upload a new Google Cloud JSON key file."
+ "rotated or revoked, or the service account deleted. Please reconnect the source with a working "
+ "service account."
)
# The private key in the uploaded JSON key file couldn't be parsed (truncated/corrupted PEM body).
@@ -212,6 +232,41 @@ BIGQUERY_VALIDATION_GENERIC_ERROR = (
"Dataset ID, and dataset region, then try again."
)
+BIGQUERY_NO_CREDENTIALS_ERROR = (
+ "This BigQuery source has no credentials. Pick a Google Cloud service account, or upload a "
+ "service account JSON key file."
+)
+
+BIGQUERY_INTEGRATION_NOT_FOUND_ERROR = (
+ "The Google Cloud service account this source uses is no longer connected. Pick a service "
+ "account again, then reconnect the source."
+)
+
+BIGQUERY_IMPERSONATION_UNAVAILABLE_ERROR = (
+ "This PostHog instance cannot impersonate Google Cloud service accounts. Upload a service "
+ "account JSON key file instead."
+)
+
+BIGQUERY_SERVICE_ACCOUNT_NOT_FOUND_ERROR = (
+ "Google Cloud could not find the service account this source connects with. Check it still "
+ "exists, then reconnect the source."
+)
+
+BIGQUERY_IMPERSONATION_PERMISSION_ERROR = (
+ "PostHog cannot read your Google Cloud service account. Grant the PostHog service account the "
+ "iam.serviceAccounts.get and Service Account Token Creator permissions on it, then reconnect "
+ "the source."
+)
+
+# Stable prefix of the ownership failure raised when the service account description does not name
+# the connecting organization. The rest of the message carries the organization ID the user must add.
+BIGQUERY_OWNERSHIP_UNVERIFIED_ERROR_PREFIX = "Could not verify that service account"
+
+
+class BigQueryAuthResolutionError(Exception):
+ """Carries a user-safe explanation of why a source's credentials could not be resolved."""
+
+
# BigQuery occasionally fails a query job with a transient `jobInternalError`, surfaced from the
# `jobs.getQueryResults` REST call as a 400 BadRequest whose message ends "The job encountered an
# error during execution. Retrying the job may solve the problem.". The client's default job-retry
@@ -394,7 +449,10 @@ def _normalize_identifier(value: str) -> str:
def _resolve_project_id(config: BigQuerySourceConfig) -> str:
- return _normalize_identifier(config.key_file.project_id)
+ key_file = config.auth_type.key_file
+ if key_file is None:
+ raise BigQueryAuthResolutionError(BIGQUERY_NO_CREDENTIALS_ERROR)
+ return _normalize_identifier(key_file.project_id)
def _resolve_dataset_id(config: BigQuerySourceConfig) -> str:
@@ -423,39 +481,162 @@ def _resolve_dataset_project_id(config: BigQuerySourceConfig) -> str | None:
return None
-def _resolve_query_project(config: BigQuerySourceConfig) -> str:
- """Project used to run INFORMATION_SCHEMA discovery queries.
+@frozen
+class BigQueryAuthInfo:
+ """The identity a sync runs as: the project it bills to, and the credentials it signs with.
- Prefers the (optional) dataset project over the service account project,
- mirroring the routing the rest of the source uses.
+ Resolved once per run from whichever authentication the source is configured with, so every
+ client the sync opens shares one credential object (and therefore one refreshed token).
"""
- dataset_project_id = _resolve_dataset_project_id(config)
- return dataset_project_id if dataset_project_id is not None else _resolve_project_id(config)
+ project_id: str
+ credentials: google_auth_credentials.Credentials
-def bigquery_client(
+
+def _service_account_key_credentials(
project_id: str,
- location: str | None,
private_key: str,
private_key_id: str,
client_email: str,
token_uri: str,
- api_version: str = BIGQUERY_API_VERSION_V2,
-) -> 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(
+) -> google_auth_credentials.Credentials:
+ return service_account.Credentials.from_service_account_info(
{
"private_key": private_key,
"private_key_id": private_key_id,
- "token_uri": token_uri,
+ "token_uri": _require_google_token_uri(token_uri),
"client_email": client_email,
- "project_id": project_id,
+ "project_id": _normalize_identifier(project_id),
},
- scopes=["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/cloud-platform"],
+ scopes=BIGQUERY_SCOPES,
+ )
+
+
+def _impersonated_credentials(service_account_email: str, team_id: int) -> google_auth_credentials.Credentials:
+ """Credentials for a service account PostHog impersonates rather than holds a key for.
+
+ Chains off the same PostHog identity BigQuery batch exports impersonate with, so a customer
+ grants one PostHog principal the token-creator role and both imports and exports work.
+ """
+ # Imported here so the source registry — which the API imports on every request path — does not
+ # pull in the batch-export Temporal module.
+ from products.batch_exports.backend.temporal.destinations.bigquery_batch_export import ( # noqa: PLC0415 — keeps the batch-export Temporal module off the source registry's import path
+ MissingRequiredPermissionsError,
+ ServiceAccountNotFoundError,
+ ServiceAccountOwnershipError,
+ get_our_google_cloud_credentials,
+ verify_impersonated_service_account_ownership,
+ )
+
+ if not settings.BATCH_EXPORT_BIGQUERY_STS_AUDIENCE_FIELD or not settings.BATCH_EXPORT_BIGQUERY_SERVICE_ACCOUNT:
+ raise BigQueryAuthResolutionError(BIGQUERY_IMPERSONATION_UNAVAILABLE_ERROR)
+
+ # Confirm the team owns the account before impersonating it, or a team that merely knows another
+ # org's service account email could have PostHog read that org's data on its behalf. Batch
+ # exports and the BigQuery destination writer guard the same way at the same point.
+ try:
+ async_to_sync(verify_impersonated_service_account_ownership)(service_account_email, team_id)
+ except ServiceAccountNotFoundError as e:
+ raise BigQueryAuthResolutionError(BIGQUERY_SERVICE_ACCOUNT_NOT_FOUND_ERROR) from e
+ except MissingRequiredPermissionsError as e:
+ raise BigQueryAuthResolutionError(BIGQUERY_IMPERSONATION_PERMISSION_ERROR) from e
+ except ServiceAccountOwnershipError as e:
+ # Already phrased for the customer, and it names the organization ID they must add.
+ raise BigQueryAuthResolutionError(str(e)) from e
+
+ return google_auth_impersonated_credentials.Credentials(
+ source_credentials=get_our_google_cloud_credentials(),
+ target_principal=service_account_email,
+ target_scopes=BIGQUERY_SCOPES,
+ lifetime=_IMPERSONATION_CREDENTIALS_LIFETIME_SECONDS,
+ )
+
+
+def _resolve_auth_from_integration(integration_id: int, team_id: int) -> BigQueryAuthInfo:
+ integration = Integration.objects.filter(
+ id=integration_id,
+ team_id=team_id,
+ kind=Integration.IntegrationKind.GOOGLE_CLOUD_SERVICE_ACCOUNT,
+ ).first()
+ if integration is None:
+ raise BigQueryAuthResolutionError(BIGQUERY_INTEGRATION_NOT_FOUND_ERROR)
+
+ google_cloud_integration = GoogleCloudServiceAccountIntegration(integration)
+ if google_cloud_integration.has_key():
+ info = google_cloud_integration.service_account_info
+ credentials = _service_account_key_credentials(
+ project_id=info["project_id"],
+ private_key=info["private_key"],
+ private_key_id=info["private_key_id"],
+ client_email=info["client_email"],
+ token_uri=info["token_uri"],
+ )
+ else:
+ credentials = _impersonated_credentials(google_cloud_integration.service_account_email, team_id)
+
+ return BigQueryAuthInfo(
+ project_id=_normalize_identifier(google_cloud_integration.project_id), credentials=credentials
)
+
+
+def _resolve_auth_from_key_file(config: BigQuerySourceConfig) -> BigQueryAuthInfo:
+ key_file = config.auth_type.key_file
+ if key_file is None:
+ raise BigQueryAuthResolutionError(BIGQUERY_NO_CREDENTIALS_ERROR)
+ if not all(
+ (key_file.project_id, key_file.private_key, key_file.private_key_id, key_file.client_email, key_file.token_uri)
+ ):
+ raise BigQueryAuthResolutionError(BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR)
+
+ return BigQueryAuthInfo(
+ project_id=_resolve_project_id(config),
+ credentials=_service_account_key_credentials(
+ project_id=key_file.project_id,
+ private_key=key_file.private_key,
+ private_key_id=key_file.private_key_id,
+ client_email=key_file.client_email,
+ token_uri=key_file.token_uri,
+ ),
+ )
+
+
+def resolve_bigquery_auth(config: BigQuerySourceConfig, team_id: int | None) -> BigQueryAuthInfo:
+ """Resolve the credentials a source runs with, from the authentication type it was set up with.
+
+ The selection decides the credential on its own: a source that carries both a stored key file
+ and an integration id (one edited from one type to the other) runs on the selected one, so the
+ other stops being an active credential the moment the user switches away from it.
+ """
+ if config.auth_type.selection != "service_account":
+ return _resolve_auth_from_key_file(config)
+
+ integration_id = config.auth_type.google_cloud_service_account_integration_id
+ if integration_id is None:
+ raise BigQueryAuthResolutionError(BIGQUERY_NO_CREDENTIALS_ERROR)
+ if team_id is None:
+ raise BigQueryAuthResolutionError(BIGQUERY_NO_CREDENTIALS_ERROR)
+ return _resolve_auth_from_integration(int(integration_id), team_id)
+
+
+def _resolve_query_project(config: BigQuerySourceConfig, fallback_project_id: str) -> str:
+ """Project used to run INFORMATION_SCHEMA discovery queries.
+
+ Prefers the (optional) dataset project over the project the credentials authenticate as,
+ mirroring the routing the rest of the source uses.
+ """
+ dataset_project_id = _resolve_dataset_project_id(config)
+ return dataset_project_id if dataset_project_id is not None else fallback_project_id
+
+
+def bigquery_client(
+ project_id: str,
+ location: str | None,
+ credentials: google_auth_credentials.Credentials,
+ api_version: str = BIGQUERY_API_VERSION_V2,
+) -> typing.Iterator[bigquery.Client]:
+ """Manage a BigQuery client."""
+ project_id = _normalize_identifier(project_id)
# See `BIGQUERY_TOKEN_REFRESH_RETRY`: hand `AuthorizedSession` our own retrying session for
# credential refresh, instead of the default one whose adapter never retries a 502/503/504.
# `capture=False` keeps the OAuth response (it carries the minted bearer token) out of HTTP
@@ -499,23 +680,8 @@ def bigquery_client(
@contextlib.contextmanager
-def bigquery_storage_read_client(
- project_id: str, private_key: str, private_key_id: str, client_email: str, token_uri: str
-):
+def bigquery_storage_read_client(credentials: google_auth_credentials.Credentials):
"""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,
- "private_key_id": private_key_id,
- "token_uri": token_uri,
- "client_email": client_email,
- "project_id": project_id,
- },
- scopes=["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/cloud-platform"],
- )
-
# Build the credential-bearing gRPC channel ourselves, wrap it in the tracked
# interceptors, then hand it to the transport. Passing a `channel` makes the
# transport ignore credentials, so they must already be baked into the channel
@@ -551,7 +717,7 @@ def bigquery_storage_read_client(
transport.close()
-def _detect_dataset_region(config: BigQuerySourceConfig) -> str | None:
+def _detect_dataset_region(config: BigQuerySourceConfig, auth: BigQueryAuthInfo) -> str | None:
"""Resolve the dataset's BigQuery location for schema-discovery queries.
Credentials validate with a region-agnostic table listing, but a query job created
@@ -560,16 +726,11 @@ def _detect_dataset_region(config: BigQuerySourceConfig) -> str | None:
location US". `get_dataset` is region-agnostic, so read the dataset's real location and
pin discovery to it. Returns None on any failure, leaving the original behaviour intact.
"""
- with bigquery_client(
- _resolve_project_id(config),
- None,
- config.key_file.private_key,
- config.key_file.private_key_id,
- config.key_file.client_email,
- config.key_file.token_uri,
- ) as bq:
+ with bigquery_client(auth.project_id, None, auth.credentials) as bq:
try:
- dataset_ref = bq.dataset(_resolve_dataset_id(config), project=_resolve_query_project(config))
+ dataset_ref = bq.dataset(
+ _resolve_dataset_id(config), project=_resolve_query_project(config, auth.project_id)
+ )
return bq.get_dataset(dataset_ref).location
except Exception as e:
# Best-effort: fall back to the default location so `get_columns` still surfaces the
@@ -583,12 +744,9 @@ def delete_table(
table_id: str,
project_id: str,
location: str | None,
- private_key: str,
- private_key_id: str,
- client_email: str,
- token_uri: str,
+ credentials: google_auth_credentials.Credentials,
) -> None:
- with bigquery_client(project_id, location, private_key, private_key_id, client_email, token_uri) as bq:
+ with bigquery_client(project_id, location, credentials) as bq:
bq.delete_table(table_id, not_found_ok=True)
@@ -598,13 +756,10 @@ def delete_all_temp_destination_tables(
project_id: str,
location: str | None,
dataset_project_id: str | None,
- private_key: str,
- private_key_id: str,
- client_email: str,
- token_uri: str,
+ credentials: google_auth_credentials.Credentials,
logger: None | FilteringBoundLogger,
) -> None:
- with bigquery_client(project_id, location, private_key, private_key_id, client_email, token_uri) as bq:
+ with bigquery_client(project_id, location, credentials) as bq:
try:
tables = bq.list_tables(bq.dataset(dataset_id, project=dataset_project_id or project_id))
for table in tables:
@@ -668,8 +823,45 @@ def filter_bigquery_incremental_fields(
return results
+def classify_bigquery_validation_error(e: Exception) -> str:
+ """Map a failure raised while validating a source to the message the wizard shows.
+
+ Mirrors the stable substrings the sync-path classifier keys off, so the wizard names the same
+ root causes. Ordering matches `get_non_retryable_errors`: identifier/dataset before the generic
+ access-denied so the more specific message wins.
+ """
+ if isinstance(e, BigQueryAuthResolutionError | BigQueryInvalidTokenUriError):
+ # Raised by us, already phrased for the customer.
+ return str(e)
+
+ message = str(e)
+ if "Unable to load PEM file" in message:
+ return BIGQUERY_INVALID_KEY_FILE_ERROR
+ if "invalid_grant" in message:
+ return BIGQUERY_CREDENTIALS_REJECTED_ERROR
+ if (
+ "Invalid project ID" in message
+ or "Invalid dataset ID" in message
+ or "ProjectId must be non-empty" in message
+ or "Invalid resource name" in message
+ ):
+ return BIGQUERY_INVALID_IDENTIFIER_ERROR
+ if "was not found in location" in message or "Not found: Dataset" in message:
+ return BIGQUERY_DATASET_NOT_FOUND_ERROR
+ if "Access Denied" in message or "PermissionDenied" in message or "permission denied" in message:
+ return BIGQUERY_VALIDATION_PERMISSION_DENIED_ERROR
+ # Genuinely unexpected — keep the signal, and fall back to a generic message so no raw
+ # exception text (which can embed ids or tokens) reaches the user.
+ capture_exception(e)
+ return BIGQUERY_VALIDATION_GENERIC_ERROR
+
+
def validate_bigquery_credentials(
- dataset_id: str, key_file: dict[str, str], dataset_project_id: str | None, location: str | None
+ dataset_id: str,
+ project_id: str,
+ credentials: google_auth_credentials.Credentials,
+ dataset_project_id: str | None,
+ location: str | None,
) -> tuple[bool, str | None]:
"""Validate BigQuery credentials at onboarding time.
@@ -679,19 +871,6 @@ def validate_bigquery_credentials(
so they're mapped to a clear message instead of surfacing a bare "invalid credentials" and are
not reported to error tracking — only genuinely unexpected failures are captured.
"""
- project_id = key_file.get("project_id")
- private_key = key_file.get("private_key")
- private_key_id = key_file.get("private_key_id")
- client_email = key_file.get("client_email")
- token_uri = key_file.get("token_uri")
-
- 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`.
project_id = _normalize_identifier(project_id)
@@ -700,7 +879,7 @@ def validate_bigquery_credentials(
location = _normalize_identifier(location) if location else location
try:
- with bigquery_client(project_id, location, private_key, private_key_id, client_email, token_uri) as bq:
+ with bigquery_client(project_id, location, credentials) as bq:
tables = bq.list_tables(
bq.dataset(dataset_id, project=dataset_project_id or project_id),
retry=bigquery.DEFAULT_RETRY.with_timeout(5),
@@ -711,29 +890,7 @@ def validate_bigquery_credentials(
next(tables.pages, None)
return True, None
except Exception as e:
- # Mirror the stable substrings the sync-path classifier keys off, so the wizard names the
- # same root causes. Ordering matches `get_non_retryable_errors`: identifier/dataset before
- # the generic access-denied so the more specific message wins.
- message = str(e)
- if "Unable to load PEM file" in message:
- return False, BIGQUERY_INVALID_KEY_FILE_ERROR
- if "invalid_grant" in message:
- return False, BIGQUERY_CREDENTIALS_REJECTED_ERROR
- if (
- "Invalid project ID" in message
- or "Invalid dataset ID" in message
- or "ProjectId must be non-empty" in message
- or "Invalid resource name" in message
- ):
- return False, BIGQUERY_INVALID_IDENTIFIER_ERROR
- if "was not found in location" in message or "Not found: Dataset" in message:
- return False, BIGQUERY_DATASET_NOT_FOUND_ERROR
- if "Access Denied" in message or "PermissionDenied" in message or "permission denied" in message:
- return False, BIGQUERY_VALIDATION_PERMISSION_DENIED_ERROR
- # Genuinely unexpected — keep the signal, and fall back to a generic message so no raw
- # exception text (which can embed ids or tokens) reaches the user.
- capture_exception(e)
- return False, BIGQUERY_VALIDATION_GENERIC_ERROR
+ return False, classify_bigquery_validation_error(e)
def _get_partition_settings(
@@ -1228,18 +1385,12 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
@contextmanager
def connect(self, config: BigQuerySourceConfig, *, team_id: int | None = None) -> Iterator[bigquery.Client]:
+ auth = resolve_bigquery_auth(config, team_id)
# Without a custom region the client is built with `location=None`, so discovery
# query jobs default to the US multi-region and miss datasets in other regions.
# Auto-detect the dataset's location so discovery runs where the data lives.
- region = _resolve_region(config) or _detect_dataset_region(config)
- with bigquery_client(
- _resolve_project_id(config),
- region,
- config.key_file.private_key,
- config.key_file.private_key_id,
- config.key_file.client_email,
- config.key_file.token_uri,
- ) as bq:
+ region = _resolve_region(config) or _detect_dataset_region(config, auth)
+ with bigquery_client(auth.project_id, region, auth.credentials) as bq:
yield bq
# ------------------------------------------------------------------
@@ -1268,7 +1419,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
# — quoting the whole path as one identifier (like a regular `project.dataset.table` reference)
# stops BigQuery from resolving the trailing segments as the INFORMATION_SCHEMA view, which
# raises the same "ProjectId must be non-empty" error this qualification was meant to fix.
- project = _resolve_query_project(config)
+ project = _resolve_query_project(config, conn.project)
qualified_dataset = f"{project}.{_resolve_dataset_id(config)}"
query = conn.query(
f"SELECT table_name, column_name, data_type, is_nullable FROM `{qualified_dataset}`.INFORMATION_SCHEMA.COLUMNS ORDER BY table_name ASC",
@@ -1350,7 +1501,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
if not tables:
return {}
- project = _resolve_query_project(config)
+ project = _resolve_query_project(config, conn.project)
dataset_id = _resolve_dataset_id(config)
# Join against INFORMATION_SCHEMA.COLUMNS so a PK constraint that
@@ -1418,7 +1569,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
try:
result: dict[str, set[str]] = {table: set() for table in tables}
- project = _resolve_query_project(config)
+ project = _resolve_query_project(config, conn.project)
# Project-qualify the dataset (see `get_columns`): an unqualified `dataset.INFORMATION_SCHEMA.*`
# fails with "ProjectId must be non-empty" when the dataset lives in a different project.
@@ -1448,12 +1599,11 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
# ------------------------------------------------------------------
def build_pipeline(self, config: BigQuerySourceConfig, inputs: SourceInputs) -> SourceResponse:
- if not config.key_file.private_key:
- raise ValueError(f"Missing private key for BigQuery: '{inputs.job_id}'")
+ auth = resolve_bigquery_auth(config, inputs.team_id)
region = _resolve_region(config)
dataset_project_id = _resolve_dataset_project_id(config)
- project_id = _resolve_project_id(config)
+ project_id = auth.project_id
destination_table_dataset_id = _resolve_dataset_id(config)
if (
@@ -1479,10 +1629,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
project_id=project_id,
location=region,
dataset_project_id=dataset_project_id,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
+ credentials=auth.credentials,
logger=inputs.logger,
)
@@ -1493,6 +1640,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
region=region,
dataset_project_id=dataset_project_id,
bq_destination_table_id=destination_table,
+ auth=auth,
rest_api_version=_bigquery_rest_api_version(inputs.api_version),
)
finally:
@@ -1509,10 +1657,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
table_id=destination_table,
project_id=project_id,
location=region,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
+ credentials=auth.credentials,
)
inputs.logger.info(f"Deleting bigquery temp destination table: {destination_table}")
except RefreshError as e:
@@ -1530,6 +1675,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
region: str | None,
dataset_project_id: str | None,
bq_destination_table_id: str,
+ auth: BigQueryAuthInfo,
rest_api_version: str = BIGQUERY_API_VERSION_V2,
partition_size_bytes: int = DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,
) -> SourceResponse:
@@ -1552,12 +1698,9 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
row_filters = inputs.row_filters
logger = inputs.logger
- project_id = _resolve_project_id(config)
+ project_id = auth.project_id
location = region
- private_key = config.key_file.private_key
- private_key_id = config.key_file.private_key_id
- client_email = config.key_file.client_email
- token_uri = config.key_file.token_uri
+ credentials = auth.credentials
project_id_for_dataset = dataset_project_id or project_id
name = NamingConvention.normalize_identifier(table_name)
@@ -1566,10 +1709,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
with bigquery_client(
project_id=project_id,
location=location,
- private_key=private_key,
- private_key_id=private_key_id,
- client_email=client_email,
- token_uri=token_uri,
+ credentials=credentials,
api_version=rest_api_version,
) as bq_client:
bq_table = bq_client.get_table(fully_qualified_table_name)
@@ -1591,10 +1731,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
with bigquery_client(
project_id=project_id,
location=location,
- private_key=private_key,
- private_key_id=private_key_id,
- client_email=client_email,
- token_uri=token_uri,
+ credentials=credentials,
api_version=rest_api_version,
) as bq_client:
bq_table = bq_client.get_table(fully_qualified_table_name)
@@ -1679,13 +1816,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
),
),
)
- with bigquery_storage_read_client(
- project_id=project_id,
- private_key=private_key,
- private_key_id=private_key_id,
- client_email=client_email,
- token_uri=token_uri,
- ) as bq_storage:
+ with bigquery_storage_read_client(credentials=credentials) as bq_storage:
read_session = bq_storage.create_read_session(
parent="projects/{}".format(bq_table.project),
read_session=requested_session,
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 ed38e791859c..5df0c84878d1 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
@@ -7,20 +7,32 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldFileUploadJsonFormatConfig,
SourceFieldInputConfig,
SourceFieldInputConfigType,
+ SourceFieldOauthConfig,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
SourceFieldSwitchGroupConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery import (
BIGQUERY_API_VERSION_V2,
BIGQUERY_CREDENTIALS_REJECTED_ERROR,
BIGQUERY_DATASET_NOT_FOUND_ERROR,
+ BIGQUERY_IMPERSONATION_PERMISSION_ERROR,
+ BIGQUERY_IMPERSONATION_UNAVAILABLE_ERROR,
+ BIGQUERY_INTEGRATION_NOT_FOUND_ERROR,
BIGQUERY_INVALID_IDENTIFIER_ERROR,
BIGQUERY_INVALID_KEY_FILE_ERROR,
BIGQUERY_INVALID_TOKEN_URI_ERROR,
+ BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR,
+ BIGQUERY_NO_CREDENTIALS_ERROR,
BIGQUERY_ON_DEMAND_RATIO_EXCEEDED_ERROR,
+ BIGQUERY_OWNERSHIP_UNVERIFIED_ERROR_PREFIX,
BIGQUERY_RESOURCES_EXCEEDED_ERROR,
+ BIGQUERY_SERVICE_ACCOUNT_NOT_FOUND_ERROR,
BIGQUERY_TOKEN_RESPONSE_ERROR,
BigQueryImplementation,
build_destination_table_prefix,
+ classify_bigquery_validation_error,
+ resolve_bigquery_auth,
validate_bigquery_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
@@ -84,6 +96,22 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
# 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,
+ # Raised by `resolve_bigquery_auth` before any request, when the source's stored
+ # credentials cannot produce an identity to sync as: the service account integration was
+ # disconnected, the uploaded key file lost fields, the instance can't impersonate, or the
+ # source has no credentials at all. Each is a config problem the user has to fix in the
+ # source, so retrying only repeats the same failure every run.
+ BIGQUERY_INTEGRATION_NOT_FOUND_ERROR: BIGQUERY_INTEGRATION_NOT_FOUND_ERROR,
+ BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR: BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR,
+ BIGQUERY_IMPERSONATION_UNAVAILABLE_ERROR: BIGQUERY_IMPERSONATION_UNAVAILABLE_ERROR,
+ BIGQUERY_NO_CREDENTIALS_ERROR: BIGQUERY_NO_CREDENTIALS_ERROR,
+ # Raised when PostHog impersonates the customer's service account but Google Cloud
+ # rejects the ownership check that guards impersonation — the account is gone, PostHog
+ # can't read it, or its description doesn't name the connecting organization. All three
+ # need a change in the customer's Google Cloud project, so retrying can't recover them.
+ BIGQUERY_SERVICE_ACCOUNT_NOT_FOUND_ERROR: BIGQUERY_SERVICE_ACCOUNT_NOT_FOUND_ERROR,
+ BIGQUERY_IMPERSONATION_PERMISSION_ERROR: BIGQUERY_IMPERSONATION_PERMISSION_ERROR,
+ BIGQUERY_OWNERSHIP_UNVERIFIED_ERROR_PREFIX: None,
# 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
@@ -361,6 +389,27 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
"do not exist in the table schema": "BigQuery couldn't read this table because it referenced columns that no longer exist on it — usually columns selected for syncing were renamed or removed. Retrying won't help — please update the source's column selection to match the table's current schema, then reconnect the source.",
}
+ def validate_config(self, job_inputs: dict) -> tuple[bool, list[str]]:
+ is_valid, errors = super().validate_config(job_inputs)
+
+ # The credential fields under each option are optional on the form, because the option the
+ # user did not pick must not block the save. That makes this the only check that stops a
+ # source being created with no credentials at all.
+ auth_type = job_inputs.get("auth_type")
+ if not isinstance(auth_type, dict):
+ return is_valid, errors
+
+ if auth_type.get("selection") == "key_file":
+ key_file = auth_type.get("key_file")
+ if not isinstance(key_file, dict) or not any(key_file.values()):
+ errors.append("Upload a Google Cloud service account JSON key file.")
+ is_valid = False
+ elif auth_type.get("google_cloud_service_account_integration_id") in (None, ""):
+ errors.append("Pick a Google Cloud service account.")
+ is_valid = False
+
+ return is_valid, errors
+
def validate_credentials(
self,
config: BigQuerySourceConfig,
@@ -368,6 +417,11 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
+ try:
+ auth = resolve_bigquery_auth(config, team_id)
+ except Exception as e:
+ return False, classify_bigquery_validation_error(e)
+
region: str | None = None
if (
config.use_custom_region
@@ -378,13 +432,8 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
region = config.use_custom_region.region
return validate_bigquery_credentials(
config.dataset_id,
- {
- "project_id": config.key_file.project_id,
- "private_key": config.key_file.private_key,
- "private_key_id": config.key_file.private_key_id,
- "client_email": config.key_file.client_email,
- "token_uri": config.key_file.token_uri,
- },
+ auth.project_id,
+ auth.credentials,
config.dataset_project.dataset_project_id if config.dataset_project else None,
region,
)
@@ -405,14 +454,52 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
fields=cast(
list[FieldType],
[
- SourceFieldFileUploadConfig(
- name="key_file",
- label="Google Cloud JSON key file",
- fileFormat=SourceFieldFileUploadJsonFormatConfig(
- format=".json",
- keys=["project_id", "private_key", "private_key_id", "client_email", "token_uri"],
- ),
+ SourceFieldSelectConfig(
+ name="auth_type",
+ label="Authentication type",
required=True,
+ defaultValue="service_account",
+ options=[
+ SourceFieldSelectConfigOption(
+ label="Google Cloud service account",
+ value="service_account",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldOauthConfig(
+ name="google_cloud_service_account_integration_id",
+ label="Google Cloud service account",
+ required=False,
+ kind="google-cloud-service-account",
+ ),
+ ],
+ ),
+ ),
+ SourceFieldSelectConfigOption(
+ label="JSON key file",
+ value="key_file",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldFileUploadConfig(
+ name="key_file",
+ label="Google Cloud JSON key file",
+ fileFormat=SourceFieldFileUploadJsonFormatConfig(
+ format=".json",
+ keys=[
+ "project_id",
+ "private_key",
+ "private_key_id",
+ "client_email",
+ "token_uri",
+ ],
+ ),
+ required=False,
+ ),
+ ],
+ ),
+ ),
+ ],
),
SourceFieldSwitchGroupConfig(
name="use_custom_region",
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 742b3297dd8c..c6696245bdd4 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
@@ -20,15 +20,21 @@ from google.auth.credentials import Credentials as GoogleAuthCredentials
from google.auth.exceptions import RefreshError
from requests.adapters import HTTPAdapter
+from posthog.models.integration import Integration
+from posthog.models.team.team import Team
+
+from products.batch_exports.backend.temporal.destinations.bigquery_batch_export import ServiceAccountOwnershipError
from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery import bigquery as bq_module
from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery import (
BIGQUERY_CREATE_READ_SESSION_RETRY,
BIGQUERY_CREDENTIALS_REJECTED_ERROR,
BIGQUERY_DATASET_NOT_FOUND_ERROR,
+ BIGQUERY_INTEGRATION_NOT_FOUND_ERROR,
BIGQUERY_INVALID_IDENTIFIER_ERROR,
BIGQUERY_INVALID_KEY_FILE_ERROR,
BIGQUERY_INVALID_TOKEN_URI_ERROR,
BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR,
+ BIGQUERY_NO_CREDENTIALS_ERROR,
BIGQUERY_QUERY_CREATE_RETRY,
BIGQUERY_QUERY_JOB_RETRY,
BIGQUERY_READ_ROWS_RETRY,
@@ -36,6 +42,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b
BIGQUERY_TOKEN_RESPONSE_ERROR,
BIGQUERY_VALIDATION_GENERIC_ERROR,
BIGQUERY_VALIDATION_PERMISSION_DENIED_ERROR,
+ BigQueryAuthResolutionError,
BigQueryCredentialsRejectedError,
BigQueryDatasetNotFoundError,
BigQueryImplementation,
@@ -56,6 +63,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b
_resolve_region,
_run_destination_query_with_job_retry,
delete_all_temp_destination_tables,
+ resolve_bigquery_auth,
validate_bigquery_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.source import BigQuerySource
@@ -68,8 +76,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bigquery import (
+ BigQueryAuthTypeConfig,
+ BigQueryAuthTypeConfigKeyFileConfig,
BigQueryDatasetProjectConfig,
- BigQueryKeyFileConfig,
BigQuerySourceConfig,
BigQueryTemporaryDatasetConfig,
BigQueryUseCustomRegionConfig,
@@ -77,6 +86,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.types import IncrementalFieldType
[email protected](autouse=True)
+def _stub_google_credential_construction():
+ """The test key files carry placeholder private keys, which google-auth rejects as malformed PEM.
+
+ Turning a key file into credentials is google-auth's job, not the source's, so stub it and let
+ each test exercise the source's own wiring. Tests that assert on credential construction patch
+ over this themselves.
+ """
+ with mock.patch.object(
+ bq_module.service_account.Credentials,
+ "from_service_account_info",
+ side_effect=lambda info, scopes=None: mock.MagicMock(spec=GoogleAuthCredentials),
+ ):
+ yield
+
+
def _make_inputs(**overrides) -> SourceInputs:
defaults: dict = {
"schema_name": "schema",
@@ -96,6 +121,28 @@ def _make_inputs(**overrides) -> SourceInputs:
return SourceInputs(**defaults)
+def _key_file(**overrides) -> BigQueryAuthTypeConfigKeyFileConfig:
+ fields: dict[str, str] = {
+ "project_id": "project-id",
+ "private_key": "private-key",
+ "private_key_id": "private-key-id",
+ "client_email": "client-email",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ }
+ fields.update(overrides)
+ return BigQueryAuthTypeConfigKeyFileConfig(**fields)
+
+
+def _key_file_auth(**overrides) -> BigQueryAuthTypeConfig:
+ return BigQueryAuthTypeConfig(selection="key_file", key_file=_key_file(**overrides))
+
+
+def _integration_auth(integration_id: int) -> BigQueryAuthTypeConfig:
+ return BigQueryAuthTypeConfig(
+ selection="service_account", google_cloud_service_account_integration_id=integration_id
+ )
+
+
def _make_config(
*,
project_id: str = "project-id",
@@ -105,13 +152,7 @@ def _make_config(
use_custom_region: BigQueryUseCustomRegionConfig | None = None,
) -> BigQuerySourceConfig:
return BigQuerySourceConfig(
- key_file=BigQueryKeyFileConfig(
- project_id=project_id,
- private_key="private-key",
- private_key_id="private-key-id",
- client_email="client-email",
- token_uri="https://oauth2.googleapis.com/token",
- ),
+ auth_type=_key_file_auth(project_id=project_id),
dataset_id=dataset_id,
dataset_project=dataset_project,
temporary_dataset=temporary_dataset,
@@ -906,10 +947,7 @@ def _run_delete_all_temp_destination_tables(side_effect, logger):
project_id="project-id",
location=None,
dataset_project_id=None,
- private_key="private-key",
- private_key_id="private-key-id",
- client_email="client-email",
- token_uri="https://oauth2.googleapis.com/token",
+ credentials=mock.MagicMock(spec=GoogleAuthCredentials),
logger=logger,
)
return mock_capture
@@ -1051,14 +1089,16 @@ def test_bigquery_resolve_dataset_project_id_trims_and_treats_whitespace_as_unse
def test_bigquery_resolve_query_project_prefers_dataset_project():
+ """The dataset project wins over the project the open connection authenticated as, which is the
+ only project available when the source authenticates through a service account integration."""
config = _make_config(
project_id=" service-account-project ",
dataset_project=BigQueryDatasetProjectConfig(dataset_project_id=" dataset-project ", enabled=True),
)
- assert _resolve_query_project(config) == "dataset-project"
+ assert _resolve_query_project(config, "connection-project") == "dataset-project"
config = _make_config(project_id=" service-account-project ")
- assert _resolve_query_project(config) == "service-account-project"
+ assert _resolve_query_project(config, "connection-project") == "connection-project"
def test_bigquery_get_columns_trims_whitespace_in_identifiers():
@@ -1067,6 +1107,8 @@ def test_bigquery_get_columns_trims_whitespace_in_identifiers():
fake_client = mock.MagicMock()
fake_client.query.return_value.result.return_value = []
+ fake_client.project = "524098457564"
+
config = _make_config(project_id=" 524098457564", dataset_id=" bigquery_aloalo ")
BigQueryImplementation().get_columns(fake_client, config, names=None)
@@ -1125,6 +1167,8 @@ def test_bigquery_get_primary_keys_trims_whitespace_in_identifiers():
fake_client = mock.MagicMock()
fake_client.query.return_value.result.return_value = []
+ fake_client.project = "my-project"
+
config = _make_config(project_id=" my-project ", dataset_id=" my_dataset ")
BigQueryImplementation().get_primary_keys(fake_client, config, tables=["t"])
@@ -1146,13 +1190,8 @@ def test_bigquery_validate_credentials_trims_whitespace_before_calling_bigquery(
) as mock_client:
validate_bigquery_credentials(
dataset_id=" my_dataset ",
- key_file={
- "project_id": " 524098457564",
- "private_key": "private-key",
- "private_key_id": "private-key-id",
- "client_email": "client-email",
- "token_uri": "https://oauth2.googleapis.com/token",
- },
+ project_id=" 524098457564",
+ credentials=mock.MagicMock(spec=GoogleAuthCredentials),
dataset_project_id=None,
location=None,
)
@@ -1161,24 +1200,15 @@ def test_bigquery_validate_credentials_trims_whitespace_before_calling_bigquery(
bq.dataset.assert_called_once_with("my_dataset", project="524098457564")
-def _valid_key_file() -> dict[str, str]:
- return {
- "project_id": "my-project",
- "private_key": "private-key",
- "private_key_id": "private-key-id",
- "client_email": "client-email",
- "token_uri": "https://oauth2.googleapis.com/token",
- }
+def _config_with_key_file(**overrides) -> BigQuerySourceConfig:
+ return BigQuerySourceConfig(auth_type=_key_file_auth(**overrides), dataset_id="my_dataset")
-def test_bigquery_validate_credentials_missing_fields_reports_actionable_message():
- key_file = _valid_key_file()
- del key_file["private_key"]
+def test_bigquery_validate_credentials_missing_key_file_fields_reports_actionable_message():
+ config = _config_with_key_file(private_key="")
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
- )
+ ok, message = BigQuerySource().validate_credentials(config, team_id=1)
assert ok is False
assert message == BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR
@@ -1186,6 +1216,25 @@ def test_bigquery_validate_credentials_missing_fields_reports_actionable_message
mock_client.assert_not_called()
+ "auth_type",
+ [
+ BigQueryAuthTypeConfig(selection="service_account"),
+ BigQueryAuthTypeConfig(selection="key_file"),
+ ],
+)
+def test_bigquery_validate_credentials_without_the_selected_credential_reports_actionable_message(auth_type):
+ """The credential under each option is optional on the form, so a source can reach validation
+ having picked an authentication type without supplying its credential."""
+ config = BigQuerySourceConfig(dataset_id="my_dataset", auth_type=auth_type)
+
+ with mock.patch.object(bq_module, "bigquery_client") as mock_client:
+ ok, message = BigQuerySource().validate_credentials(config, team_id=1)
+
+ assert (ok, message) == (False, BIGQUERY_NO_CREDENTIALS_ERROR)
+ mock_client.assert_not_called()
+
+
_NON_GOOGLE_TOKEN_URIS = [
"https://attacker.example.com/relay",
"http://oauth2.googleapis.com/token",
@@ -1199,49 +1248,32 @@ _NON_GOOGLE_TOKEN_URIS = [
["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}
+ config = _config_with_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
- )
+ with (
+ mock.patch.object(bq_module, "bigquery_client"),
+ mock.patch.object(bq_module.service_account.Credentials, "from_service_account_info") as mock_creds,
+ ):
+ ok, message = BigQuerySource().validate_credentials(config, team_id=1)
assert (ok, message) == (True, None)
- assert mock_client.call_args.args[5] == token_uri
+ assert mock_creds.call_args.args[0]["token_uri"] == token_uri
@pytest.mark.parametrize("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 {}
+def test_bigquery_rejects_non_google_token_uri_before_building_credentials(token_uri):
+ """`token_uri` decides where a worker posts the service-account grant, so a hand-edited one must
+ be refused before google-auth is handed the key at all."""
+ config = _config_with_key_file(token_uri=token_uri)
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()
+ resolve_bigquery_auth(config, team_id=1)
+
+ mock_creds.assert_not_called()
+ ok, message = BigQuerySource().validate_credentials(config, team_id=1)
+
+ assert (ok, message) == (False, BIGQUERY_INVALID_TOKEN_URI_ERROR)
assert str(exc_info.value) in BigQuerySource().get_non_retryable_errors()
@@ -1295,7 +1327,11 @@ def test_bigquery_validate_credentials_maps_failures_to_actionable_messages(
mock.patch.object(bq_module, "capture_exception") as mock_capture,
):
ok, message = validate_bigquery_credentials(
- dataset_id="my_dataset", key_file=_valid_key_file(), dataset_project_id=None, location=None
+ dataset_id="my_dataset",
+ project_id="my-project",
+ credentials=mock.MagicMock(spec=GoogleAuthCredentials),
+ dataset_project_id=None,
+ location=None,
)
assert ok is False
@@ -1324,10 +1360,9 @@ def test_bigquery_source_validate_credentials_wires_config_and_region(use_custom
result = BigQuerySource().validate_credentials(config, team_id=1)
assert result == (True, None)
- dataset_id, key_file, dataset_project_id, region = mock_validate.call_args.args
+ dataset_id, project_id, _credentials, 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"] == "https://oauth2.googleapis.com/token"
+ assert project_id == "project-id"
assert dataset_project_id is None
# A custom region only flows through when the toggle is enabled and non-empty.
assert region == expected_region
@@ -2051,13 +2086,7 @@ def test_bigquery_storage_read_client_disables_grpc_message_size_limit():
mock.patch.object(bq_module, "BigQueryReadGrpcTransport") as mock_transport_cls,
mock.patch.object(bq_module.bigquery_storage, "BigQueryReadClient"),
):
- with bq_module.bigquery_storage_read_client(
- project_id="project-id",
- private_key="private-key",
- private_key_id="private-key-id",
- client_email="client-email",
- token_uri="https://oauth2.googleapis.com/token",
- ):
+ with bq_module.bigquery_storage_read_client(credentials=mock.Mock(spec=GoogleAuthCredentials)):
pass
mock_transport_cls.create_channel.assert_called_once()
@@ -2072,22 +2101,14 @@ def test_bigquery_client_retries_transient_token_refresh_failures():
endpoint escaped every `bigquery_client` call site as an opaque `RefreshError` instead of
being retried. `bigquery_client` must hand `AuthorizedSession` an `auth_request` built from
a session carrying `BIGQUERY_TOKEN_REFRESH_RETRY`."""
- with mock.patch.object(
- bq_module.service_account.Credentials,
- "from_service_account_info",
- return_value=mock.Mock(spec=GoogleAuthCredentials),
- ):
- with bq_module.bigquery_client(
- project_id="project-id",
- location=None,
- private_key="private-key",
- private_key_id="private-key-id",
- client_email="client-email",
- 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"))
- retry = adapter.max_retries
+ with bq_module.bigquery_client(
+ project_id="project-id",
+ location=None,
+ credentials=mock.Mock(spec=GoogleAuthCredentials),
+ ) as client:
+ auth_request_session = client._http._auth_request.session
+ adapter = cast(HTTPAdapter, auth_request_session.get_adapter("https://oauth2.googleapis.com"))
+ retry = adapter.max_retries
assert retry is BIGQUERY_TOKEN_REFRESH_RETRY
assert retry.allowed_methods and "POST" in retry.allowed_methods
@@ -2224,3 +2245,187 @@ def test_bigquery_build_pipeline_threads_resolved_rest_api_version(pin):
BigQuerySource().source_for_pipeline(_make_config(), _make_inputs(api_version=pin))
assert mock_build.call_args.kwargs["rest_api_version"] == "v2"
+
+
+# A BigQuery source authenticates either with a Google Cloud service account integration (shared
+# across the team, and keyless when PostHog impersonates the account) or with a JSON key file
+# uploaded onto the source itself. `resolve_bigquery_auth` picks between them once per run, and
+# every client the run opens signs with what it returns.
+
+
+_BATCH_EXPORT_MODULE = "products.batch_exports.backend.temporal.destinations.bigquery_batch_export"
+
+
+def _google_cloud_integration(team, *, with_key: bool, email: str = "[email protected]"):
+ return Integration.objects.create(
+ team=team,
+ kind=Integration.IntegrationKind.GOOGLE_CLOUD_SERVICE_ACCOUNT,
+ integration_id=f"{email}-{team.id}-{'key-file' if with_key else 'impersonated'}",
+ config={"project_id": "integration-project", "service_account_email": email},
+ sensitive_config=(
+ {
+ "private_key": "private-key",
+ "private_key_id": "private-key-id",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ }
+ if with_key
+ else {}
+ ),
+ )
+
+
+def test_bigquery_auth_from_integration_with_a_key_signs_with_the_integrations_key(team):
+ integration = _google_cloud_integration(team, with_key=True)
+ config = BigQuerySourceConfig(dataset_id="my_dataset", auth_type=_integration_auth(integration.id))
+
+ with mock.patch.object(bq_module.service_account.Credentials, "from_service_account_info") as mock_creds:
+ auth = resolve_bigquery_auth(config, team_id=team.id)
+
+ # The project must come from the integration, not from a key file the source no longer has.
+ assert auth.project_id == "integration-project"
+ assert mock_creds.call_args.args[0]["client_email"] == "[email protected]"
+
+
+def test_bigquery_auth_from_keyless_integration_impersonates_only_after_ownership_is_verified(team, settings):
+ """A keyless integration means PostHog signs as the customer's service account using its own
+ identity. Without the ownership check, a team that merely knows another org's service account
+ email could have PostHog read that org's data on its behalf."""
+ settings.BATCH_EXPORT_BIGQUERY_STS_AUDIENCE_FIELD = "//iam.googleapis.com/projects/1/locations/global"
+ settings.BATCH_EXPORT_BIGQUERY_SERVICE_ACCOUNT = "[email protected]"
+ integration = _google_cloud_integration(team, with_key=False)
+ config = BigQuerySourceConfig(dataset_id="my_dataset", auth_type=_integration_auth(integration.id))
+
+ with (
+ mock.patch(f"{_BATCH_EXPORT_MODULE}.verify_impersonated_service_account_ownership") as mock_verify,
+ mock.patch(f"{_BATCH_EXPORT_MODULE}.get_our_google_cloud_credentials"),
+ mock.patch.object(bq_module.google_auth_impersonated_credentials, "Credentials") as mock_impersonated,
+ ):
+ auth = resolve_bigquery_auth(config, team_id=team.id)
+
+ mock_verify.assert_awaited_once_with("[email protected]", team.id)
+ assert auth.project_id == "integration-project"
+ assert auth.credentials is mock_impersonated.return_value
+ assert mock_impersonated.call_args.kwargs["target_principal"] == "[email protected]"
+
+
+def test_bigquery_unverified_service_account_ownership_is_reported_and_not_retried(team, settings):
+ settings.BATCH_EXPORT_BIGQUERY_STS_AUDIENCE_FIELD = "//iam.googleapis.com/projects/1/locations/global"
+ settings.BATCH_EXPORT_BIGQUERY_SERVICE_ACCOUNT = "[email protected]"
+ integration = _google_cloud_integration(team, with_key=False)
+ config = BigQuerySourceConfig(dataset_id="my_dataset", auth_type=_integration_auth(integration.id))
+ # Verbatim wording from batch exports, which raises the same error for the same check.
+ ownership_error = ServiceAccountOwnershipError("[email protected]", "org-uuid")
+
+ with (
+ mock.patch(
+ f"{_BATCH_EXPORT_MODULE}.verify_impersonated_service_account_ownership", side_effect=ownership_error
+ ),
+ mock.patch(f"{_BATCH_EXPORT_MODULE}.get_our_google_cloud_credentials"),
+ mock.patch.object(bq_module, "bigquery_client") as mock_client,
+ ):
+ ok, message = BigQuerySource().validate_credentials(config, team_id=team.id)
+
+ assert ok is False
+ assert message == str(ownership_error)
+ mock_client.assert_not_called()
+ # The customer has to change their service account description, so the sync must stop rather
+ # than retry the same rejection every run.
+ assert any(key in str(ownership_error) for key in BigQuerySource().get_non_retryable_errors())
+
+
+def test_bigquery_auth_follows_the_selection_when_both_credentials_are_stored(team):
+ """Switching an existing source to a service account leaves the old upload in `job_inputs`. The
+ selection has to decide, or the source keeps syncing on a key the customer thinks is retired."""
+ integration = _google_cloud_integration(team, with_key=True)
+ config = BigQuerySourceConfig(
+ dataset_id="my_dataset",
+ auth_type=BigQueryAuthTypeConfig(
+ selection="service_account",
+ google_cloud_service_account_integration_id=integration.id,
+ key_file=_key_file(project_id="stale-key-file-project"),
+ ),
+ )
+
+ assert resolve_bigquery_auth(config, team_id=team.id).project_id == "integration-project"
+
+ config.auth_type.selection = "key_file"
+
+ assert resolve_bigquery_auth(config, team_id=team.id).project_id == "stale-key-file-project"
+
+
+def test_bigquery_auth_rejects_an_integration_belonging_to_another_team(team):
+ other_team = Team.objects.create(organization=team.organization, name="other")
+ integration = _google_cloud_integration(other_team, with_key=True)
+ config = BigQuerySourceConfig(dataset_id="my_dataset", auth_type=_integration_auth(integration.id))
+
+ with pytest.raises(BigQueryAuthResolutionError) as exc_info:
+ resolve_bigquery_auth(config, team_id=team.id)
+
+ assert str(exc_info.value) == BIGQUERY_INTEGRATION_NOT_FOUND_ERROR
+
+
+def test_bigquery_disconnected_integration_is_reported_and_not_retried(team):
+ config = BigQuerySourceConfig(dataset_id="my_dataset", auth_type=_integration_auth(999999999))
+
+ with mock.patch.object(bq_module, "bigquery_client") as mock_client:
+ ok, message = BigQuerySource().validate_credentials(config, team_id=team.id)
+
+ assert (ok, message) == (False, BIGQUERY_INTEGRATION_NOT_FOUND_ERROR)
+ mock_client.assert_not_called()
+ # Reconnecting is the only fix, so the sync must stop instead of retrying every run.
+ assert BIGQUERY_INTEGRATION_NOT_FOUND_ERROR in BigQuerySource().get_non_retryable_errors()
+
+
+def test_bigquery_connect_works_for_a_source_with_no_key_file(team):
+ """Schema discovery resolves the project it queries from the open connection, because a source
+ authenticating through an integration has no key file to read a project out of."""
+ integration = _google_cloud_integration(team, with_key=True)
+ config = BigQuerySourceConfig(dataset_id="my_dataset", auth_type=_integration_auth(integration.id))
+ fake_bq = mock.MagicMock()
+ fake_bq.get_dataset.return_value.location = "europe-west1"
+
+ with _patch_bigquery_client(fake_bq) as mock_client:
+ with BigQueryImplementation().connect(config, team_id=team.id) as conn:
+ assert conn is fake_bq
+
+ assert mock_client.call_args_list[-1][0][0] == "integration-project"
+ assert mock_client.call_args_list[-1][0][1] == "europe-west1"
+
+
+_COMPLETE_KEY_FILE = {
+ "project_id": "my-project",
+ "private_key": "private-key",
+ "private_key_id": "private-key-id",
+ "client_email": "client-email",
+ "token_uri": "https://oauth2.googleapis.com/token",
+}
+
+
+ "auth_type,expected_valid",
+ [
+ ({"selection": "service_account", "google_cloud_service_account_integration_id": 7}, True),
+ ({"selection": "key_file", "key_file": _COMPLETE_KEY_FILE}, True),
+ ({"selection": "service_account", "google_cloud_service_account_integration_id": ""}, False),
+ ({"selection": "key_file", "key_file": {}}, False),
+ # The credential the user did not pick must not satisfy the one they did.
+ ({"selection": "service_account", "key_file": _COMPLETE_KEY_FILE}, False),
+ ({"selection": "key_file", "google_cloud_service_account_integration_id": 7}, False),
+ ],
+)
+def test_bigquery_validate_config_requires_the_credential_for_the_selected_auth_type(auth_type, expected_valid):
+ """The credential fields under each option are optional on the form, so the option the user did
+ not pick does not block the save. That makes this the only check stopping a source being created
+ with no usable credentials."""
+ is_valid, errors = BigQuerySource().validate_config({"dataset_id": "d", "auth_type": auth_type})
+
+ assert is_valid is expected_valid
+ if not expected_valid:
+ assert any("Google Cloud service account" in error for error in errors)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py
index c80d2827f3c8..246a4f49f65f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_source_config_generator.py
@@ -592,3 +592,48 @@ class TestSourceConfigGenerator(ClickhouseTestMixin):
output = self._run({ExternalDataSourceType.STRIPE: config})
assert "class StripeSwitchGroupConfig(config.Config):" in output
assert "switch_group: StripeSwitchGroupConfig" in output
+
+ def test_a_nested_config_is_declared_before_the_nested_config_that_references_it(self):
+ """Python evaluates an annotation when the class body runs, so a generated module whose
+ classes are ordered alphabetically raises `NameError` on import as soon as one nested config
+ names another. A file upload inside a select option is the shape that produces that pair."""
+ config = SourceConfig(
+ name=ExternalDataSourceType.STRIPE,
+ iconPath="",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="auth_type",
+ label="auth type label",
+ required=True,
+ defaultValue="key_file",
+ options=[
+ SourceFieldSelectConfigOption(
+ label="key file",
+ value="key_file",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldFileUploadConfig(
+ name="key_file",
+ label="key file label",
+ fileFormat=SourceFieldFileUploadJsonFormatConfig(
+ format=".json", keys=["project_id"]
+ ),
+ required=False,
+ ),
+ ],
+ ),
+ ),
+ ],
+ )
+ ],
+ ),
+ )
+
+ output = self._run({ExternalDataSourceType.STRIPE: config})
+
+ referenced = output.index("class StripeAuthTypeConfigKeyFileConfig(config.Config):")
+ referencing = output.index("class StripeAuthTypeConfig(config.Config):")
+ assert referenced < referencing
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigquery.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigquery.py
index f218bc67374b..5916ff80de0e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigquery.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigquery.py
@@ -1,17 +1,13 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
-from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
-
+from typing import Literal
-class BigQueryDatasetProjectConfig(config.Config):
- dataset_project_id: str
- enabled: bool = config.value(converter=config.str_to_bool, default=False)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@config.config
-class BigQueryKeyFileConfig(config.Config):
+class BigQueryAuthTypeConfigKeyFileConfig(config.Config):
project_id: str
private_key: str
private_key_id: str
@@ -19,6 +15,21 @@ class BigQueryKeyFileConfig(config.Config):
token_uri: str
+class BigQueryAuthTypeConfig(config.Config):
+ google_cloud_service_account_integration_id: int | None = config.value(
+ converter=config.str_to_optional_int, default_factory=lambda: None
+ )
+ selection: Literal["service_account", "key_file"] = "service_account"
+ key_file: BigQueryAuthTypeConfigKeyFileConfig | None = None
+
+
+class BigQueryDatasetProjectConfig(config.Config):
+ dataset_project_id: str
+ enabled: bool = config.value(converter=config.str_to_bool, default=False)
+
+
@config.config
class BigQueryTemporaryDatasetConfig(config.Config):
temporary_dataset_id: str
@@ -33,7 +44,7 @@ class BigQueryUseCustomRegionConfig(config.Config):
@config.config
class BigQuerySourceConfig(config.Config):
- key_file: BigQueryKeyFileConfig
+ auth_type: BigQueryAuthTypeConfig
dataset_id: str
temporary_dataset: BigQueryTemporaryDatasetConfig | None = config.value(
alias="temporary-dataset", default_factory=lambda: None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py
index 40c026b57e0c..7a1d249037aa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py
@@ -64,12 +64,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
def test_bigquery_config(temporary_dataset_key: str):
config = BigQuerySourceConfig.from_dict(
{
- "key_file": {
- "project_id": "project_id",
- "private_key_id": "private_key_id",
- "private_key": "private_key",
- "client_email": "client_email",
- "token_uri": "token_uri",
+ "auth_type": {
+ "selection": "key_file",
+ "key_file": {
+ "project_id": "project_id",
+ "private_key_id": "private_key_id",
+ "private_key": "private_key",
+ "client_email": "client_email",
+ "token_uri": "token_uri",
+ },
},
"dataset_id": "dataset_id",
temporary_dataset_key: {"enabled": False, "temporary_dataset_id": ""},
@@ -77,11 +80,13 @@ def test_bigquery_config(temporary_dataset_key: str):
}
)
- assert config.key_file.project_id == "project_id"
- assert config.key_file.private_key_id == "private_key_id"
- assert config.key_file.private_key == "private_key"
- assert config.key_file.client_email == "client_email"
- assert config.key_file.token_uri == "token_uri"
+ assert config.auth_type.selection == "key_file"
+ assert config.auth_type.key_file is not None
+ assert config.auth_type.key_file.project_id == "project_id"
+ assert config.auth_type.key_file.private_key_id == "private_key_id"
+ assert config.auth_type.key_file.private_key == "private_key"
+ assert config.auth_type.key_file.client_email == "client_email"
+ assert config.auth_type.key_file.token_uri == "token_uri"
assert config.dataset_id == "dataset_id"
assert config.temporary_dataset is not None
assert config.temporary_dataset.enabled is False
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 5c08326dbc13..2d7fa585c9a2 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -2406,12 +2406,15 @@ class TestExternalDataSource(APIBaseTest):
},
],
"dataset_id": "my_project.my_dataset",
- "key_file": {
- "project_id": "my_project",
- "private_key": "my_private_key",
- "private_key_id": "my_private_key_id",
- "token_uri": "https://google.com",
- "client_email": "[email protected]",
+ "auth_type": {
+ "selection": "key_file",
+ "key_file": {
+ "project_id": "my_project",
+ "private_key": "my_private_key",
+ "private_key_id": "my_private_key_id",
+ "token_uri": "https://google.com",
+ "client_email": "[email protected]",
+ },
},
},
},
@@ -2422,9 +2425,9 @@ class TestExternalDataSource(APIBaseTest):
source = response.json()
source_model = ExternalDataSource.objects.get(id=source["id"])
- assert source_model.job_inputs["key_file"]["project_id"] == "my_project"
- assert source_model.job_inputs["key_file"]["private_key"] == "my_private_key"
- assert source_model.job_inputs["key_file"]["private_key_id"] == "my_private_key_id"
+ assert source_model.job_inputs["auth_type"]["key_file"]["project_id"] == "my_project"
+ assert source_model.job_inputs["auth_type"]["key_file"]["private_key"] == "my_private_key"
+ assert source_model.job_inputs["auth_type"]["key_file"]["private_key_id"] == "my_private_key_id"
assert source_model.job_inputs["dataset_id"] == "my_project.my_dataset"
def test_create_external_data_source_missing_required_bigquery_job_input(self):
@@ -2435,10 +2438,13 @@ class TestExternalDataSource(APIBaseTest):
"created_via": "web",
"payload": {
"dataset_id": "my_dataset",
- "key_file": {
- "project_id": "my_project",
- "token_uri": "https://google.com",
- "client_email": "[email protected]",
+ "auth_type": {
+ "selection": "key_file",
+ "key_file": {
+ "project_id": "my_project",
+ "token_uri": "https://google.com",
+ "client_email": "[email protected]",
+ },
},
},
},
@@ -2487,12 +2493,15 @@ class TestExternalDataSource(APIBaseTest):
{"name": "my_table", "should_sync": True, "sync_type": "full_refresh"},
],
"dataset_id": "my_project.my_dataset",
- "key_file": {
- "project_id": "my_project",
- "private_key": "my_private_key",
- "private_key_id": "my_private_key_id",
- "token_uri": "https://google.com",
- "client_email": "[email protected]",
+ "auth_type": {
+ "selection": "key_file",
+ "key_file": {
+ "project_id": "my_project",
+ "private_key": "my_private_key",
+ "private_key_id": "my_private_key_id",
+ "token_uri": "https://google.com",
+ "client_email": "[email protected]",
+ },
},
},
},
@@ -8469,18 +8478,21 @@ class TestExternalDataSource(APIBaseTest):
"created_via": "web",
"payload": {
"source_type": "BigQuery",
- "key_file": {
- "type": "service_account",
- "project_id": "dummy_project_id",
- "private_key_id": "dummy_private_key_id",
- "private_key": "dummy_private_key",
- "client_email": "dummy_client_email",
- "client_id": "dummy_client_id",
- "auth_uri": "dummy_auth_uri",
- "token_uri": "dummy_token_uri",
- "auth_provider_x509_cert_url": "dummy_auth_provider_x509_cert_url",
- "client_x509_cert_url": "dummy_client_x509_cert_url",
- "universe_domain": "dummy_universe_domain",
+ "auth_type": {
+ "selection": "key_file",
+ "key_file": {
+ "type": "service_account",
+ "project_id": "dummy_project_id",
+ "private_key_id": "dummy_private_key_id",
+ "private_key": "dummy_private_key",
+ "client_email": "dummy_client_email",
+ "client_id": "dummy_client_id",
+ "auth_uri": "dummy_auth_uri",
+ "token_uri": "dummy_token_uri",
+ "auth_provider_x509_cert_url": "dummy_auth_provider_x509_cert_url",
+ "client_x509_cert_url": "dummy_client_x509_cert_url",
+ "universe_domain": "dummy_universe_domain",
+ },
},
"dataset_id": "dummy_dataset_id",
"use_custom_region": {"enabled": False, "region": ""},
@@ -8510,13 +8522,14 @@ class TestExternalDataSource(APIBaseTest):
# validate against the actual class we use in the Temporal activity
bq_config = BigQuerySourceConfig.from_dict(job_inputs)
+ assert bq_config.auth_type.key_file is not None
- assert bq_config.key_file.project_id == "dummy_project_id"
+ assert bq_config.auth_type.key_file.project_id == "dummy_project_id"
assert bq_config.dataset_id == "dummy_dataset_id"
- assert bq_config.key_file.private_key == "dummy_private_key"
- assert bq_config.key_file.private_key_id == "dummy_private_key_id"
- assert bq_config.key_file.client_email == "dummy_client_email"
- assert bq_config.key_file.token_uri == "dummy_token_uri"
+ assert bq_config.auth_type.key_file.private_key == "dummy_private_key"
+ assert bq_config.auth_type.key_file.private_key_id == "dummy_private_key_id"
+ assert bq_config.auth_type.key_file.client_email == "dummy_client_email"
+ assert bq_config.auth_type.key_file.token_uri == "dummy_token_uri"
assert bq_config.use_custom_region is not None
assert bq_config.use_custom_region.enabled is False
assert bq_config.temporary_dataset is not None
@@ -8539,18 +8552,21 @@ class TestExternalDataSource(APIBaseTest):
"client_email": "dummy_client_email",
"temporary-dataset": {"enabled": True, "temporary_dataset_id": "dummy_temporary_dataset_id"},
"dataset_project": {"enabled": False, "dataset_project_id": ""},
- "key_file": {
- "type": "service_account",
- "project_id": "dummy_project_id",
- "private_key_id": "dummy_private_key_id",
- "private_key": "dummy_private_key",
- "client_email": "dummy_client_email",
- "client_id": "dummy_client_id",
- "auth_uri": "dummy_auth_uri",
- "token_uri": "dummy_token_uri",
- "auth_provider_x509_cert_url": "dummy_auth_provider_x509_cert_url",
- "client_x509_cert_url": "dummy_client_x509_cert_url",
- "universe_domain": "dummy_universe_domain",
+ "auth_type": {
+ "selection": "key_file",
+ "key_file": {
+ "type": "service_account",
+ "project_id": "dummy_project_id",
+ "private_key_id": "dummy_private_key_id",
+ "private_key": "dummy_private_key",
+ "client_email": "dummy_client_email",
+ "client_id": "dummy_client_id",
+ "auth_uri": "dummy_auth_uri",
+ "token_uri": "dummy_token_uri",
+ "auth_provider_x509_cert_url": "dummy_auth_provider_x509_cert_url",
+ "client_x509_cert_url": "dummy_client_x509_cert_url",
+ "universe_domain": "dummy_universe_domain",
+ },
},
}
},
@@ -8562,13 +8578,14 @@ class TestExternalDataSource(APIBaseTest):
# validate against the actual class we use in the Temporal activity
bq_config = BigQuerySourceConfig.from_dict(source_model.job_inputs)
+ assert bq_config.auth_type.key_file is not None
- assert bq_config.key_file.project_id == "dummy_project_id"
+ assert bq_config.auth_type.key_file.project_id == "dummy_project_id"
assert bq_config.dataset_id == "dummy_dataset_id"
- assert bq_config.key_file.private_key == "dummy_private_key"
- assert bq_config.key_file.private_key_id == "dummy_private_key_id"
- assert bq_config.key_file.client_email == "dummy_client_email"
- assert bq_config.key_file.token_uri == "dummy_token_uri"
+ assert bq_config.auth_type.key_file.private_key == "dummy_private_key"
+ assert bq_config.auth_type.key_file.private_key_id == "dummy_private_key_id"
+ assert bq_config.auth_type.key_file.client_email == "dummy_client_email"
+ assert bq_config.auth_type.key_file.token_uri == "dummy_token_uri"
assert bq_config.use_custom_region is not None
assert bq_config.use_custom_region.enabled is False
assert bq_config.temporary_dataset is not None
@@ -8591,18 +8608,21 @@ class TestExternalDataSource(APIBaseTest):
"client_email": "dummy_client_email",
"temporary-dataset": {"enabled": False, "temporary_dataset_id": ""},
"dataset_project": {"enabled": True, "dataset_project_id": "other_project_id"},
- "key_file": {
- "type": "service_account",
- "project_id": "dummy_project_id",
- "private_key_id": "dummy_private_key_id",
- "private_key": "dummy_private_key",
- "client_email": "dummy_client_email",
- "client_id": "dummy_client_id",
- "auth_uri": "dummy_auth_uri",
- "token_uri": "dummy_token_uri",
- "auth_provider_x509_cert_url": "dummy_auth_provider_x509_cert_url",
- "client_x509_cert_url": "dummy_client_x509_cert_url",
- "universe_domain": "dummy_universe_domain",
+ "auth_type": {
+ "selection": "key_file",
+ "key_file": {
+ "type": "service_account",
+ "project_id": "dummy_project_id",
+ "private_key_id": "dummy_private_key_id",
+ "private_key": "dummy_private_key",
+ "client_email": "dummy_client_email",
+ "client_id": "dummy_client_id",
+ "auth_uri": "dummy_auth_uri",
+ "token_uri": "dummy_token_uri",
+ "auth_provider_x509_cert_url": "dummy_auth_provider_x509_cert_url",
+ "client_x509_cert_url": "dummy_client_x509_cert_url",
+ "universe_domain": "dummy_universe_domain",
+ },
},
}
},
@@ -8614,13 +8634,14 @@ class TestExternalDataSource(APIBaseTest):
# validate against the actual class we use in the Temporal activity
bq_config = BigQuerySourceConfig.from_dict(source_model.job_inputs)
+ assert bq_config.auth_type.key_file is not None
- assert bq_config.key_file.project_id == "dummy_project_id"
+ assert bq_config.auth_type.key_file.project_id == "dummy_project_id"
assert bq_config.dataset_id == "dummy_dataset_id"
- assert bq_config.key_file.private_key == "dummy_private_key"
- assert bq_config.key_file.private_key_id == "dummy_private_key_id"
- assert bq_config.key_file.client_email == "dummy_client_email"
- assert bq_config.key_file.token_uri == "dummy_token_uri"
+ assert bq_config.auth_type.key_file.private_key == "dummy_private_key"
+ assert bq_config.auth_type.key_file.private_key_id == "dummy_private_key_id"
+ assert bq_config.auth_type.key_file.client_email == "dummy_client_email"
+ assert bq_config.auth_type.key_file.token_uri == "dummy_token_uri"
assert bq_config.use_custom_region is not None
assert bq_config.use_custom_region.enabled is False
assert bq_config.temporary_dataset is not None
@@ -14108,12 +14129,15 @@ class TestBigQuerySwitchGroups(APIBaseTest):
created_by=self.user,
prefix="bq",
job_inputs={
- "key_file": {
- "project_id": "project_id",
- "private_key_id": "private_key_id",
- "private_key": "private_key",
- "client_email": "client_email",
- "token_uri": "token_uri",
+ "auth_type": {
+ "selection": "key_file",
+ "key_file": {
+ "project_id": "project_id",
+ "private_key_id": "private_key_id",
+ "private_key": "private_key",
+ "client_email": "client_email",
+ "token_uri": "token_uri",
+ },
},
"dataset_id": "my_dataset",
**job_inputs,
diff --git a/products/warehouse_sources/backend/tests/test_migrate_bigquery_job_inputs_to_auth_type.py b/products/warehouse_sources/backend/tests/test_migrate_bigquery_job_inputs_to_auth_type.py
new file mode 100644
index 000000000000..62bb9e45fc52
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_migrate_bigquery_job_inputs_to_auth_type.py
@@ -0,0 +1,76 @@
+import importlib
+
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bigquery import (
+ BigQuerySourceConfig,
+)
+
+# The module name starts with a digit, so it cannot be imported with a normal import statement.
+migration = importlib.import_module(
+ "products.warehouse_sources.backend.migrations.0165_migrate_bigquery_job_inputs_to_auth_type"
+)
+
+_KEY_FILE = {
+ "project_id": "my-project",
+ "private_key": "private-key",
+ "private_key_id": "private-key-id",
+ "client_email": "client-email",
+ "token_uri": "https://oauth2.googleapis.com/token",
+}
+
+
+def test_migrated_job_inputs_parse_as_a_key_file_source():
+ """Every BigQuery source predates `auth_type`, so the reshape this migration performs is the
+ only thing that keeps them parsing once the new config class requires it."""
+ migrated = migration.nest_key_file_under_auth_type(
+ {"key_file": dict(_KEY_FILE), "dataset_id": "my_dataset", "temporary-dataset": {"enabled": False}}
+ )
+ assert migrated is not None
+
+ config = BigQuerySourceConfig.from_dict(migrated)
+
+ assert config.auth_type.selection == "key_file"
+ assert config.auth_type.key_file is not None
+ assert config.auth_type.key_file.project_id == "my-project"
+ # Everything outside the credential must survive untouched.
+ assert config.dataset_id == "my_dataset"
+
+
+ "job_inputs,expected_key_file",
+ [
+ ({"key_file": dict(_KEY_FILE)}, _KEY_FILE),
+ # A source whose upload never landed still needs an `auth_type`, or it stops parsing and
+ # reports a config error instead of the missing credentials it actually has.
+ ({}, {}),
+ ({"key_file": None}, {}),
+ ],
+)
+def test_migration_nests_whatever_key_file_the_source_holds(job_inputs, expected_key_file):
+ migrated = migration.nest_key_file_under_auth_type(job_inputs)
+
+ assert migrated == {"auth_type": {"selection": "key_file", "key_file": expected_key_file}}
+
+
+def test_migration_leaves_an_already_migrated_source_alone():
+ """The migration can be re-run by a retry, and it must not wrap `auth_type` in a second one."""
+ assert migration.nest_key_file_under_auth_type({"auth_type": {"selection": "service_account"}}) is None
+
+
+ "auth_type,expected",
+ [
+ ({"selection": "key_file", "key_file": _KEY_FILE}, {"key_file": _KEY_FILE}),
+ (
+ {"selection": "service_account", "google_cloud_service_account_integration_id": 7},
+ {"google_cloud_service_account_integration_id": 7},
+ ),
+ ],
+)
+def test_reverse_restores_the_shape_the_previous_release_reads(auth_type, expected):
+ """A rollback runs the previous release against these rows, and that code reads `key_file` from
+ the top level."""
+ flattened = migration.flatten_auth_type_to_key_file({"auth_type": auth_type, "dataset_id": "my_dataset"})
+
+ assert flattened == {**expected, "dataset_id": "my_dataset"}