Skip to content

fix(access-control): keep app db, log setup - #269

Merged
uniqueg merged 23 commits into
devfrom
fix/access-control-setup
Oct 18, 2026
Merged

uniqueg merged 23 commits into
devfrom
fix/access-control-setup

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

Summary

Second phase-2 PR of the v0.14.0 maintenance series. Builds on #267 (and #266, #265); the new commits are the two fix(access-control) commits. Independent of #268.

Keep app databases when sharing the access control database (#114)

If security.access_control.db_name was the name of one of the app's databases, register_access_control() replaced that database's DBConfig, silently dropping the app's collections (including their clients and index config) from config.foca.db. Now:

  • the policy collection is added to the existing database, and the app's collections are kept
  • if the policy collection name equals one of the app's collections in that database, FOCA refuses to start with a ValueError explaining which setting to change (policies and app documents would otherwise share a collection)
  • separate databases behave as before
  • repeated registration with the same configuration (e.g., calling Foca.create_app() twice on the same instance) reuses the collection/database FOCA added before (thanks Copilot for catching that the first version broke this)

Setup logs (#250)

INFO log lines confirm that the Casbin enforcer, the permission management API (with spec path) and access control as a whole were registered.

Docs

The access control docs describe the shared-database behaviour and now state the correct default collection name (policy_rules, not permission_rules).

Ideas for the log lines come from #256/#257 (thanks @minhpham1810).

Closes #114, closes #250

Not included: configurable permission IDs (#142), which you rated low priority on the issue.

Verification

Test-first: new TestRegisterAccessControlSetup tests (separate DB, shared DB with and without a registered client, collection clash, no DB config, log lines, repeated registration) and test_foca_create_app_twice; the tests for the shared DB, clash, logs and repeated registration failed before the respective fixes.

Locally (Python 3.13): unit tests without MongoDB: 255 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

Preserve application database configuration during access-control setup and improve registration visibility and reliability.

Bug Fixes:

  • Preserve existing application databases and collections when access control shares a database, while rejecting policy collection name clashes.
  • Make repeated access-control registration safe and reusable, including repeated app creation.
  • Add INFO logs confirming access-control, Casbin, and permission API registration.

Enhancements:

  • Document shared-database behavior and correct the default policy collection name to policy_rules.

Documentation:

  • Update access-control database configuration documentation with shared-database behavior, collection clash restrictions, and the corrected default collection name.

Tests:

  • Add coverage for separate and shared databases, existing clients, collection clashes, missing database configuration, repeated registration, setup logging, and repeated app creation.

uniqueg and others added 15 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
If `security.access_control.db_name` named one of the app's databases,
registering access control replaced that database's config, dropping
the app's collections (and their clients and indexes) from
`config.foca.db`. Add the policy collection to the existing database
instead, and refuse to start if the policy collection would share a
collection with the app.

Also log when the Casbin enforcer, the permission management API and
access control as a whole have been registered, and correct the default
collection name in the access control docs.

Closes #114
Closes #250

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

sourcery-ai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This maintenance PR fixes access-control registration so shared application databases retain their existing collections and clients, rejects policy collection collisions, supports repeated app creation, and adds setup INFO logs and corresponding documentation. It also substantially refreshes project tooling and delivery infrastructure through formatting/type modernization, dependency updates, new CI/release workflows, container updates, Dependabot, and pre-commit configuration.

Sequence diagram for access-control setup registration and logs

sequenceDiagram
    participant Foca
    participant Register as register_access_control
    participant Casbin as register_casbin_enforcer
    participant API as register_permission_specs
    participant Logger

    Foca->>Register: register_access_control
    Register->>Casbin: register_casbin_enforcer
    Casbin-->>Logger: Casbin enforcer registered.
    Register->>API: register_permission_specs
    API-->>Logger: Permission management API registered from spec_path.
    Register-->>Foca: registered access-control configuration
    Foca-->>Logger: Access control registered.
Loading

Flow diagram for shared access-control database registration

flowchart TD
    A[register_access_control] --> B[Look up access_control_db]
    B -->|database absent| C[Create DBConfig with policy_rules]
    C --> D[add_new_database]
    B -->|database exists| E[Keep existing DBConfig and app collections]
    E --> F{Policy collection clashes?}
    F -->|yes| G[Raise ValueError]
    F -->|no| H[Add policy CollectionConfig]
    H --> I{Database client exists?}
    I -->|no| J[add_new_database]
    I -->|yes| K[Attach policy collection client]
    D --> L[register_casbin_enforcer]
    J --> L
    K --> L
    L --> M[register_permission_specs]
    M --> N[Store _registered_collection for repeated registration]
Loading

File-Level Changes

Change Details Files
Preserve application database configuration when access-control storage shares a database, while preventing policy/application collection collisions and making repeated registration safe.
  • Add the policy collection to an existing database instead of replacing its DBConfig.
  • Track FOCA-added database/collection state to avoid duplication during repeated app creation.
  • Reuse registered database clients and raise a descriptive ValueError for collection-name clashes.
  • Add coverage for separate/shared databases, existing clients, missing DB configuration, clashes, and repeated registration.
foca/security/access_control/register_access_control.py
foca/models/config.py
foca/database/register_mongodb.py
tests/security/access_control/test_register_access_control.py
tests/test_foca.py
Add explicit startup INFO logging for access-control registration stages and document the shared-database behavior.
  • Log Casbin enforcer registration, permission API registration with its specification path, and overall access-control registration.
  • Correct the documented default policy collection name and describe shared-database constraints.
foca/security/access_control/register_access_control.py
foca/foca.py
docs/access_control/README.md
tests/security/access_control/test_register_access_control.py
Modernize and harden the project’s development, CI, release, and packaging configuration.
  • Replace the CI workflow with separate lint/type-check/build, multi-version MongoDB unit-test, integration, and gated Docker publishing jobs.
  • Add Dependabot, pre-commit hooks, pinned GitHub Actions, concurrency controls, release-to-PyPI trusted publishing, and distribution validation.
  • Update supported dependency ranges, Python classifiers, Ruff configuration, warning filters, Docker base images, and documentation build settings.
.github/dependabot.yml
.github/workflows/checks.yml
.github/workflows/release.yml
.pre-commit-config.yaml
pyproject.toml
.readthedocs.yaml
docker/Dockerfile
examples/petstore/docker-compose.yaml
examples/petstore-access-control/docker-compose.yaml
setup.cfg
Apply broad Ruff/pyupgrade formatting and typing modernization across the package, tests, examples, and documentation support code.
  • Convert legacy typing annotations and imports to modern Python syntax.
  • Normalize formatting, imports, docstrings, exception chaining, and minor readability issues.
  • Add package-level module docstrings and update examples/test fixtures accordingly.
foca/**/*.py
tests/**/*.py
examples/**/*.py
README.md
docs/api/conf.py
PULL_REQUEST_TEMPLATE.md
examples/**/*.yaml
examples/**/*.conf

Assessment against linked issues

Issue Objective Addressed Explanation
#114 Handle access-control configuration when its database name matches an application database, preserving the application's database and collections. ✅
#114 Detect and reject an access-control collection name that conflicts with an application collection in the shared database. ✅
#250 Add a client-readable log confirming that the Casbin enforcer has been registered. ✅
#250 Add a client-readable log confirming that the permission management specs/API have been registered. ✅
#250 Add a client-readable log confirming that access control registration as a whole has completed. ✅

Possibly linked issues

  • Add readable logs for Access Control Setup #250: The PR adds the requested enforcer, permission API, and overall access-control registration confirmation logs.
  • #N/A: Link them: the PR adds config-driven enforcement, validated OIDC claim/group mapping, permissions API authorization, and public resource-role helpers requested by the issue.

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 (839ffb3) to head (715f181).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #269   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines         1101      1130   +29     
=========================================
+ Hits          1101      1130   +29     
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 and others added 2 commits October 17, 2026 18:50
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]>

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

Repeated app creation fails, and the YAML hook rejects an intentional invalid fixture.

2 open issues
What changed in this PR

Preserves application collections when sharing the access-control database and adds startup confirmation logs. The stacked changes also modernize dependencies, tooling, and delivery workflows.

Changes:

  • Preserve shared database configuration and reject collection-name conflicts.
  • Add setup logs, regression tests, and shared-database documentation.
  • Update dependencies, CI, release automation, and Python formatting.
File Description
tests/​utils/​test_misc.py Clean up test docstrings.
tests/​utils/​test_logging.py Format logging tests.
tests/​utils/​test_db.py Normalize quoting.
tests/​test_foca.py Format imports and paths.
tests/​test_files/​models_petstore.py Modernize type annotations.
tests/​test_files/​model_valid.py Format model fixture.
tests/​security/​test_cors.py Normalize quoting.
tests/​security/​test_auth.py Format authentication tests.
tests/​security/​access_control/​test_register_access_control.py Add database preservation, collision, and logging tests.
tests/​security/​access_control/​test_enforcement.py Modernize enforcement tests.
tests/​security/​access_control/​test_access_control_server.py Format permission-controller tests.
tests/​security/​access_control/​foca_casbin_adapter/​test_casbin_rule.py Format rule tests.
tests/​security/​access_control/​foca_casbin_adapter/​test_adapter.py Modernize adapter tests.
tests/​models/​test_config.py Format configuration tests.
tests/​mock_data.py Format shared fixtures.
tests/​factories/​test_connexion_app.py Normalize imports and quoting.
tests/​factories/​test_celery_app.py Simplify imports.
tests/​errors/​test_errors.py Format error-handler tests.
tests/​database/​test_register_mongodb.py Format database tests.
tests/​config/​test_config_parser.py Normalize formatting and type comparisons.
tests/​api/​test_register_openapi.py Format OpenAPI tests.
setup.cfg Remove obsolete Flake8 configuration.
README.md Format Python examples.
pyproject.toml Update dependencies and configure Ruff.
foca/​version.py Normalize quoting; version unchanged.
foca/​utils/​misc.py Format identifier utility.
foca/​utils/​logging.py Modernize annotations and formatting.
foca/​utils/​db.py Modernize database utilities.
foca/​utils/​__init__.py Add package docstring.
foca/​security/​cors.py Clarify docstring and formatting.
foca/​security/​auth.py Modernize typing, defaults, and exception chaining.
foca/​security/​access_control/​register_access_control.py Preserve app databases, reject clashes, and log setup.
foca/​security/​access_control/​foca_casbin_adapter/​casbin_rule.py Modernize typing and docstrings.
foca/​security/​access_control/​foca_casbin_adapter/​adapter.py Modernize adapter typing and documentation.
foca/​security/​access_control/​foca_casbin_adapter/​__init__.py Add package docstring.
foca/​security/​access_control/​enforcement.py Modernize typing and formatting.
foca/​security/​access_control/​constants.py Format module docstring.
foca/​security/​access_control/​api/​__init__.py Add package docstring.
foca/​security/​access_control/​access_control_server.py Modernize controllers and chain exceptions.
foca/​security/​__init__.py Add package docstring.
foca/​models/​config.py Modernize annotations and validator syntax.
foca/​models/​__init__.py Add package docstring.
foca/​foca.py Log completed access-control registration.
foca/​factories/​connexion_app.py Modernize factory formatting and typing.
foca/​factories/​celery_app.py Clarify task documentation and formatting.
foca/​factories/​__init__.py Add package docstring.
foca/​errors/​exceptions.py Modernize error-handler typing and formatting.
foca/​errors/​__init__.py Add package docstring.
foca/​database/​register_mongodb.py Format database registration code.
foca/​database/​__init__.py Add package docstring.
foca/​config/​config_parser.py Modernize typing and chain import errors.
foca/​config/​__init__.py Add package docstring.
foca/​api/​register_openapi.py Modernize OpenAPI registration formatting.
foca/​api/​__init__.py Add package docstring.
examples/​petstore/​docker-compose.yaml Update Python and MongoDB images.
examples/​petstore/​controllers.py Format example controllers.
examples/​petstore/​app.py Simplify application bootstrap formatting.
examples/​petstore-access-control/​exceptions.py Sort imports.
examples/​petstore-access-control/​docker-compose.yaml Update Python and MongoDB images.
examples/​petstore-access-control/​controllers.py Format protected controllers.
examples/​petstore-access-control/​app.py Simplify application bootstrap formatting.
docs/​api/​conf.py Format Sphinx configuration and close version file.
docs/​access_control/​README.md Document database sharing and correct collection default.
docker/​Dockerfile Update base image and Dockerfile syntax.
.readthedocs.yaml Update documentation build environment.
.pre-commit-config.yaml Add Ruff and file-validation hooks.
.github/​workflows/​release.yml Add trusted PyPI publishing.
.github/​workflows/​checks.yml Expand validation and restrict image publishing.
.github/​dependabot.yml Add scheduled dependency updates.

Review effort: Balanced

Comment thread .pre-commit-config.yaml Resolved
uniqueg and others added 2 commits October 17, 2026 18:55
Calling `Foca.create_app()` twice on the same instance failed: the
policy collection added by the first call was taken for an app
collection with the same name. Remember which collection (and
database) access control registration added and replace it on
repeated registration.

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

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

Retrying after a collection clash can remove application collection configuration and bypass clash validation.

1 open issue
2 resolved since last review

Review effort: Balanced

@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 reviewed your changes and they look great!

Sourcery assessment

Needs a human reviewer. Access-control registration now selects or adds the MongoDB collection that stores Casbin policies, so a routing mistake could make authorization use the wrong persisted rules; reverting would not undo policy records already written. The new release workflow also publishes distributions externally, which a revert cannot retract.


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

uniqueg and others added 4 commits October 18, 2026 01:22
# Conflicts:
#	.github/workflows/checks.yml
#	pyproject.toml
Remember the policy collection added by access control registration
only once registration of the database succeeded, so that retrying a
rejected registration (collection clash) does not remove the app's
collection config. Also cover app databases without collections.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	.github/workflows/checks.yml
#	.github/workflows/release.yml
#	foca/foca.py
#	foca/models/config.py
#	foca/security/access_control/register_access_control.py
#	tests/security/access_control/test_register_access_control.py
@uniqueg
uniqueg merged commit 9047976 into dev Oct 18, 2026
13 checks passed
@uniqueg
uniqueg deleted the fix/access-control-setup branch October 18, 2026 00:08
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 readable logs for Access Control Setup Add validation checks for access control databases.

2 participants