Skip to content

feat(db): support MONGO_URI connection strings - #270

Merged
uniqueg merged 24 commits into
devfrom
feat/mongo-uri
Oct 18, 2026
Merged

uniqueg merged 24 commits into
devfrom
feat/mongo-uri

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

Summary

Third phase-2 PR of the v0.14.0 maintenance series. Builds on #267 (and #266, #265); the new commits are feat(db): support MONGO_URI connection strings and fix(db): keep auth source, redact URI options. Independent of #268 and #269.

Supersedes #254, #256 and #257, which each implemented MONGO_URI but made every configured database (including the access control database) collapse into the single database named in the URI. Thanks @anuragxxd and @minhpham1810 for the groundwork.

MONGO_URI

New foca.database.register_mongodb.get_mongo_uri() builds the connection string for one database:

  • if environment variable MONGO_URI is set, it is used as is (mongodb:// or mongodb+srv://; replica sets, TLS, read preferences etc. via options), but with the database set to the database being registered, so each database in db.dbs (and the access control database) keeps its own name
  • the authentication database is preserved unless authSource is set explicitly: a database in the URI path becomes authSource (so mongodb://user:pw@host/admin keeps authenticating against admin), and URIs with credentials but no database get authSource=admin, the MongoDB default
  • options separated by ; instead of & are supported
  • an invalid scheme raises a ValueError naming MONGO_URI
  • without MONGO_URI, behaviour is as before (MONGO_HOST, MONGO_PORT, MONGO_USERNAME, MONGO_PASSWORD, config values), except that credentials are now percent-escaped (passwords containing @, : or / previously produced invalid URIs)
  • MONGO_DBNAME keeps overriding database names in both modes

Casbin adapter (existing bug)

The access control adapter connected to mongodb://{db.host}:{db.port}/, ignoring all environment variables, credentials included, so access control could not work against an authenticated or relocated MongoDB. It now uses get_mongo_uri() as well, and selects its database with the MONGO_DBNAME override applied (new get_mongo_db_name()), like all other database clients.

Thanks Copilot for the review findings on auth source, separators, logging and MONGO_DBNAME.

Other

  • connection strings are logged without credentials and options (options may contain secrets such as tlsCertificateKeyFilePassword)
  • README documents the environment variables
  • _create_mongo_client() keeps its signature (used by proTES)

Closes #253

Noted for the code audit (not changed here)

With MONGO_USERNAME set but MONGO_PASSWORD unset, the literal string None is used as password, as before (PyMongo refuses to create a client with a username but no password). Failing early with a clear error would be better, but changes behaviour for such deployments.

Verification

Test-first: new TestGetMongoUri tests (defaults, env overrides, escaped credentials, MONGO_URI with replica set/options, without path, with and without credentials, SRV, auth DB, explicit authSource, ; separators, MONGO_DBNAME, invalid scheme), a log redaction test, and Casbin adapter tests (MONGO_URI, individual variables, MONGO_DBNAME); the adapter and review-finding tests failed before the respective fixes. PyMongo's parse_uri() accepts the generated connection strings.

Locally (Python 3.13): unit tests without MongoDB: 266 passed; ruff check, ruff format --check, mypy foca clean.

CI: all checks pass (run): ruff, mypy, build, unit tests incl. MongoDB-dependent tests on Python 3.10–3.14, petstore integration tests, Read the Docs.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Support full MongoDB connection strings while consistently applying database overrides, authentication settings, and secure logging across database clients.

New Features:

  • Add support for configuring MongoDB connections with full MONGO_URI connection strings while preserving per-database selection and authentication settings.
  • Apply shared MongoDB connection configuration to the Casbin access-control adapter.
  • Document MongoDB connection environment variables in the README.

Bug Fixes:

  • Ensure authenticated and relocated MongoDB deployments work with the access-control adapter.
  • Prevent MongoDB credentials and sensitive URI options from appearing in connection logs.
  • Properly escape credentials when constructing MongoDB URIs from individual environment variables.

Enhancements:

  • Centralize MongoDB database-name and connection-URI resolution across database clients.
  • Validate MongoDB URI schemes and support both ampersand- and semicolon-separated URI options.

Documentation:

  • Document supported MongoDB connection environment variables and their precedence.

Tests:

  • Add coverage for URI generation, credential escaping, authentication databases, database overrides, URI validation, log redaction, and Casbin adapter configuration.

uniqueg and others added 18 commits October 17, 2026 18:05
Replace setup.py and the requirements*.txt files with PEP 621 metadata
in pyproject.toml (setuptools backend). Distribution name, import
package and the `dev` and `docs` extras are unchanged.

- declare `requires-python = ">=3.10"` (3.9 is end of life)
- ship `py.typed` inside the package so the "Typed" classifier holds
- package only `foca*`, so `tests` is no longer installed into
  site-packages; configure pytest `pythonpath` so tests still import
- declare `typing_extensions` as a runtime dependency (it is imported
  by `foca.models.config`)
- drop the obsolete `typing` backport and the unused `toml`,
  `mypy-extensions`, `types-urllib3`, `types-setuptools`, `pylint`,
  `python-semantic-release` and `readthedocs-sphinx-ext`
- drop `setup_requires` and the setuptools-git based MANIFEST.in
- remove the stale semantic-release config from setup.cfg; move the
  mypy config to pyproject.toml (flake8 config stays in setup.cfg until
  ruff replaces it)
- install FOCA directly from the source tree in the Docker image

Closes #232

Co-Authored-By: Claude Opus 5.5 <[email protected]>
FOCA now requires Python >= 3.10.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Update runtime, dev and docs dependencies while staying on Connexion 2.
Ranges now allow minor/patch updates within the current major version.

- connexion >=2.15.1,<3: makes explicit what was already resolved
  (2.15 is the only 2.x line compatible with Werkzeug 3)
- Flask >=3.1.3,<4 (fixes CVE-2026-27205); Flask-PyMongo 3.x
- cryptography >=50 (fixes six advisories in 44.x)
- flask-authz <2.8 (2.8+ hard-pins a vulnerable Flask)
- swagger-ui-bundle >=1.1 (Swagger UI 4; required by connexion 2.15)
- raise floors of celery, Flask-Cors, PyJWT, requests and dev/docs
  tools (Sphinx >=8, sphinx-rtd-theme >=3)

pip-audit reports no known vulnerabilities for the updated set.

BREAKING CHANGE: FOCA now requires Flask 3. Apps using APIs removed in
Flask 3 (e.g. `flask.Markup`, `_app_ctx_stack`, custom JSON encoders)
need to be updated.

Closes #216

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Docker: default to python:3.13-slim-trixie (Debian 13), use
  trixie-based images in CI, fix Dockerfile lint (`AS`, `ENV K=V`)
- examples: MongoDB 8.0, Python 3.13 images, drop obsolete compose
  `version` key
- Read the Docs: Ubuntu 24.04 and Python 3.13; install only the
  `docs` extra

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- update actions (Node 24 versions) and pin them by commit SHA
- split into lint/build, unit test, integration test and image jobs
- test Python 3.10-3.14 against MongoDB 8.0 (plus 3.13 on 7.0)
  instead of 16 jobs with EOL MongoDB versions; upload coverage and
  run the petstore integration tests once
- check that sdist and wheel build and pass `twine check`
- wait for the petstore app instead of sleeping; show logs on failure
- push Docker images only for pushes to `dev`, add Python 3.13/3.14
  images and move `latest` to 3.13; skip image builds on PRs (the
  integration job already builds one)
- restrict token permissions, cancel superseded PR runs, set job
  timeouts, cache pip downloads
- replace the blanket `-W ignore::DeprecationWarning` with targeted
  pytest filters for connexion's use of deprecated jsonschema APIs
- add Python 3.13 and 3.14 classifiers

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build sdist and wheel when a GitHub release is published, check that
the release tag matches the package version, and upload to PyPI via
trusted publishing from the `pypi` environment (no API token).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Weekly grouped updates for Python dependencies, GitHub Actions and the
Docker base image, targeting `dev`. Connexion major updates are ignored
until the Connexion 3 migration (#188).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Configure ruff for linting and formatting (line length 79, as used by
the existing code) with pycodestyle, Pyflakes, isort, pyupgrade,
pydocstyle (Google convention), Pylint, bugbear, simplify,
comprehensions and Ruff-specific rules. Complexity limits are left
disabled for now. Tests are exempt from docstring and magic-value
rules.

Run `ruff check` and `ruff format --check` in CI instead of flake8, and
add a pre-commit config with ruff and basic file hygiene hooks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Automatic, behaviour-preserving fixes by `ruff check --fix`: PEP 585
and PEP 604 annotations (closes #231), sorted imports, docstring
whitespace, f-strings, and simplified conditionals and with-blocks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
One-off reformat of all Python files with `ruff format` (Black style,
line length 79). No functional changes; one `type: ignore` comment was
moved back to the line it applies to.

Closes #237

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Docstrings (closes #239):
- add package, class and method docstrings where missing
- shorten multi-line summaries to one line (Google convention)

Linting (closes #238):
- chain exceptions raised in `except` blocks (`raise ... from exc`)
- replace mutable argument default in `_validate_jwt_public_key()`
- replace attribute probe with `hasattr()` and try/except/pass with
  `contextlib.suppress()` in exception config validation
- merge nested `with` statements in tests; minor simplifications

Disable magic-value comparisons (PLR2004), which only flag HTTP status
codes and Casbin rule lengths, and docstring rules for docs and
examples.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	.github/workflows/checks.yml
#	pyproject.toml
Exclude the deliberately malformed YAML fixture from `check-yaml` and
keep Markdown hard line breaks in `trailing-whitespace`, so that
`pre-commit run --all-files` passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
One-off fixes by the `end-of-file-fixer` and `trailing-whitespace`
pre-commit hooks. No content changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add `get_mongo_uri()` to build MongoDB connection strings, and use it
for both the app databases and the Casbin adapter:

- if environment variable `MONGO_URI` is set, use it as connection
  string (`mongodb://` or `mongodb+srv://`, e.g., for replica sets, TLS
  or other options), with the database set to the database being
  registered, so that each configured database keeps its own name; a
  database in the URI path is kept as `authSource` unless set
- otherwise build the connection string from `MONGO_HOST`,
  `MONGO_PORT`, `MONGO_USERNAME`, `MONGO_PASSWORD` and the config, as
  before, but percent-escape credentials
- `MONGO_DBNAME` keeps overriding database names in both cases

Previously, the Casbin adapter connected to `mongodb://host:port/`
from the config, ignoring all environment variables, including
credentials. Connection strings are logged without credentials.

Closes #253

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 17, 2026 16:55
@sourcery-ai

sourcery-ai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR centralizes MongoDB connection-string handling so every configured and access-control database honors MONGO_URI and legacy environment variables without collapsing database names, preserves authentication semantics, escapes and redacts sensitive URI data, and adds comprehensive tests and documentation. It also includes a broad tooling/runtime modernization with reworked CI, release automation, dependency updates, and repository-wide Ruff formatting/type cleanup.

Sequence diagram for MongoDB database registration with MONGO_URI

sequenceDiagram
    participant Foca
    participant RegisterMongoDB
    participant URIBuilder as get_mongo_uri
    participant PyMongo
    participant MongoDB

    Foca->>RegisterMongoDB: register_mongodb
    RegisterMongoDB->>URIBuilder: get_mongo_uri(host, port, db)
    alt MONGO_URI is set
        URIBuilder->>URIBuilder: _set_uri_database(uri, db)
        URIBuilder-->>RegisterMongoDB: URI with target database and authSource
    else MONGO_URI is unset
        URIBuilder->>URIBuilder: quote_plus credentials
        URIBuilder-->>RegisterMongoDB: URI from legacy environment variables
    end
    RegisterMongoDB->>PyMongo: _create_mongo_client(uri)
    PyMongo->>MongoDB: Connect to registered database
    RegisterMongoDB->>RegisterMongoDB: _redact_uri(uri)
    RegisterMongoDB-->>Foca: Database client
Loading

Flow diagram for MongoDB URI selection and protection

flowchart TD
    Start["Register database"] --> Override[get_mongo_db_name]
    Override --> HasURI{"MONGO_URI set?"}
    HasURI -->|Yes| Validate["Validate mongodb or mongodb+srv scheme"]
    Validate --> SetDB["_set_uri_database: set target database"]
    SetDB --> Auth["Preserve or derive authSource"]
    HasURI -->|No| Legacy["Build URI from host, port and credentials"]
    Legacy --> Escape["Percent-escape credentials"]
    Auth --> Client["Create MongoDB client"]
    Escape --> Client
    Client --> Redact["_redact_uri for logging"]
Loading

File-Level Changes

Change Details Files
Add centralized MongoDB URI construction with per-database selection, authentication-source preservation, environment-variable precedence, credential escaping, validation, and safe logging.
  • Introduces get_mongo_uri() and get_mongo_db_name() for legacy variables and MONGO_URI.
  • Rewrites URI paths while retaining explicit or inferred authSource, including semicolon-separated options and SRV URIs.
  • Escapes legacy credentials and redacts credentials/options from registration logs.
  • Adds focused URI, parsing, redaction, and precedence coverage.
foca/database/register_mongodb.py
tests/database/test_register_mongodb.py
README.md
Route Casbin access-control persistence through the same MongoDB configuration as application databases.
  • Builds the Casbin adapter URI with get_mongo_uri().
  • Applies MONGO_DBNAME consistently to the adapter database name.
  • Adds adapter registration tests for full URIs, individual variables, and database overrides.
foca/security/access_control/register_access_control.py
tests/security/access_control/test_register_casbin_enforcer.py
Modernize project tooling, dependency constraints, runtime support, and CI/release automation.
  • Updates dependencies and type annotations for Python 3.10–3.14, adds Ruff/pre-commit configuration, and removes legacy setup configuration.
  • Restructures CI into lint/build, MongoDB unit-test, integration, and gated Docker publishing jobs.
  • Adds Dependabot, trusted PyPI release publishing, newer Python/MongoDB/Docker bases, and documentation formatting updates.
.github/dependabot.yml
.github/workflows/checks.yml
.github/workflows/release.yml
.pre-commit-config.yaml
.readthedocs.yaml
docker/Dockerfile
examples/petstore/docker-compose.yaml
examples/petstore-access-control/docker-compose.yaml
pyproject.toml
setup.cfg
Apply broad Ruff-driven formatting, typing, documentation, and import modernization across the package and tests.
  • Replaces legacy typing forms and normalizes formatting/import order throughout application, security, configuration, utility, example, and test modules.
  • Adds package docstrings and small documentation/error-chain cleanups without changing the primary feature behavior.
foca/**/*.py
tests/**/*.py
examples/**/*.py
docs/api/conf.py
PULL_REQUEST_TEMPLATE.md

Assessment against linked issues

Issue Objective Addressed Explanation
#253 Support a full MongoDB connection string through the MONGO_URI environment variable, taking precedence over individual MongoDB environment variables while preserving the existing component-variable configuration as a backwards-compatible fallback. ✅

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 Oct 17, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #270   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines         1130      1151   +21     
=========================================
+ Hits          1130      1151   +21     
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.

Copilot AI 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.

🟡 Changes recommended

MongoDB authentication handling, adapter database selection, and secret-bearing connection logs need correction.

4 open issues
What changed in this PR

Adds per-database MONGO_URI support to FOCA, alongside inherited maintenance changes from #265–#267.

Changes:

  • Centralizes MongoDB URI construction and reuses it for Casbin connections.
  • Adds connection configuration documentation and tests.
  • Updates dependencies, automation, formatting, and Python typing.
File Description
tests/​utils/​test_misc.py Cleans test formatting.
tests/​utils/​test_logging.py Formats logging tests.
tests/​utils/​test_db.py Formats database tests.
tests/​test_foca.py Formats imports and paths.
tests/​test_files/​openapi_3_petstore.original.yaml Removes trailing whitespace.
tests/​test_files/​openapi_3_petstore_pathitemparam.original.yaml Removes trailing whitespace.
tests/​test_files/​models_petstore.py Modernizes model annotations.
tests/​test_files/​model_valid.py Formats fixture model.
tests/​test_files/​invalid_conf.yaml Adds final newline.
tests/​test_files/​empty_conf.yaml Adds final newline.
tests/​test_files/​conf_valid_cors_enabled.yaml Adds final newline.
tests/​test_files/​conf_valid_cors_disabled.yaml Adds final newline.
tests/​test_files/​conf_valid_access_control.yaml Adds final newline.
tests/​test_files/​conf_jobs.yaml Adds final newline.
tests/​test_files/​conf_invalid_jobs.yaml Adds final newline.
tests/​test_files/​conf_invalid_access_control.yaml Adds final newline.
tests/​test_files/​conf_api.yaml Adds final newline.
tests/​security/​test_cors.py Formats CORS test.
tests/​security/​test_auth.py Formats authentication tests.
tests/​security/​access_control/​test_register_casbin_enforcer.py Adds adapter connection tests.
tests/​security/​access_control/​test_register_access_control.py Formats permission tests.
tests/​security/​access_control/​test_enforcement.py Modernizes test typing and formatting.
tests/​security/​access_control/​test_access_control_server.py Formats endpoint tests.
tests/​security/​access_control/​foca_casbin_adapter/​test_files/​rbac_with_resources_roles.conf Adds final newline.
tests/​security/​access_control/​foca_casbin_adapter/​test_files/​rbac_model.conf Adds final newline.
tests/​security/​access_control/​foca_casbin_adapter/​test_casbin_rule.py Formats rule tests.
tests/​security/​access_control/​foca_casbin_adapter/​test_adapter.py Modernizes adapter test annotations.
tests/​models/​test_config.py Formats configuration tests.
tests/​mock_data.py Formats shared fixtures.
tests/​factories/​test_connexion_app.py Formats application factory tests.
tests/​factories/​test_celery_app.py Formats imports.
tests/​errors/​test_errors.py Formats exception tests.
tests/​database/​test_register_mongodb.py Adds URI construction tests.
tests/​config/​test_config_parser.py Cleans parser test assertions.
tests/​api/​test_register_openapi.py Formats OpenAPI tests.
setup.cfg Removes obsolete Flake8 configuration.
README.md Documents MongoDB environment variables.
pyproject.toml Updates dependencies and tooling configuration.
PULL_REQUEST_TEMPLATE.md Removes trailing blank line.
foca/​version.py Changes quoting only.
foca/​utils/​misc.py Formats identifier utility.
foca/​utils/​logging.py Modernizes typing and formatting.
foca/​utils/​db.py Modernizes database utility annotations.
foca/​utils/​__init__.py Adds module description.
foca/​security/​cors.py Cleans documentation and formatting.
foca/​security/​auth.py Modernizes typing and exception chaining.
foca/​security/​access_control/​register_access_control.py Uses shared URI builder for Casbin.
foca/​security/​access_control/​foca_casbin_adapter/​casbin_rule.py Modernizes annotations and documentation.
foca/​security/​access_control/​foca_casbin_adapter/​adapter.py Modernizes adapter typing and formatting.
foca/​security/​access_control/​foca_casbin_adapter/​__init__.py Adds module description.
foca/​security/​access_control/​enforcement.py Modernizes typing and formatting.
foca/​security/​access_control/​constants.py Formats module documentation.
foca/​security/​access_control/​api/​default_model.conf Removes comment whitespace.
foca/​security/​access_control/​api/​__init__.py Adds module description.
foca/​security/​access_control/​access_control_server.py Adds exception chaining and modern annotations.
foca/​security/​__init__.py Adds module description.
foca/​models/​config.py Modernizes models and validator formatting.
foca/​models/​__init__.py Adds module description.
foca/​foca.py Documents class and simplifies branching.
foca/​factories/​connexion_app.py Modernizes typing and formatting.
foca/​factories/​celery_app.py Cleans formatting and documentation.
foca/​factories/​__init__.py Adds module description.
foca/​errors/​exceptions.py Modernizes typing and formatting.
foca/​errors/​__init__.py Adds module description.
foca/​database/​register_mongodb.py Adds URI building and log redaction.
foca/​database/​__init__.py Adds module description.
foca/​config/​config_parser.py Modernizes typing and exception chaining.
foca/​config/​__init__.py Adds module description.
foca/​api/​register_openapi.py Modernizes typing and formatting.
foca/​api/​__init__.py Adds module description.
examples/​petstore/​README.md Removes trailing whitespace.
examples/​petstore/​petstore.yaml Removes trailing whitespace.
examples/​petstore/​petstore_policies.conf Adds final newline.
examples/​petstore/​Dockerfile Adds final newline.
examples/​petstore/​docker-compose.yaml Updates Python and MongoDB images.
examples/​petstore/​controllers.py Formats example controllers.
examples/​petstore/​app.py Formats application entry point.
examples/​petstore-access-control/​README.md Removes trailing whitespace.
examples/​petstore-access-control/​petstore-access-control.yaml Removes trailing whitespace.
examples/​petstore-access-control/​petstore_policies.conf Adds final newline.
examples/​petstore-access-control/​exceptions.py Sorts imports.
examples/​petstore-access-control/​Dockerfile Adds final newline.
examples/​petstore-access-control/​docker-compose.yaml Updates Python and MongoDB images.
examples/​petstore-access-control/​controllers.py Formats protected controllers.
examples/​petstore-access-control/​app.py Formats application entry point.
docs/​api/​index.rst Removes trailing blank line.
docs/​api/​conf.py Formats configuration and closes version file.
docker/​Dockerfile Updates base image and Docker syntax.
.readthedocs.yaml Updates documentation build environment.
.pre-commit-config.yaml Adds Ruff and file hygiene hooks.
.github/​workflows/​release.yml Adds trusted PyPI publishing.
.github/​workflows/​checks.yml Restructures validation and image publishing.
.github/​dependabot.yml Adds scheduled dependency updates.

Review effort: Balanced

Comment thread foca/database/register_mongodb.py Resolved
Comment thread foca/database/register_mongodb.py Resolved
Comment thread foca/database/register_mongodb.py Resolved
Address review findings for `MONGO_URI` support:

- keep `admin` as authentication database for connection strings with
  credentials but without database, instead of switching to the
  database being registered
- recognize and keep `;` as option separator
- log connection strings without options, which may contain secrets
- select the Casbin adapter's database with `MONGO_DBNAME` applied, as
  for all other database clients (new `get_mongo_db_name()`)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 17, 2026 17:03
@uniqueg
uniqueg marked this pull request as ready for review October 17, 2026 17:05

Copilot AI 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.

Comment thread foca/database/register_mongodb.py Resolved
Comment thread foca/database/register_mongodb.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.

Hey - I've found 4 security issues

Security issues:

  • Detected a MongoDB connection string with embedded credentials, potentially exposing direct database access and sensitive application data. (link)
  • Detected a MongoDB connection string with embedded credentials, potentially exposing direct database access and sensitive application data. (link)
  • Detected a MongoDB connection string with embedded credentials, potentially exposing direct database access and sensitive application data. (link)
  • Detected a MongoDB connection string with embedded credentials, potentially exposing direct database access and sensitive application data. (link)
Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="tests/database/test_register_mongodb.py" line_range="55" />
<code_context>
mongodb://us%40r:p%3Aw%2Fd@db:1234/my_db
</code_context>
<issue_to_address>
**security (mongodb-connection-string):** Detected a MongoDB connection string with embedded credentials, potentially exposing direct database access and sensitive application data.

*Source: betterleaks*
</issue_to_address>

### Comment 2
<location path="tests/database/test_register_mongodb.py" line_range="62" />
<code_context>
mongodb://user:None@db:1234/my_db
</code_context>
<issue_to_address>
**security (mongodb-connection-string):** Detected a MongoDB connection string with embedded credentials, potentially exposing direct database access and sensitive application data.

*Source: betterleaks*
</issue_to_address>

### Comment 3
<location path="tests/database/test_register_mongodb.py" line_range="55" />
<code_context>
mongodb://us@r:p:w/d@db:1234/my_db
</code_context>
<issue_to_address>
**security (mongodb-connection-string):** Detected a MongoDB connection string with embedded credentials, potentially exposing direct database access and sensitive application data.

*Source: betterleaks*
</issue_to_address>

### Comment 4
<location path="tests/security/access_control/test_register_casbin_enforcer.py" line_range="60" />
<code_context>
mongodb://user:secret@other:27017/access_control_db
</code_context>
<issue_to_address>
**security (mongodb-connection-string):** Detected a MongoDB connection string with embedded credentials, potentially exposing direct database access and sensitive application data.

*Source: betterleaks*
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and if MONGO_URI points to the wrong server or database, application and access-control operations can read or write data there; reverting stops future use but does not undo those writes or any data exposure. The new release workflow also publishes distributions to PyPI, where a mistaken release cannot be fully taken back.

Blocking findings: tests/database/test_register_mongodb.py:55, tests/database/test_register_mongodb.py:62, tests/database/test_register_mongodb.py:55, tests/security/access_control/test_register_casbin_enforcer.py:60


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

Comment thread tests/database/test_register_mongodb.py Resolved
Comment thread tests/database/test_register_mongodb.py Resolved
Comment thread tests/database/test_register_mongodb.py Resolved
uniqueg and others added 5 commits October 18, 2026 01:25
# Conflicts:
#	.github/workflows/checks.yml
#	pyproject.toml
Instead of rewriting the database in `MONGO_URI` (and trying to keep
the effective authentication database by adding `authSource`), use the
connection string unchanged and select each database via the client
(`PyMongo.db = PyMongo.cx[name]`). The database in the URI path thus
keeps its standard meaning as authentication database, and
authentication mechanisms with other defaults (e.g., GSSAPI, X.509,
AWS), `authSource` from DNS TXT records of `mongodb+srv` URIs, and
unusual paths are no longer affected. The Casbin adapter already
selects its database by name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	.github/workflows/checks.yml
#	.github/workflows/release.yml
#	foca/database/register_mongodb.py
#	foca/security/access_control/register_access_control.py
Check usernames, passwords, hosts and databases of built connection
strings via `urlsplit()` instead of comparing with literal connection
strings that embed (dummy) credentials, which secret scanners flag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

Add MONGO_URI Environment Variable Support

2 participants