: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): mask credentials in source sync errors (#108791)
posthog[bot]189443c016dd
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex c722e65e1261..3622892c014f 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -84,6 +84,7 @@ from products.warehouse_sources.backend.presentation.views.destination_links impSchemaDestinationsSerializer,set_schema_destinations,)+from products.warehouse_sources.backend.presentation.views.external_data_source import helpers as source_helpersfrom products.warehouse_sources.backend.presentation.views.source_api_versions import (ExternalDataSourceApiVersionDeprecationSerializer,api_version_deprecation_payload,@@ -353,6 +354,16 @@ def schema_display_status(schema: ExternalDataSchema) -> str | None:return schema.status+def redact_schema_error(schema: ExternalDataSchema, context: dict[str, Any]) -> str | None:+ if not schema.latest_error:+ return schema.latest_error+ # The source serializer passes its secret values in, so embedded schemas skip a per-schema source lookup.+ secret_values = context.get("error_redaction_values")+ if secret_values is None:+ secret_values = source_helpers.get_error_redaction_values(schema.source)+ return source_helpers.redact_error_message(schema.latest_error, secret_values)++class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):"""A schema of an external data source: its sync configuration and the warehouse table it syncs into."""@@ -759,6 +770,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersret["incremental_field_lookback_seconds"] = instance.incremental_field_lookback_secondsret["primary_key_columns"] = instance.primary_key_columnsret["cdc_table_mode"] = instance.cdc_table_mode+ ret["latest_error"] = redact_schema_error(instance, self.context)return retdef _run_temporal_side_effect(self, callback: Callable[[], None]) -> None:@@ -1685,6 +1697,11 @@ class ExternalDataSchemaListSerializer(serializers.ModelSerializer):def get_status(self, schema: ExternalDataSchema) -> str | None:return schema_display_status(schema)+ def to_representation(self, instance: ExternalDataSchema) -> dict[str, Any]:+ ret = super().to_representation(instance)+ ret["latest_error"] = redact_schema_error(instance, self.context)+ return ret+class SimpleExternalDataSchemaSerializer(serializers.ModelSerializer):class Meta:diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.pyindex 2581e58797aa..cda9f9ebd9f1 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py@@ -2,8 +2,10 @@from __future__ import annotations+import refrom collections.abc import Iterable, Mappingfrom typing import Any+from urllib.parse import unquote, urlsplitfrom django.db.models import Q, QuerySet@@ -34,10 +36,11 @@ from products.warehouse_sources.backend.facade.source_management import (AnySource,Config,FieldType,+ SourceRegistry,SourceSchema,source_requires_ssl,)-from products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLMode+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType, ManagedWarehouseSQLModeREFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE = "Could not fetch schemas from source."@@ -383,6 +386,107 @@ def strip_sensitive_from_dict(data: dict, nonsensitive: set[str], sensitive: setreturn result+REDACTED_VALUE = "***"++# Shorter stored values (e.g. a port or a boolean flag) would match unrelated parts of an error message.+_MIN_REDACTED_SECRET_LENGTH = 4++# Matches job_input keys that hold secrets even when a source config does not declare them.+_SECRET_KEY_NAME_PATTERN = re.compile(+ r"pass(word|wd|phrase)?|secret|token|api[_-]?key|private[_-]?key|credential|connection[_-]?string",+ re.IGNORECASE,+)++_SECRET_PARAM_NAMES = (+ r"api[_-]?key|apikey|access[_-]?key|secret[_-]?key|client[_-]?secret|secret|access[_-]?token|"+ r"refresh[_-]?token|auth[_-]?token|token|password|passwd|pwd|signature|sig|key"+)++_ERROR_REDACTION_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (+ # Password in URL userinfo: postgres://user:secret@host+ (re.compile(r"(\b[a-z][a-z0-9+.-]*://[^\s:/@?#]+:)[^\s/?#@]+@", re.IGNORECASE), rf"\1{REDACTED_VALUE}@"),+ # Query string or key=value pairs: ?api_key=secret, password=secret+ (+ re.compile(rf"((?<![a-z0-9_])(?:{_SECRET_PARAM_NAMES})=)[^\s&;,'\"]+", re.IGNORECASE),+ rf"\1{REDACTED_VALUE}",+ ),+ # JSON-like pairs: "password": "secret"+ (+ re.compile(rf"(['\"](?:{_SECRET_PARAM_NAMES})['\"]\s*:\s*['\"])[^'\"]*", re.IGNORECASE),+ rf"\1{REDACTED_VALUE}",+ ),+ # Authorization header values: Bearer abc.def, Basic dXNlcjpwYXNz+ (re.compile(r"\b(Bearer|Basic|Token)\s+[a-z0-9._~+/=-]{8,}", re.IGNORECASE), rf"\1 {REDACTED_VALUE}"),+)+++def _collect_string_leaves(value: Any, into: set[str]) -> None:+ if isinstance(value, str):+ into.add(value)+ url_password = _url_password(value)+ if url_password:+ into.add(url_password)+ elif isinstance(value, Mapping):+ for nested in value.values():+ _collect_string_leaves(nested, into)+ elif isinstance(value, list | tuple):+ for nested in value:+ _collect_string_leaves(nested, into)+++def _url_password(value: str) -> str | None:+ if "://" not in value:+ return None+ try:+ password = urlsplit(value).password+ except ValueError:+ return None+ return unquote(password) if password else None+++def _collect_secret_values(data: Any, sensitive: set[str], into: set[str]) -> None:+ if isinstance(data, Mapping):+ for key, value in data.items():+ if isinstance(key, str) and (key in sensitive or _SECRET_KEY_NAME_PATTERN.search(key)):+ _collect_string_leaves(value, into)+ else:+ _collect_secret_values(value, sensitive, into)+ elif isinstance(data, list | tuple):+ for nested in data:+ _collect_secret_values(nested, sensitive, into)+++def get_error_redaction_values(source: ExternalDataSource) -> frozenset[str]:+ """The stored secret values of a source, to mask wherever they appear in its error messages."""+ job_inputs = source.job_inputs+ if not isinstance(job_inputs, dict):+ return frozenset()+ try:+ source_config = SourceRegistry.get_source(ExternalDataSourceType(source.source_type)).get_source_config+ sensitive = get_sensitive_field_names(source_config.fields)+ except (ValueError, KeyError):+ sensitive = set()+ values: set[str] = set()+ _collect_secret_values(job_inputs, sensitive, values)+ return frozenset(value for value in values if len(value) >= _MIN_REDACTED_SECRET_LENGTH)+++def redact_error_message(message: str | None, secret_values: Iterable[str]) -> str | None:+ """Mask credentials in a sync error message before an API response returns it.++ Source errors often embed the failed request URL, a connection string or a raw driver message,+ so the source's own stored secrets and common credential patterns are both masked.+ """+ if not message:+ return message+ # Replace longer values first, so a secret that contains a shorter one is masked whole.+ for value in sorted(secret_values, key=len, reverse=True):+ message = message.replace(value, REDACTED_VALUE)+ for pattern, replacement in _ERROR_REDACTION_PATTERNS:+ message = pattern.sub(replacement, message)+ return message++# Fields whose change could redirect the database connection to a different server# (and therefore exfiltrate credentials via a poisoned SSH tunnel — VERIA-311)._SSH_TUNNEL_CONNECTION_FIELDS = ("enabled", "host", "port")diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.pyindex a2808648b2a2..4761f2b337ad 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py@@ -343,7 +343,16 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer)else:schema_with_error = instance.schemas.filter(latest_error__isnull=False).first()- return schema_with_error.latest_error if schema_with_error else None+ if schema_with_error is None:+ return None+ return helpers.redact_error_message(schema_with_error.latest_error, self._error_redaction_values(instance))++ def _error_redaction_values(self, instance: ExternalDataSource) -> frozenset[str]:+ cached = getattr(instance, "_error_redaction_values", None)+ if cached is None:+ cached = helpers.get_error_redaction_values(instance)+ instance._error_redaction_values = cached # type: ignore[attr-defined]+ return cached@extend_schema_field(serializers.ListField(child=serializers.DictField()))def get_schemas(self, instance: ExternalDataSource):@@ -355,9 +364,10 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer# The source list embeds every schema of every source; large projects have tens of thousands.# The list UI only reads a handful of per-schema fields, so serialize the trimmed shape there# and reserve the full serializer for single-source reads.+ context = {**self.context, "error_redaction_values": self._error_redaction_values(instance)}if self.context.get("schemas_list_only"):- return ExternalDataSchemaListSerializer(schemas, many=True, read_only=True, context=self.context).data- return ExternalDataSchemaSerializer(schemas, many=True, read_only=True, context=self.context).data+ return ExternalDataSchemaListSerializer(schemas, many=True, read_only=True, context=context).data+ return ExternalDataSchemaSerializer(schemas, many=True, read_only=True, context=context).datadef update(self, instance: ExternalDataSource, validated_data: Any) -> Any:request = self.context.get("request")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 c9743feeac5b..12aee82db667 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@@ -251,6 +251,43 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(result["status"], ExternalDataSchema.Status.FAILED)self.assertEqual(result["latest_error"], "boom")+ @parameterized.expand(+ [+ ("stored_secret", "Stripe rejected key sk_test_123 for this account", "sk_test_123"),+ (+ "url_query_param",+ "HTTP 503 for https://api.example.com/v1/items?api_key=abc123xyz&page=2",+ "abc123xyz",+ ),+ (+ "url_userinfo",+ "could not connect to postgres://admin:[email protected]:5432",+ "hunter2secret",+ ),+ ("bearer_header", "401 Unauthorized, sent Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.payload", "eyJhbGci"),+ ]+ )+ def test_latest_error_masks_credentials(self, _name, error, secret):+ source = self._make_source("redact")+ self._make_schema_with_table(+ source, "Customers", status=ExternalDataSchema.Status.FAILED, latest_error=error, should_sync=True+ )++ listed = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/").json()["results"][0]+ detail = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/").json()+ schemas = self.client.get(f"/api/environments/{self.team.pk}/external_data_schemas/").json()["results"]++ errors = [+ listed["latest_error"],+ listed["schemas"][0]["latest_error"],+ detail["latest_error"],+ detail["schemas"][0]["latest_error"],+ schemas[0]["latest_error"],+ ]+ for masked in errors:+ self.assertIn("***", masked)+ self.assertNotIn(secret, masked)+def test_list_query_count_does_not_scale_with_source_count(self):# Guards the prefetch design: adding sources (each with schemas + tables) must not add queries.# A regression to per-source credential/source lookups or the duplicate schema prefetch shows up