Repository navigation
docs(examples): config-driven access control - #271
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]>
Rewrite the Petstore access control example to use the config-driven enforcement introduced in #259 instead of the header-based `check_permissions` decorator, which the docs advise against combining with `enforce`: - enforce policies on all operations (`access_control.enforce`) with subjects taken from validated bearer tokens - use a model with resource-scoped roles; seed policies allowing any authenticated user to list and add pets, and owners to view and delete their pets - make the creator of a pet its owner (`add_resource_role()`) and remove all roles granted on deleted pets (`remove_resource()`) - document policies, ownership, admin roles and bearer tokens in the example's README; fix the link to the access control docs and outdated Docker/Python hints Closes #147 Closes #148 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR combines a configuration-driven access-control example with broad repository maintenance: it centralizes authorization in FOCA configuration and Casbin resource roles, adds canonical and race-safe pet ownership handling, documents the bearer-token/admin workflow, and modernizes CI, release automation, dependencies, typing, formatting, and tests. Sequence diagram for config-driven pet access enforcementsequenceDiagram
actor User
participant FOCA
participant Auth
participant Casbin
participant Controller
participant MongoDB
User->>FOCA: HTTP request with Bearer token
FOCA->>Auth: validate_token(token)
Auth-->>FOCA: validated claims including sub
FOCA->>Casbin: enforce(subject, request.path, request.method)
alt policy allows request
Casbin-->>FOCA: allow
FOCA->>Controller: resolve operation
Controller->>MongoDB: read or write pet
Controller-->>User: response
else policy denies request
Casbin-->>FOCA: deny
FOCA-->>User: 403 Forbidden
end
Sequence diagram for race-safe pet ownership creationsequenceDiagram
actor User
participant Controller
participant MongoDB
participant Casbin
User->>Controller: addPet(pet)
loop until insert succeeds
Controller->>MongoDB: find_one latest id
Controller->>MongoDB: insert_one(record)
alt DuplicateKeyError
MongoDB-->>Controller: duplicate id
else insert succeeds
MongoDB-->>Controller: pet created
end
end
Controller->>Casbin: add_resource_role(subject, owner, canonical pet path)
Controller-->>User: created pet
Sequence diagram for canonical pet ownership cleanupsequenceDiagram
actor User
participant Controller
participant MongoDB
participant Casbin
User->>Controller: deletePet(id)
Controller->>MongoDB: find_one(id)
Controller->>MongoDB: delete_one(id)
Controller->>Casbin: remove_resource(canonical pet path)
Casbin-->>Controller: resource roles removed
Controller-->>User: 204 No Content
Entity relationship diagram for pet and access-control ruleserDiagram
PETS {
int id PK
string name
string tag
}
POLICY_RULES {
string ptype
string subject
string role
string resource
string action
}
PETS ||--o{ POLICY_RULES : owns_resource_roles
File-Level Changes
Assessment against 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 #271 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 22 22
Lines 1151 1151
=========================================
Hits 1151 1151
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
ID collisions and incomplete ownership cleanup can give users access to another creator’s pet.
2 open issues
What changed in this PR
Updates the Petstore example to demonstrate FOCA’s config-driven authorization, alongside inherited tooling and dependency maintenance.
Changes:
- Enables bearer-token authorization, resource ownership, and administrator policies.
- Documents authentication, ownership, and permissions API usage.
- Modernizes dependencies, CI, release automation, and repository formatting.
| File | Description |
|---|---|
| tests/utils/test_misc.py | Cleans up test formatting and docstrings. |
| tests/utils/test_logging.py | Reformats logging tests. |
| tests/utils/test_db.py | Standardizes quoting. |
| 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 type annotations. |
| tests/test_files/model_valid.py | Formats model fixture. |
| tests/test_files/invalid_conf.yaml | Normalizes final newline. |
| tests/test_files/empty_conf.yaml | Normalizes final newline. |
| tests/test_files/conf_valid_cors_enabled.yaml | Normalizes final newline. |
| tests/test_files/conf_valid_cors_disabled.yaml | Normalizes final newline. |
| tests/test_files/conf_valid_access_control.yaml | Normalizes final newline. |
| tests/test_files/conf_jobs.yaml | Normalizes final newline. |
| tests/test_files/conf_invalid_jobs.yaml | Normalizes final newline. |
| tests/test_files/conf_invalid_access_control.yaml | Normalizes final newline. |
| tests/test_files/conf_api.yaml | Normalizes final newline. |
| tests/security/test_cors.py | Standardizes quoting. |
| tests/security/test_auth.py | Formats authentication tests. |
| tests/security/access_control/test_register_access_control.py | Formats registration tests. |
| tests/security/access_control/test_enforcement.py | Formats existing enforcement tests and annotations. |
| tests/security/access_control/test_access_control_server.py | Formats permissions API tests. |
| tests/security/access_control/foca_casbin_adapter/test_files/rbac_with_resources_roles.conf | Normalizes final newline. |
| tests/security/access_control/foca_casbin_adapter/test_files/rbac_model.conf | Normalizes 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 test annotations and formatting. |
| tests/models/test_config.py | Formats configuration tests. |
| tests/mock_data.py | Formats shared fixtures. |
| tests/factories/test_connexion_app.py | Formats imports and fixtures. |
| tests/factories/test_celery_app.py | Simplifies import syntax. |
| tests/errors/test_errors.py | Formats error-handler tests. |
| tests/database/test_register_mongodb.py | Formats database tests. |
| tests/config/test_config_parser.py | Formats tests and type comparisons. |
| tests/api/test_register_openapi.py | Formats OpenAPI registration tests. |
| setup.cfg | Removes legacy Flake8 configuration. |
| README.md | Formats Python examples. |
| pyproject.toml | Updates dependencies and configures Ruff. |
| PULL_REQUEST_TEMPLATE.md | Removes trailing blank line. |
| foca/version.py | Standardizes quoting. |
| foca/utils/misc.py | Formats ID-generation code. |
| foca/utils/logging.py | Modernizes annotations and formatting. |
| foca/utils/db.py | Modernizes annotations and query formatting. |
| foca/utils/__init__.py | Adds package docstring. |
| foca/security/cors.py | Cleans up documentation and formatting. |
| foca/security/auth.py | Modernizes typing, defaults, and exception chaining. |
| foca/security/access_control/register_access_control.py | Formats registration and decorator code. |
| foca/security/access_control/foca_casbin_adapter/casbin_rule.py | Updates annotations and method documentation. |
| foca/security/access_control/foca_casbin_adapter/adapter.py | Modernizes typing and documentation. |
| foca/security/access_control/foca_casbin_adapter/__init__.py | Adds package docstring. |
| foca/security/access_control/enforcement.py | Modernizes existing enforcement code formatting. |
| foca/security/access_control/constants.py | Formats module docstring. |
| foca/security/access_control/api/default_model.conf | Removes comment whitespace. |
| foca/security/access_control/api/__init__.py | Adds package docstring. |
| foca/security/access_control/access_control_server.py | Formats controllers and preserves exception causes. |
| foca/security/__init__.py | Adds package docstring. |
| foca/models/config.py | Modernizes annotations and validator syntax. |
| foca/models/__init__.py | Adds package docstring. |
| foca/foca.py | Documents factory and simplifies branching. |
| foca/factories/connexion_app.py | Modernizes formatting and annotations. |
| foca/factories/celery_app.py | Formats factory and task documentation. |
| foca/factories/__init__.py | Adds package docstring. |
| foca/errors/exceptions.py | Modernizes error-handler formatting. |
| foca/errors/__init__.py | Adds package docstring. |
| foca/database/register_mongodb.py | Formats database registration code. |
| foca/database/__init__.py | Adds package docstring. |
| foca/config/config_parser.py | Modernizes typing and exception chaining. |
| foca/config/__init__.py | Adds package docstring. |
| foca/api/register_openapi.py | Formats OpenAPI registration code. |
| foca/api/__init__.py | Adds package docstring. |
| examples/petstore/README.md | Removes trailing whitespace. |
| examples/petstore/petstore.yaml | Removes trailing whitespace. |
| examples/petstore/petstore_policies.conf | Normalizes final newline. |
| examples/petstore/Dockerfile | Normalizes final newline. |
| examples/petstore/docker-compose.yaml | Updates Python and MongoDB images. |
| examples/petstore/controllers.py | Formats existing controllers. |
| examples/petstore/app.py | Formats entry point. |
| examples/petstore-access-control/README.md | Documents authorization and authenticated requests. |
| examples/petstore-access-control/petstore-access-control.yaml | Removes trailing whitespace. |
| examples/petstore-access-control/petstore_policies.conf | Defines resource roles and administrator access. |
| examples/petstore-access-control/exceptions.py | Sorts imports. |
| examples/petstore-access-control/Dockerfile | Normalizes final newline. |
| examples/petstore-access-control/docker-compose.yaml | Updates Python and MongoDB images. |
| examples/petstore-access-control/controllers.py | Replaces decorators with ownership management. |
| examples/petstore-access-control/config.yaml | Enables enforcement and documents group mapping. |
| examples/petstore-access-control/app.py | Seeds default access policies. |
| docs/api/index.rst | Removes trailing blank line. |
| docs/api/conf.py | Formats documentation build configuration. |
| docker/Dockerfile | Updates base image and Dockerfile 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 grouped dependency updates. |
Review effort: Balanced
Ownership in the access control example is granted per pet path, so pet IDs must never be shared and roles must be removed reliably: - make pet IDs unique (index in `config.yaml`) and retry with the next ID if a concurrent request took it - grant and remove roles on the canonical pet path built from the validated ID, so that, e.g., deleting via `/pets/00` also removes the roles granted on `/pets/0` Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="examples/petstore-access-control/README.md" line_range="100" />
<code_context>
- cd ../..
- sleep 10
- pytest ./tests/integration_tests.py
+ docker compose up -d --build
+ - name: Wait for petstore app
+ run: |
</code_context>
<issue_to_address>
**Public debugger permits code execution**
When the documented example is deployed on a network reachable by untrusted users, the documented Compose deployment publishes the app on port 80, while `config.yaml` sets `server.debug: True` and `host: '0.0.0.0'`. `Foca.create_app()` passes debug mode to Connexion, so an unauthenticated attacker who can reach the app can access the Werkzeug debugger and execute code in the container.
Disable debug mode and the reloader in the example configuration before documenting or recommending this deployment.
</issue_to_address>
### Comment 2
<location path="examples/petstore-access-control/config.yaml" line_range="60" />
<code_context>
+ - keys:
+ id: 1
+ options:
+ unique: True
exceptions:
</code_context>
<issue_to_address>
**Startup drops unrelated indexes**
When the existing pets collection has secondary indexes not declared in this config, `register_mongodb` drops every secondary index on the pets collection and recreates only the configured `id` index, removing other indexes and any uniqueness constraints they enforce.
Preserve unrelated indexes and remove only indexes that FOCA explicitly manages.
</issue_to_address>
### Comment 3
<location path="examples/petstore-access-control/controllers.py" line_range="62-73" />
<code_context>
+ # IDs are unique (cf. index in `config.yaml`); if a concurrent request
+ # took the next ID, try again with the one after
+ for _ in range(MAX_INSERT_ATTEMPTS):
+ last = db_collection.find_one(
+ {}, {"_id": False, "id": True}, sort=[("id", -1)]
+ )
+ counter = 0 if last is None else last["id"] + 1
+ record = {"id": counter, "name": pet["name"], "tag": pet["tag"]}
+ try:
+ db_collection.insert_one(record)
+ break
+ except DuplicateKeyError:
+ continue
+ else:
+ raise InternalServerError
+ del record["_id"]
+ # Make the creator the owner of the new pet
</code_context>
<issue_to_address>
**Concurrent creates return errors**
When a create request loses all ten ID-insert attempts during a burst of concurrent creates, `addPet` raises `InternalServerError` even though other inserts are succeeding and IDs remain available, so the caller's otherwise valid create fails.
Avoid giving up after a fixed number of duplicate-key retries.
Also at `examples/petstore-access-control/controllers.py:24`, `examples/petstore-access-control/controllers.py:61`.
</issue_to_address>
### Comment 4
<location path="examples/petstore-access-control/controllers.py" line_range="66" />
<code_context>
+ {}, {"_id": False, "id": True}, sort=[("id", -1)]
+ )
+ counter = 0 if last is None else last["id"] + 1
+ record = {"id": counter, "name": pet["name"], "tag": pet["tag"]}
+ try:
+ db_collection.insert_one(record)
</code_context>
<issue_to_address>
**Optional tag breaks pet creation**
When a client posts a pet with the required `name` but no `tag`, `addPet` indexes `pet["tag"]` unconditionally, so a valid request that omits the optional `tag` field raises `KeyError` before insertion and returns an error instead of creating the pet.
Handle an omitted tag, for example by using `pet.get("tag")` when building the record.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 4 findings to address first, and a mistaken policy can grant a non-owner access to pet records or deletion, and the release workflow can publish an incorrect distribution to PyPI. Reverting stops future runs but cannot restore deleted data or erase a version already published.
Blocking findings: examples/petstore-access-control/README.md:100, examples/petstore-access-control/config.yaml:60, examples/petstore-access-control/controllers.py:73, examples/petstore-access-control/controllers.py:66
- take pet IDs from an atomically incremented counter, so that IDs are neither shared by concurrent requests nor reused after deletion (ownership is granted per pet ID), and creating pets no longer fails under contention - accept pets without the optional `tag` - disable the debugger and reloader in the example config, as the app is published on all interfaces Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ontrol # Conflicts: # .github/workflows/checks.yml # .github/workflows/release.yml # examples/petstore-access-control/app.py # examples/petstore-access-control/controllers.py # examples/petstore-access-control/petstore_policies.conf

