:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): return a clear error when a source credential probe raises (#82658)
Tom Owers5a72472f96b9
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.pyindex f968a1d5c77e..fa98fa660860 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py@@ -221,6 +221,17 @@ def _classify_refresh_schemas_error(source: AnySource | None, error: Exception)return REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE, False+def _credentials_validation_failed(source: AnySource, team_id: int, error: Exception) -> tuple[bool, str | None]:+ """Fallback result for an *unexpected* exception raised by a source's credential probe.++ Sources are expected to catch their own errors and return ``(False, message)``. One that raises+ instead would 500 the create/update request and show someone mid-onboarding an opaque server+ error, so capture it for us and hand back an actionable message — the same treatment schema+ discovery already gives an unexpected error just below the credential check."""+ capture_exception(error, {"source_type": str(source.source_type), "team_id": team_id})+ return False, INVALID_CREDENTIALS_FALLBACK_MESSAGE++def get_sensitive_field_names(fields: list[FieldType]) -> set[str]:"""Extract field names that contain sensitive data from a source config's fields."""sensitive: set[str] = set()@@ -1200,29 +1211,32 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerif job_inputs_were_submitted:effective_api_version = source.resolve_api_version(instance.api_version)- if isinstance(source, (PostgresSource, MySQLSource)):- credentials_valid, credentials_error = source.validate_credentials_for_access_method(- cast(Any, source_config),- instance.team_id,- instance.access_method,- api_version=effective_api_version,- )- elif isinstance(source, CustomSource):- # Pass the source being updated so an integration-backed OAuth2 source can only validate- # with the integration bound to it — not another source's, whose token the probe would- # otherwise mint and send to the submitted manifest host. owner_user_id additionally gates- # an as-yet-unbound integration to its creator.- credentials_valid, credentials_error = source.validate_credentials(- source_config,- instance.team_id,- source_id=str(instance.pk),- owner_user_id=self.context["request"].user.id,- api_version=effective_api_version,- )- else:- credentials_valid, credentials_error = source.validate_credentials(- source_config, instance.team_id, api_version=effective_api_version- )+ try:+ if isinstance(source, (PostgresSource, MySQLSource)):+ credentials_valid, credentials_error = source.validate_credentials_for_access_method(+ cast(Any, source_config),+ instance.team_id,+ instance.access_method,+ api_version=effective_api_version,+ )+ elif isinstance(source, CustomSource):+ # Pass the source being updated so an integration-backed OAuth2 source can only validate+ # with the integration bound to it — not another source's, whose token the probe would+ # otherwise mint and send to the submitted manifest host. owner_user_id additionally gates+ # an as-yet-unbound integration to its creator.+ credentials_valid, credentials_error = source.validate_credentials(+ source_config,+ instance.team_id,+ source_id=str(instance.pk),+ owner_user_id=self.context["request"].user.id,+ api_version=effective_api_version,+ )+ else:+ credentials_valid, credentials_error = source.validate_credentials(+ source_config, instance.team_id, api_version=effective_api_version+ )+ except Exception as e:+ credentials_valid, credentials_error = _credentials_validation_failed(source, instance.team_id, e)if not credentials_valid:raise ValidationError(credentials_error or INVALID_CREDENTIALS_FALLBACK_MESSAGE)if instance.is_direct_query:@@ -3095,19 +3109,22 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixisource_config: Config = source.parse_config(request.data)access_method = request.data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE)- if isinstance(source, (PostgresSource, MySQLSource)):- credentials_valid, credentials_error = source.validate_credentials_for_access_method(- cast(Any, source_config), self.team_id, access_method- )- elif isinstance(source, CustomSource):- # Schema discovery for an as-yet-uncreated source: an integration-backed manifest may only use- # an unbound integration owned by the requester, or the probe could send another source's token- # to the submitted host.- credentials_valid, credentials_error = source.validate_credentials(- source_config, self.team_id, owner_user_id=self.request.user.id- )- else:- credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)+ try:+ if isinstance(source, (PostgresSource, MySQLSource)):+ credentials_valid, credentials_error = source.validate_credentials_for_access_method(+ cast(Any, source_config), self.team_id, access_method+ )+ elif isinstance(source, CustomSource):+ # Schema discovery for an as-yet-uncreated source: an integration-backed manifest may only use+ # an unbound integration owned by the requester, or the probe could send another source's token+ # to the submitted host.+ credentials_valid, credentials_error = source.validate_credentials(+ source_config, self.team_id, owner_user_id=self.request.user.id+ )+ else:+ credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)+ except Exception as e:+ credentials_valid, credentials_error = _credentials_validation_failed(source, self.team_id, e)if not credentials_valid:return Response(status=status.HTTP_400_BAD_REQUEST,@@ -3567,18 +3584,21 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi)source_config: Config = source.parse_config(payload)- if isinstance(source, (PostgresSource, MySQLSource)):- credentials_valid, credentials_error = source.validate_credentials_for_access_method(- cast(Any, source_config), self.team_id, access_method- )- elif isinstance(source, CustomSource):- # Create-time validation for an integration-backed manifest may only use an unbound integration- # owned by the requester, so the probe can't send another source's token to the submitted host.- credentials_valid, credentials_error = source.validate_credentials(- source_config, self.team_id, owner_user_id=self.request.user.id- )- else:- credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)+ try:+ if isinstance(source, (PostgresSource, MySQLSource)):+ credentials_valid, credentials_error = source.validate_credentials_for_access_method(+ cast(Any, source_config), self.team_id, access_method+ )+ elif isinstance(source, CustomSource):+ # Create-time validation for an integration-backed manifest may only use an unbound integration+ # owned by the requester, so the probe can't send another source's token to the submitted host.+ credentials_valid, credentials_error = source.validate_credentials(+ source_config, self.team_id, owner_user_id=self.request.user.id+ )+ else:+ credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)+ except Exception as e:+ credentials_valid, credentials_error = _credentials_validation_failed(source, self.team_id, e)if not credentials_valid:return (Response(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.pyindex eb9bfad1966a..f00dbb1b95e9 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@@ -56,6 +56,7 @@ from products.warehouse_sources.backend.facade.models import (from products.warehouse_sources.backend.facade.types import IncrementalFieldTypefrom products.warehouse_sources.backend.presentation.views.external_data_schema import ExternalDataSchemaSerializerfrom products.warehouse_sources.backend.presentation.views.external_data_source import (+ INVALID_CREDENTIALS_FALLBACK_MESSAGE,ExternalDataSourceViewSet,get_direct_connection_metadata,get_nonsensitive_and_sensitive_field_names,@@ -183,6 +184,31 @@ class TestExternalDataSource(APIBaseTest):source = ExternalDataSource.objects.get(id=payload["id"])self.assertEqual(source.api_version, "2024-09-30.acacia")+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ side_effect=AttributeError("boom"),+ )+ def test_create_surfaces_400_when_credential_probe_raises(self, _mock_validate):+ # A source whose validate_credentials raises (rather than returning (False, message)) must+ # not 500 the create request — the user gets an actionable message and no source is created.+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/",+ data={+ "source_type": "Stripe",+ "created_via": "web",+ "payload": {+ "auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"},+ "schemas": [+ {"name": name, "should_sync": True, "sync_type": "full_refresh"} for name in STRIPE_ENDPOINTS+ ],+ },+ },+ )++ self.assertEqual(response.status_code, 400)+ self.assertEqual(response.json()["message"], INVALID_CREDENTIALS_FALLBACK_MESSAGE)+ self.assertFalse(ExternalDataSource.objects.filter(team_id=self.team.pk).exists())+def test_api_version_pin_is_read_only_via_api(self):source = self._create_external_data_source()original_pin = source.api_version