Repository navigation
fix(db): don't quote URIs in MongoDB errors - #703
Conversation
Replace PyMongo's InvalidURI messages, which can quote part of a password, with a fixed message, without a chain. Keep those that only name options. Check the scheme without urlsplit(), whose errors quote the netloc. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep PyMongo's other messages about options. Raise the fixed message out of the handler, as the original would stay in __context__. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR prevents malformed MongoDB connection-string errors from exposing URI contents or credentials by replacing parsing-related InvalidURI messages with a fixed, context-free error, while retaining useful option and host-validation diagnostics; it also documents the escaping behavior and adds comprehensive regression tests. Sequence diagram for sanitized MongoDB URI errorssequenceDiagram
participant Caller
participant FOCA
participant PyMongo
Caller->>FOCA: create_mongo_client(host, port, db, options)
FOCA->>FOCA: get_mongo_uri(host, port, db)
FOCA->>PyMongo: MongoClient(uri, connect, options)
PyMongo-->>FOCA: InvalidURI
alt option-only InvalidURI
FOCA-->>Caller: re-raise original InvalidURI
else malformed URI
FOCA-->>Caller: raise fixed InvalidURI without cause
end
Flow diagram for MongoDB URI scheme validationflowchart TD
A[get_mongo_uri] --> B{uri starts with mongodb:// or mongodb+srv://?}
B -->|No| C[Raise ValueError]
B -->|Yes| D[Return URI for MongoClient]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #703 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 66 66
Lines 8588 8597 +9
=========================================
+ Hits 8588 8597 +9
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 1 issue
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/database/register_mongodb.py" line_range="192" />
<code_context>
+ **_get_client_options(uri=uri, options=options or {}, appname=appname),
+ )
+ except InvalidURI as exc:
+ if str(exc).startswith(_OPTION_ERRORS):
+ raise
+ malformed = True
</code_context>
<issue_to_address>
**Malformed URI exposes password fragment**
When a password contains an unescaped `?` and its remainder becomes a duplicated option name, pyMongo can raise an `InvalidURI` beginning with `URI option` that includes the duplicated option name; `create_mongo_client` re-raises it unchanged, so callers receive the password fragment.
Only preserve option errors when their echoed names are known fixed option identifiers, or replace messages that include URI-derived option names.
</issue_to_address>Linked issues
#701 security: PyMongo errors can quote URI parts · 2 of 2 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Decide how to handle potentially credential-leaking PyMongo errors and give reasons. | ✅ Met | The PR replaces malformed-URI messages with a fixed message, keeps errors that name only options, and explains why this approach was chosen over redaction or documentation alone. |
| 2 | If behavior changes, test malformed URIs containing credentials and useful wrong-option messages, and update the docs. | ✅ Met | Tests cover credential-bearing malformed URIs and preserved option errors; the database configuration docs explain escaping, sanitized errors, and the remaining unescaped-? limitation. |
Sourcery assessment
Approval pending. 1 finding to address first.
Blocking findings: foca/database/register_mongodb.py:192
Closes #701
Decision
Replace the message of PyMongo's
InvalidURIfor malformed connection strings with a fixed one, raised with no cause or context; keep messages that only name options. Of the issue's options:Tested against real messages of PyMongo 4.19.0, which changed the plan in three ways:
Bad database name "..."(unescaped/in a password) andPercent-encoding is only allowed ...: <entity>(unescaped%). Port and IPv6 errors areValueErrors with fixed text, so they stay, with their hint on escaping.InvalidURIalone isn't enough: PyMongo also raises it for conflicting keyword arguments, i.e.,db.client_options(e.g.,tlsInsecurewithtlsAllowInvalidCertificates). So messages starting with a known wording that names only options are kept (_OPTION_ERRORS), matching on the start, so that a quoted part can't qualify. Unknown wordings are replaced: a reworded message goes generic rather than leaking.urlsplit()inget_mongo_uri()quotes the whole netloc, with the password, for characters failing its NFKC check. The scheme check now usesstartswith.MONGODB://or leading whitespace now fail with FOCA'sValueErrorrather than PyMongo'sInvalidURI; they were rejected before too.Known limit
An unescaped
?in a password makes the rest parse as options. PyMongo's warnings (e.g.,<value> is not a valid read preference,Unknown option: <name>) and theFileNotFoundErroroftlsCAFilecan then quote it. Left as is and documented indocs/configuration/db.md: these same messages tell operators about wrong options, the password must contain such a form, and filtering warnings process-wide isn't thread-safe.Verification
Local, Python 3.12, PyMongo 4.19.0:
coverage run -m pytest -m 'not mongodb', without the integration test files: 4175 passed, 3 skipped;register_mongodb.pyat 100%. Total 99%, as the tests needing a MongoDB server didn't run locally; CI runs them.ruff check,ruff format --check,mypy,ast-grep scan,mkdocs build --strict: passed.CI: see the checks of this PR.
Declined review findings
OSErrorof client creation: a wrongtlsCAFilepath must stay readable; see the known limit.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Sanitize malformed MongoDB connection-string errors while preserving useful option diagnostics and documenting credential-escaping limitations.
Bug Fixes:
Enhancements:
Documentation:
Tests: