Repository navigation
feat(db): support MONGO_URI connection strings - #270
Conversation
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]>
Reviewer's GuideThis PR centralizes MongoDB connection-string handling so every configured and access-control database honors Sequence diagram for MongoDB database registration with MONGO_URIsequenceDiagram
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
Flow diagram for MongoDB URI selection and protectionflowchart 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"]
File-Level Changes
Assessment against linked issues
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 #270 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 22 22
Lines 1130 1151 +21
=========================================
+ Hits 1130 1151 +21
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.
🟡 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
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]>
There was a problem hiding this comment.
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
# 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]>


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 stringsandfix(db): keep auth source, redact URI options. Independent of #268 and #269.Supersedes #254, #256 and #257, which each implemented
MONGO_URIbut 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_URINew
foca.database.register_mongodb.get_mongo_uri()builds the connection string for one database:MONGO_URIis set, it is used as is (mongodb://ormongodb+srv://; replica sets, TLS, read preferences etc. via options), but with the database set to the database being registered, so each database indb.dbs(and the access control database) keeps its own nameauthSourceis set explicitly: a database in the URI path becomesauthSource(somongodb://user:pw@host/adminkeeps authenticating againstadmin), and URIs with credentials but no database getauthSource=admin, the MongoDB default;instead of&are supportedValueErrornamingMONGO_URIMONGO_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_DBNAMEkeeps overriding database names in both modesCasbin 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 usesget_mongo_uri()as well, and selects its database with theMONGO_DBNAMEoverride applied (newget_mongo_db_name()), like all other database clients.Thanks Copilot for the review findings on auth source, separators, logging and
MONGO_DBNAME.Other
tlsCertificateKeyFilePassword)_create_mongo_client()keeps its signature (used by proTES)Closes #253
Noted for the code audit (not changed here)
With
MONGO_USERNAMEset butMONGO_PASSWORDunset, the literal stringNoneis 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
TestGetMongoUritests (defaults, env overrides, escaped credentials,MONGO_URIwith replica set/options, without path, with and without credentials, SRV, auth DB, explicitauthSource,;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'sparse_uri()accepts the generated connection strings.Locally (Python 3.13): unit tests without MongoDB: 266 passed;
ruff check,ruff format --check,mypy focaclean.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:
MONGO_URIconnection strings while preserving per-database selection and authentication settings.Bug Fixes:
Enhancements:
Documentation:
Tests: