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(bigquery): stop key file field names blocking source setup (#105736)

Tom Owersb88941af8682
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 5df0c84878d1..d9dda7ea5625 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
@@ -1,3 +1,4 @@
+import dataclasses
from typing import Optional, cast
from products.warehouse_sources.backend.facade.source_config import (
@@ -35,6 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b
resolve_bigquery_auth,
validate_bigquery_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config as source_config
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
UNVERSIONED_API_VERSION,
FieldType,
@@ -42,6 +44,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bigquery import (
+ BigQueryAuthTypeConfigKeyFileConfig,
BigQuerySourceConfig,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -50,6 +53,16 @@ __all__ = ["BigQuerySource", "build_destination_table_prefix"]
_BIGQUERY_IMPLEMENTATION = BigQueryImplementation()
+# Every field of the key file is read out of the JSON the user uploads, never typed into the form,
+# so the generic "Required field ..." error for one names something they have no way to fill in.
+_KEY_FILE_FIELD_NAMES = tuple(field.name for field in dataclasses.fields(BigQueryAuthTypeConfigKeyFileConfig))
+_KEY_FILE_FIELD_ERRORS = frozenset(source_config.missing_field_error(name) for name in _KEY_FILE_FIELD_NAMES)
+_MISSING_KEY_FILE_ERROR = "Upload a Google Cloud service account JSON key file."
+_INCOMPLETE_KEY_FILE_ERROR = (
+ "That file is not a complete Google Cloud service account key. Upload the JSON key file "
+ "exactly as you downloaded it, then try again."
+)
+
@SourceRegistry.register
class BigQuerySource(SQLSource[BigQuerySourceConfig]):
@@ -392,19 +405,36 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
def validate_config(self, job_inputs: dict) -> tuple[bool, list[str]]:
is_valid, errors = super().validate_config(job_inputs)
+ # An empty `key_file` object reaches us both when the upload produced nothing and when the
+ # form sends the option the user did not pick, so on its own it says nothing worth showing.
+ if any(error in _KEY_FILE_FIELD_ERRORS for error in errors):
+ errors = [error for error in errors if error not in _KEY_FILE_FIELD_ERRORS]
+ is_valid = not errors
+
# 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):
+ selection: str | None
+ credentials: dict
+ if isinstance(auth_type, str):
+ # A select container also arrives as the bare string naming the chosen option, and
+ # then its fields sit at the top level of the payload rather than under it.
+ selection, credentials = auth_type, job_inputs
+ elif isinstance(auth_type, dict):
+ selection, credentials = auth_type.get("selection"), auth_type
+ else:
return is_valid, errors
- if auth_type.get("selection") == "key_file":
- key_file = auth_type.get("key_file")
+ if selection == "key_file":
+ key_file = credentials.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.")
+ errors.append(_MISSING_KEY_FILE_ERROR)
+ is_valid = False
+ elif not all(key_file.get(name) for name in _KEY_FILE_FIELD_NAMES):
+ errors.append(_INCOMPLETE_KEY_FILE_ERROR)
is_valid = False
- elif auth_type.get("google_cloud_service_account_integration_id") in (None, ""):
+ elif credentials.get("google_cloud_service_account_integration_id") in (None, ""):
errors.append("Pick a Google Cloud service account.")
is_valid = False
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 d8fc1103dc47..5fd5910161fe 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
@@ -2429,6 +2429,9 @@ _COMPLETE_KEY_FILE = {
# 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),
+ ({"selection": "service_account", "google_cloud_service_account_integration_id": 7, "key_file": {}}, True),
+ ({"selection": "key_file", "key_file": {"type": "authorized_user"}}, False),
+ ({"selection": "key_file", "key_file": {"project_id": "my-project"}}, False),
],
)
def test_bigquery_validate_config_requires_the_credential_for_the_selected_auth_type(auth_type, expected_valid):
@@ -2438,5 +2441,26 @@ def test_bigquery_validate_config_requires_the_credential_for_the_selected_auth_
is_valid, errors = BigQuerySource().validate_config({"dataset_id": "d", "auth_type": auth_type})
assert is_valid is expected_valid
+ assert not any("Required field" in error for error in errors)
+ if not expected_valid:
+ assert any("Google Cloud service account" in error for error in errors)
+
+
+ "job_inputs,expected_valid",
+ [
+ ({"auth_type": "service_account", "google_cloud_service_account_integration_id": 7}, True),
+ ({"auth_type": "key_file", "key_file": _COMPLETE_KEY_FILE}, True),
+ ({"auth_type": "service_account"}, False),
+ ({"auth_type": "key_file"}, False),
+ ({"auth_type": "key_file", "key_file": {"project_id": "my-project"}}, False),
+ ({"auth_type": "key_file", "key_file": {**_COMPLETE_KEY_FILE, "private_key": ""}}, False),
+ ],
+)
+def test_bigquery_validate_config_reads_a_bare_selection_from_the_flat_payload(job_inputs, expected_valid):
+ is_valid, errors = BigQuerySource().validate_config({"dataset_id": "d", **job_inputs})
+
+ assert is_valid is expected_valid
+ assert not any("Required field" in error for error in errors)
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/config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py
index e120e16c9b85..eb78a0a43eb6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py
@@ -183,6 +183,14 @@ def _selection_options(config_type: type) -> tuple[str, ...] | None:
return None
+def missing_field_error(field_name: str) -> str:
+ """The error `validate_config` reports for a required field that is absent.
+
+ Exposed so a source that replaces one of these with its own copy can match on it without
+ duplicating the wording."""
+ return f"Required field '{field_name}' is missing"
+
+
def validate_config(
config_cls: type, d: dict[str, typing.Any], prefixes: tuple[str, ...] | None = None
) -> tuple[bool, list[str]]:
@@ -212,7 +220,7 @@ def validate_config(
if field_flat_key not in d and field_nested_key not in d and field.name not in d:
# Field not found in dict
if field.default is dataclasses.MISSING and field.default_factory is dataclasses.MISSING:
- errors.append(f"Required field '{field.name}' is missing")
+ errors.append(missing_field_error(field.name))
continue
# Validate nested configs
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 d2485ec42280..75c4df65a4f8 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
@@ -2452,8 +2452,7 @@ class TestExternalDataSource(APIBaseTest):
assert response.status_code == 400
assert len(ExternalDataSource.objects.all()) == 0
assert response.json()["message"].startswith("Invalid source config")
- assert "'private_key'" in response.json()["message"]
- assert "'private_key_id'" in response.json()["message"]
+ assert "not a complete Google Cloud service account key" in response.json()["message"]
@patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")
def test_create_external_data_source_bigquery_returns_400_on_credentials_rejected_during_schema_discovery(