: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(mongodb): redact raw driver errors from source validation (#66259)
Tom Owersb5e9e0d3b509
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.pyindex a291bedc6479..96dbd7461d36 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py@@ -55,6 +55,19 @@ _MONGO_HOST_UNRESOLVED_MESSAGE = ("string is spelled correctly.")+_MONGO_AUTHENTICATION_FAILED_MESSAGE = (+ "MongoDB authentication failed. Please check the username and password for this source."+)++_MONGO_NOT_AUTHORIZED_MESSAGE = (+ "PostHog connected to MongoDB, but this user isn't authorized to list collections on the "+ "database. Grant the user a read role on the database (e.g. read or readAnyDatabase) and try again."+)++_MONGO_CONNECT_FAILED_MESSAGE = (+ "Could not connect to your MongoDB database. Check your connection string and credentials, then try again."+)+# Substrings pymongo embeds in ServerSelectionTimeoutError when the OS can't resolve the host._DNS_RESOLUTION_FAILURE_MARKERS = ("No address associated with hostname",@@ -71,7 +84,7 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixinreturn ExternalDataSourceType.MONGODBdef get_non_retryable_errors(self) -> dict[str, str | None]:- auth_failed_msg = "MongoDB authentication failed. Please check the username and password for this source."+ auth_failed_msg = _MONGO_AUTHENTICATION_FAILED_MESSAGEreturn {"The DNS query name does not exist": None,# pymongo raises InvalidURI("Username and password must be escaped according to RFC 3986,@@ -95,6 +108,13 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixin# 'authentication failed' here doesn't match the capitalised entries above (matching is# case-sensitive), so key off the stable Atlas-specific 'bad auth' prefix."bad auth": auth_failed_msg,+ # pymongo raises OperationFailure with codeName 'Unauthorized' (code 13) and errmsg+ # 'not authorized on <db> to execute command ...' when the user authenticates but lacks+ # a read role on the database. str(e) appends the full server response (clusterTime,+ # signature, BSON ids) via pymongo's _format_detailed_error, so the raw text must never+ # reach the user — match the stable 'not authorized' fragment. Granting permission is a+ # config change the user must make, so this never recovers on retry.+ "not authorized": _MONGO_NOT_AUTHORIZED_MESSAGE,"SSL handshake failed": None,# Atlas SQL / Data Federation endpoints live under *.query.mongodb.net and are served by# a query proxy the standard MongoDB driver can't drive: the handshake is closed, the@@ -191,8 +211,14 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixinif len(collection_names) == 0:return False, "No collections found in database"except OperationFailure as e:+ # pymongo's OperationFailure stringifies the full server response — clusterTime,+ # signature hashes, BSON ids — so str(e) must never be surfaced. Map the stable error+ # markers to a clean message; an authorization failure ("not authorized") means the+ # credentials are valid but lack read access, which is distinct from a bad password.capture_exception(e)- return False, f"MongoDB authentication failed: {str(e)}"+ if "not authorized" in str(e):+ return False, _MONGO_NOT_AUTHORIZED_MESSAGE+ return False, _MONGO_AUTHENTICATION_FAILED_MESSAGEexcept ServerSelectionTimeoutError as e:# pymongo dumps a verbose topology description into str(e); surface a concise,# actionable message instead. A DNS failure means the host doesn't resolve at all,@@ -204,7 +230,13 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixinreturn False, _MONGO_UNREACHABLE_MESSAGEexcept Exception as e:capture_exception(e)- return False, f"Failed to connect to MongoDB database: {str(e)}"+ # pymongo raises InvalidURI with the RFC-3986 hint before any network call when the+ # credentials contain unescaped reserved characters; surface the actionable message+ # rather than the raw driver string. Any other exception falls back to a generic message+ # so internal exception text never reaches the user.+ if "must be escaped according to RFC 3986" in str(e):+ return False, _MONGO_UNESCAPED_CREDENTIALS_MESSAGE+ return False, _MONGO_CONNECT_FAILED_MESSAGEreturn True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_database_name.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_database_name.pyindex 0e54c9280593..f041abb9f284 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_database_name.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_database_name.py@@ -1,6 +1,8 @@import pytestfrom unittest.mock import patch+from pymongo.errors import InvalidURI, OperationFailure+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MongoDBSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo import (DATABASE_NAME_REQUIRED_ERROR,@@ -8,7 +10,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mo)from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.source import (_DNS_RESOLUTION_FAILURE_MARKERS,+ _MONGO_AUTHENTICATION_FAILED_MESSAGE,+ _MONGO_CONNECT_FAILED_MESSAGE,_MONGO_HOST_UNRESOLVED_MESSAGE,+ _MONGO_NOT_AUTHORIZED_MESSAGE,+ _MONGO_UNESCAPED_CREDENTIALS_MESSAGE,_MONGO_UNREACHABLE_MESSAGE,MongoDBSource,)@@ -87,3 +93,57 @@ class TestMongoValidateCredentialsServerSelection:assert ok is Falseassert err == _MONGO_UNREACHABLE_MESSAGE+++class TestMongoValidateCredentialsOperationFailure:+ # All values here are synthetic — pymongo appends the full server response (clusterTime,+ # signature, BSON ids) to str(e), and that raw text must never reach the user. Each row+ # exercises a distinct branch: two inside `except OperationFailure`, two inside `except Exception`.+ @pytest.mark.parametrize(+ "exc, expected_message, forbidden",+ [+ (+ OperationFailure(+ "not authorized on demo_db to execute command { listCollections: 1 }",+ 13,+ {+ "ok": 0.0,+ "errmsg": "not authorized on demo_db to execute command { listCollections: 1 }",+ "code": 13,+ "codeName": "Unauthorized",+ "$clusterTime": {"clusterTime": "Timestamp(1, 1)", "signature": {"keyId": 1234567890}},+ },+ ),+ _MONGO_NOT_AUTHORIZED_MESSAGE,+ ("full error", "signature", "clusterTime", "keyId", "demo_db"),+ ),+ (+ OperationFailure(+ "Authentication failed.", 18, {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18}+ ),+ _MONGO_AUTHENTICATION_FAILED_MESSAGE,+ ("full error",),+ ),+ (+ InvalidURI("Username and password must be escaped according to RFC 3986, use urllib.parse.quote_plus"),+ _MONGO_UNESCAPED_CREDENTIALS_MESSAGE,+ (),+ ),+ (+ Exception("some-internal-driver-detail-xyz"),+ _MONGO_CONNECT_FAILED_MESSAGE,+ ("xyz",),+ ),+ ],+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.source.get_collection_names")+ def test_returns_clean_message_without_internals(self, mock_get_collections, exc, expected_message, forbidden):+ mock_get_collections.side_effect = exc+ config = MongoDBSourceConfig.from_dict({"connection_string": _SRV_WITH_DB})++ ok, err = MongoDBSource().validate_credentials(config, team_id=1)++ assert ok is False+ assert err == expected_message+ for leaked in forbidden:+ assert leaked not in (err or "")