Summary
Fourth phase-2 PR of the v0.14.0 maintenance series. Builds on #267 (and #266, #265); the new commits are
docs(examples): config-driven access controlandfix(examples): unique pet IDs, canonical paths. Independent of #268–#270.The
petstore-access-controlexample still used the header-basedcheck_permissionsdecorator (subjects from auser_idheader), which the access control docs advise against combining with the config-driven enforcement introduced in #259. It now demonstrates the recommended setup:security.access_control.enforce: True; subjects come from validated bearer tokens (subclaim); no decorators in controllerspetstore_policies.confis now a model with resource-scoped roles (based on FOCA's reference model)app.pyseedsp, *, /pets, (GET)|(POST)(any authenticated user may list/add pets) andp, owner, /pets/:id, (GET)|(DELETE)(owners may view/delete their pets); adding is a no-op if they existaddPetmakes the creator the owner (add_resource_role()),deletePetremoves all roles granted on the deleted pet (remove_resource()); roles are granted/removed on the canonical pet path built from the validated ID (e.g., deleting via/pets/00cleans up/pets/0)addPetretries with the next ID if a concurrent request took it, so two creators can never share ownership of one pet path (thanks Copilot for both findings)grules orclaim_groups/group_mapping(commented example inconfig.yaml)Closes #147, closes #148
Verification
ruff check/ruff format --checkonexamples/: cleanconfig.yaml(enforcement enabled, example model loaded, pets and access control databases registered)Not verified: an end-to-end run with Docker Compose. The example requires bearer tokens from an OpenID Connect identity provider, so it cannot run in CI (as before, the example is not part of the CI integration tests), and I had no Docker access in my environment.
CI: all checks pass (run).
Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Demonstrate configuration-driven access control in the petstore example with authenticated requests, resource ownership, and administrator permissions.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Chores: