Skip to content

feat(db): add MongoDB client options - #675

Merged
uniqueg merged 11 commits into
devfrom
feat/618-mongo-client-options
Nov 4, 2026
Merged

uniqueg merged 11 commits into
devfrom
feat/618-mongo-client-options

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

  • db.client_options, passed to MongoClient, with PyMongo's names; unknown or invalid ones stop the app on startup. host, port, connect, username and password are refused: they're set by FOCA or belong in MONGO_URI, MONGO_USERNAME and MONGO_PASSWORD.
  • Defaults: serverSelectionTimeoutMS and connectTimeoutMS of 5 seconds, instead of PyMongo's 30 and 20, and appname from the service info. Changed defaults are in docs/migration-0.21.md.
  • Options in MONGO_URI win, with a warning naming only the options. The issue says "as in PyMongo", which is wrong: in PyMongo, keyword arguments win (checked with a real client). FOCA enforces what the issue asks for, by leaving out what the connection string sets; names are parsed with PyMongo's own split_options().
  • Docs: docs/configuration/db.md, migration guide, templates/config.yaml.
  • fix: redact passwords with # in MongoDB URIs #674, found in review: _redact_uri() logged the start of a password containing #, as urlsplit() takes that for a fragment. Fixed here, as it's the same parsing in the same file.

Closes #618
Closes #674

Verification

  • ruff check, ruff format --check, mypy, ast-grep scan, mkdocs build --strict: pass.
  • pytest with coverage: 100 %. Locally, tests/factories/test_celery_worker_fork.py::test_no_client_opened_before_fork depends on which checkout the shared virtual environment has installed; see CI for the run on this branch.
  • Real clients for options and the precedence of the connection string (test_real_client, test_real_client_uri_wins).
  • Both reviewer subagents, two rounds.

Declined review findings

  • Reading the app's name lazily instead of on validation of Config: MongoConfig doesn't know the service info, and the client is created in places without the config. Noted in a comment.
  • The app's name for apps without a db section, whose fallback MongoConfig for access control gets foca: documented in docs/configuration/db.md.
  • Resolving aliases such as ssl and tls: documented; PyMongo refuses them with different values (test_aliases_not_resolved).
  • A comment on lowercase option names: the docstring covers it.

🤖 Generated with Claude Code

Summary by Sourcery

Support configurable MongoDB client behavior with safer defaults, deployment-level URI overrides, and clearer application identification.

New Features:

  • Add configurable MongoDB client options using PyMongo option names across application-created clients.
  • Name MongoDB clients in server logs using service metadata when available.

Bug Fixes:

  • Ensure MongoDB URI parsing and credential redaction handle passwords containing fragment characters correctly.

Enhancements:

  • Use five-second MongoDB server-selection and connection timeouts by default.
  • Give options specified in MONGO_URI precedence over application configuration and warn about conflicting configured options.
  • Reject reserved, duplicate, unknown, or invalid client options with appropriate validation errors.

Documentation:

  • Document MongoDB client options, precedence rules, reserved settings, defaults, and migration guidance.

Tests:

  • Add comprehensive coverage for client option validation, defaults, URI precedence, service-derived app names, real PyMongo behavior, and URI redaction.

uniqueg and others added 4 commits November 4, 2026 05:40
MongoClient was built with PyMongo's defaults, so with MongoDB down,
each request and the startup blocked for 30 seconds, and options could
only be set via MONGO_URI. Add db.client_options, passed to MongoClient,
with timeouts of 5 seconds and the service info's identifier as appname
by default. Options in MONGO_URI win, with a warning on conflicts; FOCA
has to enforce this, as keyword arguments win in PyMongo.

Closes #618

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Parse options as PyMongo does (`;` as separator, `#` not special), so
that options of the URI win in each form. Refuse username and password
in client_options, which would override the URI. Skip app names that
PyMongo would refuse.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Parse URI options with PyMongo's own function, which also splits on
whitespace. Cut URIs for logs as PyMongo does, so that a # in a
password no longer leaks its start.

Closes #674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 05:22
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR adds validated, configurable MongoDB client options across configuration and client creation, with shorter FOCA defaults, service-derived application names, and explicit deployment URI precedence. It also documents the behavior, updates mocks and comprehensive tests, and fixes credential redaction for passwords containing #.

Sequence diagram for MongoDB client option resolution

sequenceDiagram
    participant Config
    participant Factory as create_mongo_client
    participant PyMongo as MongoClient
    participant URI as MONGO_URI

    Config->>Config: _check_client_options()
    Config->>Factory: get_mongo_client()
    Factory->>Factory: _get_client_options()
    Factory->>URI: split_options()
    alt URI option overrides configured option
        Factory-->>Factory: logger.warning()
        Factory-->>PyMongo: omit option from keyword arguments
    else option is not set in URI
        Factory-->>PyMongo: pass defaults, appname, and client options
    end
    Factory->>PyMongo: MongoClient(uri, connect, options)
Loading

File-Level Changes

Change Details Files
Add validated MongoDB client option handling with FOCA defaults and deployment-level URI precedence.
  • Expose scalar PyMongo-named options through MongoConfig.client_options.
  • Reject reserved options managed by FOCA or environment variables, while deferring unknown and value validation to PyMongo during client creation.
  • Apply 5-second timeout defaults and derive appname from service metadata with a safe fallback.
  • Parse URI option names using PyMongo, omit URI-overridden options, and warn without logging configured values.
  • Pass options through shared and reopened clients, and extend the standalone client factory with options and appname.
foca/models/config.py
foca/database/register_mongodb.py
Document the new MongoDB client configuration, precedence behavior, defaults, and migration impact.
  • Describe supported option names, restrictions, URI precedence, aliases, and app naming.
  • Add changed timeout and appname defaults to the migration guide.
  • Add client_options to the configuration template.
docs/configuration/db.md
docs/migration-0.21.md
templates/config.yaml
Expand test coverage for option validation, effective client settings, URI precedence, metadata, and redaction.
  • Verify defaults, configured values, reserved and invalid options, aliases, and client reopening.
  • Exercise real PyMongo clients and URI-overrides, including warning redaction.
  • Fix test MongoClient mocks to accept new keyword arguments.
  • Cover URI redaction when credentials contain #.
tests/database/test_register_mongodb.py
tests/conftest.py
tests/security/access_control/test_register_casbin_enforcer.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 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (a1c04d0) to head (320bede).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #675   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           58        58           
  Lines         7499      7538   +39     
=========================================
+ Hits          7499      7538   +39     
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.

@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 5 issues

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="153" />
<code_context>
+    client: MongoClient[dict[str, Any]] = MongoClient(
+        uri,
+        connect=connect,
+        **_get_client_options(uri=uri, options=options or {}, appname=appname),
+    )
     logger.info("Created MongoDB client for '%s'.", _redact_uri(uri))
</code_context>
<issue_to_address>
**URI credentials get overridden**

When a direct caller supplies `username` or `password` in `options` and the URI also contains credentials, `_get_client_options` forwards those options to PyMongo, which gives them precedence over the URI credentials; the client authenticates as a different user and bypasses the documented credential configuration path.

Reject `username` and `password` options when the URI supplies credentials.

Also at `foca/database/register_mongodb.py:205-206`.
</issue_to_address>

### Comment 2
<location path="foca/database/register_mongodb.py" line_range="108" />
<code_context>
             port=conf.port,
             db=next(iter(conf.dbs or {}), None),
             connect=connect,
+            options=conf.client_options,
+            appname=conf._default_appname,
         )
</code_context>
<issue_to_address>
**Invalid options pass startup unchecked**

When `db.client_options` contains an option PyMongo rejects and no configured database or other startup path creates a client, `register_mongodb()` creates a client only while iterating configured databases, so PyMongo never validates those options during startup; the app starts with the invalid setting and the error surfaces when a client is later created.

Validate `client_options` during startup even when no database causes a client to be created.

Also at `foca/models/config.py:2323`.
</issue_to_address>

### Comment 3
<location path="foca/database/register_mongodb.py" line_range="120" />
<code_context>
     db: str | None = None,
     connect: bool = True,
+    options: Mapping[str, Any] | None = None,
+    appname: str | None = None,
 ) -> MongoClient[dict[str, Any]]:
     """Create MongoDB client.
</code_context>
<issue_to_address>
**Standalone clients lack an app name**

When `create_mongo_client()` is called without an explicit `appname`, an `appname` option, or one in the URI, `create_mongo_client()` passes `appname=None` to `_get_client_options()`, which omits the option; MongoDB logs therefore lack the FOCA application name for these clients.

Give standalone clients a default FOCA application name when no app name is supplied.

Also at `foca/database/register_mongodb.py:203-205`, `docs/configuration/db.md:87`.
</issue_to_address>

### Comment 4
<location path="foca/models/config.py" line_range="2750" />
<code_context>
+                and name
+                and len(name.encode()) <= MAX_MONGO_APPNAME_BYTES
+            ):
+                self.db._default_appname = name
+        return self
</code_context>
<issue_to_address>
**Shared configs use the wrong app name**

When the same `MongoConfig` instance is reused by `Config` instances with different service names before a client is created, `Config._set_mongo_appname()` writes `_default_appname` to the shared `MongoConfig`, so the later validation overwrites the earlier app's name and its client is attributed to the wrong app in MongoDB logs.

Store the derived app name per `Config` instead of mutating the shared `MongoConfig`.
</issue_to_address>

### Comment 5
<location path="foca/database/register_mongodb.py" line_range="206" />
<code_context>
+    if appname is not None:
+        merged["appname"] = appname
+    merged.update({name.lower(): value for name, value in options.items()})
+    return {name: value for name, value in merged.items() if name not in in_uri}
+
+
</code_context>
<issue_to_address>
**Duplicate option values are discarded**

When `client_options` contains the same option under two names differing only by case, `_get_client_options` lowercases option names into a dict, so differently cased keys for the same option overwrite one another in mapping order without an error. The caller silently loses one configured value.

Reject duplicate option names after case normalization instead of silently selecting one value.
</issue_to_address>

Linked issues

#618 feat(db): add MongoDB client options · 8 of 9 met · 1 to check by hand

# Requirement Status Notes
1 Add db.client_options as a mapping of PyMongo option names to scalar values; refuse options managed by FOCA or intended for environment variables. ✅ Met MongoConfig defines and validates client_options, and get_mongo_client passes it to MongoClient.
2 Default serverSelectionTimeoutMS and connectTimeoutMS to 5000. ✅ Met Both defaults are applied unless overridden by client_options or MONGO_URI.
3 Default appname to the service info id, or the package name. ✅ Met Config sets the default from the service id or package; names PyMongo would reject are skipped.
4 Let MONGO_URI options win and log a warning on conflict. ✅ Met URI option names are parsed with PyMongo's split_options(); matching configured options are omitted and their names are logged.
5 Fail at MongoClient creation for unknown options. ✅ Met Options are passed to PyMongo, which rejects unknown options; the tests cover this behavior.
6 Cover the model field, defaults, and pass-through in tests, with 100% coverage. ✅ Met Tests cover the field validation, defaults, pass-through, and invalid or unknown options; the PR reports 100% test coverage.
7 Document the field, defaults, and URI precedence on the database configuration page. ✅ Met The database configuration documentation describes these options and their precedence.
8 Mention the changed default timeout in release notes or the migration guide. ✅ Met docs/migration-0.21.md describes the timeout change.
9 Land the changed default by 1.0.0-rc1. 👀 Check by hand (external system) Check whether this change lands by the 1.0.0-rc1 release.

#674 fix: redact passwords with # in MongoDB URIs · 2 of 2 met

# Requirement Status Notes
1 Redact credentials and options by cutting at the first ? and removing everything through the last @. ✅ Met _redact_uri applies that parsing and preserves the scheme, host, and path.
2 Add a regression test for a password containing #, preserving hosts and paths in the redacted form. ✅ Met The regression test checks a # in the password and verifies the redacted host and path.

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and the new client_options can change MongoDB security behavior, including TLS certificate verification, while the 5-second defaults can make requests or startup fail during slow connections or failovers. Reverting restores the prior client settings, but any data exposure or service outage that already occurred cannot be undone.

Blocking findings: foca/database/register_mongodb.py:153, foca/database/register_mongodb.py:108, foca/database/register_mongodb.py:120, foca/models/config.py:2750, foca/database/register_mongodb.py:206


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

Comment thread foca/database/register_mongodb.py Resolved
Comment thread foca/database/register_mongodb.py Resolved
Comment thread foca/database/register_mongodb.py Resolved
Comment thread foca/models/config.py Resolved
Comment thread foca/database/register_mongodb.py Resolved

@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.

Linked issues

#618 feat(db): add MongoDB client options · 6 of 9 met · 2 to check by hand

# Requirement Status Notes
1 Add db.client_options as a mapping of scalar values using PyMongo option names. ✅ Met The MongoConfig field is passed to MongoClient by get_mongo_client.
2 Default serverSelectionTimeoutMS and connectTimeoutMS to 5000 unless configured otherwise. ✅ Met Both defaults are applied to clients, and configured options override them.
3 Default appname to the service-info identifier or package name. 🟡 Partly met This is done when Config has a db section, but clients created from the fallback MongoConfig used when it does not retain the generic foca name.
4 Let MONGO_URI options take precedence and warn on conflicts. ✅ Met URI option names are parsed with PyMongo's parser; warnings list conflicting configured names without values.
5 Fail at MongoClient creation for unknown options. ✅ Met Options are passed to MongoClient, which validates them; tests cover an unknown option.
6 Cover the model field, defaults and pass-through with tests at 100% coverage. 👀 Check by hand (runtime) The diff adds tests for the field, defaults and pass-through; confirm the reported 100% coverage in the test run.
7 Document the field, defaults and URI precedence on the database configuration page. ✅ Met The configuration page describes the field, defaults, and URI precedence.
8 Mention the changed default timeout in the release notes or migration guide. ✅ Met The 0.21 migration guide documents both shorter timeouts.
9 Land the changed default by 1.0.0-rc1. 👀 Check by hand (manual process) Confirm that this change is included by the 1.0.0-rc1 release.

#674 fix: redact passwords with # in MongoDB URIs · 2 of 2 met

# Requirement Status Notes
1 Redact credentials and options by cutting the URI at the first ? and removing everything before the last @. ✅ Met The updated redaction logic follows those delimiters without treating # as a fragment.
2 Add a regression test for a # in the password and verify hosts and path remain in the redacted URI. ✅ Met The test includes a # in the password and checks the host and path in the expected redacted URI.

Comment thread foca/models/config.py Resolved

@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.

Linked issues

#618 feat(db): add MongoDB client options · 7 of 9 met · 1 to check by hand

# Requirement Status Notes
1 Add a scalar-valued db.client_options mapping using PyMongo option names, and reject reserved or duplicate names. ✅ Met MongoConfig defines and validates the field; its options are passed through get_mongo_client().
2 Default serverSelectionTimeoutMS and connectTimeoutMS to 5000 unless overridden. ✅ Met The defaults are applied in _get_client_options() and are covered by tests.
3 Default appname to the service-info ID or package name. 🟡 Partly met The service-info ID or package name is used when Config.db exists, but the access-control fallback MongoConfig() retains foca even when that app has service info.
4 Let MONGO_URI options win and warn on conflicts. ✅ Met URI option names are parsed with PyMongo's parser; conflicts with configured options are warned about without logging their values.
5 Fail at client creation for unknown or invalid options. ✅ Met Options are passed to MongoClient, with tests covering unknown options and invalid types or values.
6 Cover the model field, defaults, and pass-through with tests (100% coverage). ✅ Met The new tests cover model validation, defaults, configured values, and real PyMongo client behavior.
7 Document the field, defaults, and URI precedence on the database configuration page. ✅ Met docs/configuration/db.md documents the options, defaults, restrictions, and precedence.
8 Mention the changed timeout default in the release notes or migration guide. ✅ Met docs/migration-0.21.md describes the five-second timeouts and how to override them.
9 Land the changed default by 1.0.0-rc1. 👀 Check by hand (manual process) Check that this change is included no later than the 1.0.0-rc1 release.

#674 fix: redact passwords with # in MongoDB URIs · 2 of 2 met

# Requirement Status Notes
1 Redact credentials by cutting at the first ? and retaining everything after the last @. ✅ Met _redact_uri() uses that parsing, so # in a password is not treated as a fragment.
2 Add a regression test for a password containing #, preserving hosts and path in the redacted URI. ✅ Met The test covers a # in the password and checks that the hosts and path remain.

Comment thread foca/models/config.py Resolved
uniqueg and others added 3 commits November 4, 2026 07:55
Apps with access control but no `db` section got the default name in
MongoDB's logs, not the one from their service info.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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.

Linked issues

#618 feat(db): add MongoDB client options · 5 of 7 met · 1 to check by hand

# Requirement Status Notes
1 Add db.client_options using PyMongo option names, pass options to MongoClient, and fail fast on unknown options. ✅ Met The config field is passed through the MongoDB client creation path, and tests cover invalid and unknown options.
2 Default the timeouts to 5000 ms and appname to the service ID or package name. ✅ Met The defaults and service-info naming are implemented, with tests for the timeout defaults and service ID/package cases.
3 Let options in MONGO_URI win and warn on conflicts. 🟡 Partly met Same-name options in the URI take precedence and conflicts are warned about, but aliases such as URI ssl and configured tls are not treated as the same option and can raise a conflict instead.
4 Cover the model field, defaults, and pass-through with tests at 100% coverage. ✅ Met The diff adds tests for the field, defaults, validation, pass-through, and real PyMongo behavior; the PR description reports 100% coverage.
5 Document the field, defaults, and URI precedence on the database configuration page. ✅ Met The database configuration page documents these, including the precedence behavior and its alias limitation.
6 Mention the changed timeout default in the release notes or migration guide. ✅ Met The migration guide describes the shorter MongoDB timeouts.
7 Land the changed default by 1.0.0-rc1. 👀 Check by hand (external system) Check the release schedule or target branch to confirm this change lands by 1.0.0-rc1.

#674 fix: redact passwords with # in MongoDB URIs · 2 of 2 met

# Requirement Status Notes
1 Redact the URI by cutting at the first ? and keeping everything after the last @. ✅ Met The redaction helper uses that parsing approach, avoiding urlsplit() treating # in a password as a fragment.
2 Add a regression test for # in a password and verify the hosts and path remain in the redacted URI. ✅ Met The regression test includes # in the password and asserts the redacted hosts and path.

Comment thread foca/database/register_mongodb.py Resolved
…options

# Conflicts:
#	docs/migration-0.21.md
@uniqueg
uniqueg merged commit 0d01ccc into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/618-mongo-client-options branch November 4, 2026 07:20
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.

fix: redact passwords with # in MongoDB URIs feat(db): add MongoDB client options

1 participant