Skip to content

docs(examples): config-driven access control - #271

Merged
uniqueg merged 21 commits into
devfrom
docs/petstore-access-control
Oct 18, 2026
Merged

uniqueg merged 21 commits into
devfrom
docs/petstore-access-control

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

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 control and fix(examples): unique pet IDs, canonical paths. Independent of #268–#270.

The petstore-access-control example still used the header-based check_permissions decorator (subjects from a user_id header), which the access control docs advise against combining with the config-driven enforcement introduced in #259. It now demonstrates the recommended setup:

  • Enforcement by config: security.access_control.enforce: True; subjects come from validated bearer tokens (sub claim); no decorators in controllers
  • Model: petstore_policies.conf is now a model with resource-scoped roles (based on FOCA's reference model)
  • Policies: app.py seeds p, *, /pets, (GET)|(POST) (any authenticated user may list/add pets) and p, owner, /pets/:id, (GET)|(DELETE) (owners may view/delete their pets); adding is a no-op if they exist
  • Ownership: addPet makes the creator the owner (add_resource_role()), deletePet removes 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/00 cleans up /pets/0)
  • Unique IDs: pet IDs have a unique index, and addPet retries 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)
  • Admins: documented via g rules or claim_groups/group_mapping (commented example in config.yaml)
  • README: new "Access control" section; curl examples with bearer tokens; permissions API examples for admins (e.g., making a user an admin); fixed link to the access control docs, outdated Docker Compose/Python image hints, and the mislabelled "delete a permission" example

Closes #147, closes #148

Verification

  • ruff check / ruff format --check on examples/: clean
  • the example app is created from its config.yaml (enforcement enabled, example model loaded, pets and access control databases registered)
  • the model and seeded policies plus an ownership rule were checked with Casbin directly: owners may view/delete their pets but not others', non-owners are denied, any authenticated user may list/add pets, admins may do everything incl. the permissions API, non-admins are denied the permissions API (11/11 expected decisions)
  • a scratch test of the controllers (Flask request contexts, mongomock, stubbed ownership helpers) confirmed sequential IDs, retry after a concurrent insert, and canonical role cleanup

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:

  • Configure the petstore example to enforce bearer-token-based access control with resource-scoped ownership and administrator roles.
  • Document authenticated API usage, ownership permissions, administrator configuration, and permissions management.

Bug Fixes:

  • Ensure pet identifiers remain unique under concurrent creation and clean up ownership rules using canonical resource paths when pets are deleted.

Enhancements:

  • Replace controller-level header permission checks with centralized configuration-driven enforcement.
  • Seed default pet access policies and manage ownership assignments through the example controllers.

Documentation:

  • Update the petstore access-control README with OpenID Connect prerequisites, bearer-token examples, policy behavior, and corrected setup guidance.

Chores:

  • Harden the example's default server configuration for non-development use.

uniqueg and others added 17 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]>
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]>
Copilot AI balanced review requested due to automatic review settings October 17, 2026 17:06
@sourcery-ai

sourcery-ai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 enforcement

sequenceDiagram
    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
Loading

Sequence diagram for race-safe pet ownership creation

sequenceDiagram
    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
Loading

Sequence diagram for canonical pet ownership cleanup

sequenceDiagram
    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
Loading

Entity relationship diagram for pet and access-control rules

erDiagram
    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
Loading

File-Level Changes

Change Details Files
Adds repository automation for dependency updates, formatting, type checking, packaging, integration testing, Docker publishing, and trusted PyPI releases.
  • Introduces pinned GitHub Actions workflows for lint/build, a Python and MongoDB test matrix, petstore integration tests, Docker image publishing, and release publishing.
  • Adds Dependabot and pre-commit configuration, updates documentation build settings, and replaces setup.cfg with pyproject-based tooling.
  • Updates Docker base images, dependency constraints, supported Python versions, and lint/type-check configuration.
.github/dependabot.yml
.github/workflows/checks.yml
.github/workflows/release.yml
.pre-commit-config.yaml
.readthedocs.yaml
docker/Dockerfile
pyproject.toml
setup.cfg
Reworks the petstore access-control example to use configuration-driven bearer-token enforcement with resource-scoped Casbin roles.
  • Enables access-control enforcement and loads a resource-role model from configuration.
  • Seeds authenticated-user and owner policies at startup without controller decorators.
  • Uses validated token subjects for ownership, grants ownership on creation, and removes resource roles on deletion.
  • Documents administrator role assignment, group mapping, bearer-token usage, permissions API calls, and the revised deployment requirements.
examples/petstore-access-control/app.py
examples/petstore-access-control/config.yaml
examples/petstore-access-control/controllers.py
examples/petstore-access-control/petstore_policies.conf
examples/petstore-access-control/README.md
examples/petstore-access-control/docker-compose.yaml
examples/petstore-access-control/Dockerfile
examples/petstore-access-control/petstore-access-control.yaml
examples/petstore-access-control/exceptions.py
Makes pet creation concurrency-safe and keeps ownership paths canonical.
  • Adds a unique MongoDB index for pet IDs.
  • Retries inserts after duplicate-key races, bounded by a maximum attempt count.
  • Builds ownership and cleanup paths from the validated numeric ID so alternate URL spellings address the same resource.
examples/petstore-access-control/config.yaml
examples/petstore-access-control/controllers.py
Modernizes the package implementation and tests for the updated Python, dependency, and tooling baseline.
  • Migrates typing annotations to built-in and collections.abc forms and applies Ruff formatting/import ordering across production code and tests.
  • Adds package-level module documentation and minor exception/chaining, API registration, configuration, authentication, database, and access-control cleanup.
  • Refreshes tests and fixtures to match the formatting and typing changes while retaining coverage for access-control enforcement, roles, authentication, and registration.
foca/**/*.py
tests/**/*.py
docs/api/conf.py
docs/api/index.rst
README.md
PULL_REQUEST_TEMPLATE.md
examples/petstore/**/*.py
examples/petstore/**/*.yaml
examples/petstore/**/*.md

Assessment against linked issues

Issue Objective Addressed Explanation
#147 Use FOCA’s access-control functionality in the Petstore example to automatically make each newly created pet’s creator its owner, with permission to view and delete that pet. ✅
#148 Automatically grant a resource’s creator an owner role for that resource. ✅
#148 Allow the creator-owner to manage permissions on their resource without requiring manual permission setup. ❌ The example grants creators the owner role, but its owner policy only permits viewing and deleting pets. The README explicitly limits the permissions API to admins, and the PR does not add owner-authorized permission-management operations scoped to a resource.

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 (5317509) to head (ad2df71).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #271   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines         1151      1151           
=========================================
  Hits          1151      1151           
Flag Coverage Δ
test_unit 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

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]>
Copilot AI balanced review requested due to automatic review settings October 17, 2026 22:45
@uniqueg
uniqueg marked this pull request as ready for review October 17, 2026 22:48

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

Reused pet IDs allow concurrent requests to cross ownership boundaries and delete another user’s replacement pet.

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


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

uniqueg and others added 2 commits October 18, 2026 01:32
- 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
@uniqueg
uniqueg merged commit 14c7164 into dev Oct 18, 2026
13 checks passed
@uniqueg
uniqueg deleted the docs/petstore-access-control branch October 18, 2026 00:19
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.

Self assigning owner permissions for a given resource Implement access control config client to setup default permissions in petstore

2 participants