Skip to content

fix(db): don't quote URIs in MongoDB errors - #703

Merged
uniqueg merged 2 commits into
devfrom
security/mongo-uri-errors
Nov 5, 2026
Merged

uniqueg merged 2 commits into
devfrom
security/mongo-uri-errors

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Closes #701

Decision

Replace the message of PyMongo's InvalidURI for malformed connection strings with a fixed one, raised with no cause or context; keep messages that only name options. Of the issue's options:

  • Replace for parsing errors only (chosen). It covers the leak whatever the broken form, and a fixed message can still tell operators what to check.
  • Redact the known password: rejected. In a broken URI, the password can't be told apart reliably; that is the very case at hand.
  • Only document: rejected. The fix is small, and the messages lost give little beyond what the fixed text says.

Tested against real messages of PyMongo 4.19.0, which changed the plan in three ways:

  • What leaks: Bad database name "..." (unescaped / in a password) and Percent-encoding is only allowed ...: <entity> (unescaped %). Port and IPv6 errors are ValueErrors with fixed text, so they stay, with their hint on escaping.
  • Catching InvalidURI alone isn't enough: PyMongo also raises it for conflicting keyword arguments, i.e., db.client_options (e.g., tlsInsecure with tlsAllowInvalidCertificates). 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.
  • A second source: urlsplit() in get_mongo_uri() quotes the whole netloc, with the password, for characters failing its NFKC check. The scheme check now uses startswith. MONGODB:// or leading whitespace now fail with FOCA's ValueError rather than PyMongo's InvalidURI; 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 the FileNotFoundError of tlsCAFile can then quote it. Left as is and documented in docs/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.py at 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.
  • Not run locally: tests needing MongoDB, integration tests, pre-commit as a whole.

CI: see the checks of this PR.

Declined review findings

  • Also replacing OSError of client creation: a wrong tlsCAFile path must stay readable; see the known limit.
  • Splitting the docs paragraph further and a release note: release notes are written at release time.

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:

  • Prevent malformed MongoDB connection-string errors from exposing credentials or other URI contents.
  • Preserve actionable PyMongo messages for errors that only identify invalid or conflicting options.

Enhancements:

  • Avoid URI parsing during scheme validation when it could quote credentials, while retaining existing validation for unsupported schemes and malformed host values.
  • Document credential escaping requirements and the remaining credential-exposure limitation caused by malformed query options.

Documentation:

  • Document how malformed MongoDB URI errors are sanitized and which option-related errors remain unchanged.

Tests:

  • Add coverage for sanitized malformed-URI errors, preserved option and host errors, exception-chain removal, and credential-safe scheme validation.

uniqueg and others added 2 commits November 5, 2026 07:28
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]>
@sourcery-ai

sourcery-ai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 errors

sequenceDiagram
    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
Loading

Flow diagram for MongoDB URI scheme validation

flowchart 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]
Loading

File-Level Changes

Change Details Files
Sanitize malformed MongoDB URI errors while preserving actionable option and host-validation diagnostics.
  • Catch PyMongo InvalidURI parsing failures and replace potentially credential-bearing messages with a fixed, unchained error.
  • Keep InvalidURI messages whose known prefixes identify only URI-option conflicts or invalid options.
  • Avoid urlsplit-based scheme validation that can quote credentials; enforce accepted schemes with startswith.
  • Document percent-escaping requirements and the remaining unescaped-question-mark limitation.
foca/database/register_mongodb.py
docs/configuration/db.md
Add regression coverage for credential non-disclosure and selective error preservation.
  • Verify sanitized messages omit secrets and traceback context for malformed URIs.
  • Cover preserved URI/client-option errors, non-URI option errors, port errors, and scheme handling.
  • Test credentials containing characters that previously appeared in parser errors or urlsplit failures.
tests/database/test_register_mongodb.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (5eb4f70) to head (6de0a2c).

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     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 5, 2026 06:44

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/database/register_mongodb.py Resolved
@uniqueg
uniqueg merged commit dd909c2 into dev Nov 5, 2026
83 checks passed
@uniqueg
uniqueg deleted the security/mongo-uri-errors branch November 5, 2026 06:57
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

security: PyMongo errors can quote URI parts

1 participant