PYTHON-6058 Credential exposure in connection string parse-error messages
Description
Impact
When a connection string contains a password with an unescaped reserved character, PyMongo's URI parser can echo password-derived text verbatim in the exception message it raises. Applications that log connection failures will write that material to their logs, exposing credentials to anyone with log access.
The cause is the order of parsing. The URI is split on ? into a host/database part and an options part before the userinfo is separated from the host. A password containing an unescaped ? therefore has its tail reinterpreted as query-string options, and the option validators include the offending text in their error messages.
Details
Two message sites echo the shifted password material:
pymongo/common.py:370-raise ValueError(f"{value} is not a valid read preference")echoes the option value in full.- The unknown-option path in
split_optionsechoes the option key.
Reproducer
Verified against main at 4.19.0.dev0:
>>> from pymongo.uri_parser import parse_uri
>>> parse_uri("mongodb://user:pw?readpreference=hunter2SECRET@localhost/")
ValueError: hunter2SECRET@localhost/ is not a valid read preference
>>> parse_uri("mongodb://user:se?cret=hunter2@localhost/")
ConfigurationError: Unknown option: cret. Did you mean one of (connect, tlscrlfile, retryreads) ...The first case discloses the password tail verbatim. The second discloses a fragment of the password, lowercased, as the option key.
Patches
Fixed in PyMongo TBD
Workarounds
Percent-encode username and password before building a connection string, using urllib.parse.quote_plus, as the documentation already requires. Avoid logging exception messages raised by connection string parsing, or scrub them before logging.
References
- PYTHON-6058