Skip to content

fix: pre-release review low findings - #391

Merged
uniqueg merged 8 commits into
devfrom
fix/prr-low
Oct 22, 2026
Merged

uniqueg merged 8 commits into
devfrom
fix/prr-low

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes the remaining low findings of the FOCA 0.16.0 pre-release review.

  1. get_collection() doc examples (docs/access-control.md): they now pass db and collection. They passed the collection only, which raises TypeError.
  2. Swagger UI without its specification (it returned 500):
    • With serve_spec: false (or options: {serve_spec: false}, or Connexion's deprecated swagger_json: false) in api.specs[].connexion, the UI is disabled too.
    • swagger_ui: true together with a disabled spec is rejected on config validation. Unset (None) options are ignored, as Connexion does.
    • security.access_control.api_swagger_ui: true also serves the specification of the permissions API. api_serve_spec: false, when set explicitly, is then rejected.
    • Docs: docs/configuration/api.md, docs/access-control.md, and a behaviour change note in docs/migration-0.16.md.
  3. examples/petstore-access-control uses the 0.16 ownership API:
    • add_owner() makes creators owners. It also works for users that the new example service client pet-shop acts for (X-On-Behalf-Of).
    • resource_filter() filters the listing.
    • Role endpoints /pets/{id}/permissions[/users/{userId}] are routed to ownership_server via an alias and wrappers with existence checks.
    • New policies for owners and maintainers.
    • Updated README and model comments.
    • The smoke test is extended: listings, role management, last owner, roles on deleted pets, on-behalf-of.
  4. ruff and mypy pinned for CI in requirements/lint.txt (with the type stubs). Dependabot already covers /requirements, and ruff gets its own group. The lint job installs the pins and checks that the ruff hook in .pre-commit-config.yaml has the same version.
  5. Per-request policy loads of the role endpoints: documented in the scaling notes. I didn't reuse one enforcer per request (flask.g), because the ownership helpers deliberately reload rules after changes to notice concurrent ones (last-owner restore, existence checks); a cached enforcer would hide those changes. Measured loads: GET 3, PUT 5 to 7, DELETE 6 to 7.

Closes #388

Verification

  • ruff check, ruff format --check, mypy (strict): clean
  • coverage run -m pytest (Python 3.13, MongoDB 7.0 via mise on port 12345): 1572 passed, coverage 100%
  • Lowest direct dependencies (Python 3.11, --resolution lowest-direct): 1570 passed, 1 skipped
  • mkdocs build --strict: OK
  • The pre-commit ruff version check was run locally (0.17.1 = 0.17.1). actionlint reports only the info-level SC2102 that dev already has.
  • Reviews: adversarial-reviewer (2 rounds) and quality-reviewer, no high findings.
    • Fixed: example resource paths without the API base path, Dependabot updates of ruff failing the new check, swagger_json and None options, the duplicated UI option logic, the untested existence checks, docstring wording, link order, and exact load counts in the docs.
  • Sourcery review: 2 threads. Fixed: owner roles left behind when storing a new pet fails (addPet now removes them, covered by test_pet_not_stored). Answered: concurrent role replacements may keep both roles; the race is in FOCA's grant_role(), out of scope here and benign.
  • CI: all checks green on 7a52d3e (unit tests on Python 3.11 to 3.14 with MongoDB 7.0 and 8.0, lowest dependencies, petstore integration tests, charts and kind install, lint, docs, Codecov, Sourcery)

Declined review findings

  • deletePet leaves the pet without owners if deleting from MongoDB fails after the roles were removed. It is documented in the example, as in the docs' DeleteTask pattern; admins can still delete the pet. Restoring all roles on failure would complicate the template.
  • No test of deletePetUserRole's existence check. deleteUserRole() only uses exists when it restores an owner removed by a concurrent request, which the smoke test can't trigger without mocking FOCA internals. FOCA's own tests cover that path.
  • Inlining _pet_exists in the wrappers (quality reviewer): kept as a helper, as the new smoke test patches it.
  • Commit subject "docs: give policy loads of role endpoints": left as is; the commits are squashed.

🤖 Generated with Claude Code

uniqueg and others added 7 commits October 22, 2026 06:41
The Swagger UI returned 500 unless the specification was served too,
e.g., with serve_spec: false (the UI is on by default) or with
api_swagger_ui: true without api_serve_spec. The UI is now disabled
when serving the specification is disabled, enabling the UI while
disabling the specification is rejected on validation, and
api_swagger_ui: true also serves the permissions API specification.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
get_collection() takes the database and the collection; the access
control examples passed the collection only, which raises TypeError.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Switch the access control example from the 0.15 resource role helpers to
the 0.16 ownership API: add_owner() for creators (also for users a
service client acts for), resource_filter() for listings, and role
management endpoints routed to the ownership_server controllers, with
existence checks. Configure a service client allowed to act for users
and extend the smoke test (role management, last owner, on-behalf-of).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ruff, mypy and the type stubs were unpinned in CI and could differ from
the ruff hook pinned in .pre-commit-config.yaml, so lint results could
not be reproduced from a tag. Pin them in requirements/lint.txt, which
Dependabot already updates (pip, /requirements), and check in the lint
job that the pre-commit ruff hook has the same version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Requests to the role endpoints load all policy rules several times
(GET 3, PUT and DELETE 5 to 7, measured), as the ownership helpers
reload them after changes to notice concurrent ones. Reusing one
enforcer per request would hide those changes, so document the cost in
the scaling notes instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Treat Connexion's deprecated swagger_json option like serve_spec, in
  one private helper used by validation and the add_api() arguments.
- Example: take the pets' resource path from the request again, so that
  it includes the API's base path; note that a failed delete leaves the
  pet without owners; test the existence checks of the role wrappers.
- Give ruff its own Dependabot group, as its pre-commit hook must be
  updated in the same pull request.
- Don't give exact policy load counts in the scaling docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Connexion drops None values of its options, so an empty swagger_ui or
serve_spec in options must not count as set when deciding whether the
Swagger UI can be served.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR resolves the remaining 0.16.0 pre-release findings by coupling Swagger UI availability to its specification, completing the petstore example’s resource-ownership and role-management integration, pinning lint tooling in CI, and updating tests and documentation for the new behavior and policy-loading costs.

Sequence diagram for pet ownership and role management

sequenceDiagram
    actor User
    participant API as Petstore API
    participant Controller as controllers.py
    participant Ownership as ownership_server
    participant Policy as Access control policy
    participant MongoDB

    User->>API: POST /pets
    API->>Controller: addPet(pet)
    Controller->>Ownership: add_owner(resource)
    Ownership->>Policy: Add owner role
    Controller->>MongoDB: insert_one(pet)
    API-->>User: Created pet

    User->>API: GET /pets
    API->>Controller: findPets()
    Controller->>Policy: resource_filter(_pets_path())
    Policy-->>Controller: Resource identifiers
    Controller->>MongoDB: find(filtered pets)
    API-->>User: Accessible pets

    User->>API: PUT /pets/{id}/permissions/users/{userId}
    API->>Controller: putPetUserRole(id)
    Controller->>Ownership: putUserRole(exists=_pet_exists(id))
    Ownership->>Policy: Enforce owner access and grant role
    Ownership->>MongoDB: Check pet existence
    API-->>User: Granted role

    User->>API: DELETE /pets/{id}/permissions/users/{userId}
    API->>Controller: deletePetUserRole(id)
    Controller->>Ownership: deleteUserRole(exists=_pet_exists(id))
    Ownership->>Policy: Revoke role, preserve last owner
    API-->>User: Revoked roles
Loading

Flow diagram for Swagger UI and specification validation

flowchart TD
    Config[Connexion configuration] --> SpecDisabled{serve_spec or swagger_json disabled?}
    SpecDisabled -->|No| UISetting{swagger_ui enabled?}
    SpecDisabled -->|Yes| UIExplicit{swagger_ui explicitly enabled?}
    UIExplicit -->|Yes| Reject[Reject configuration]
    UIExplicit -->|No| DisableUI[Disable Swagger UI]
    UISetting -->|Yes| ServeBoth[Serve Swagger UI and specification]
    UISetting -->|No| SpecOnly[Serve specification according to configuration]

    AccessConfig[Permissions API configuration] --> AccessUI{api_swagger_ui enabled?}
    AccessUI -->|No| AccessSpec[Use api_serve_spec]
    AccessUI -->|Yes| AccessSpecSet{api_serve_spec explicitly false?}
    AccessSpecSet -->|Yes| AccessReject[Reject configuration]
    AccessSpecSet -->|No| AccessBoth[Serve permissions UI and specification]
Loading

File-Level Changes

Change Details Files
Harden Swagger UI/specification configuration so the UI cannot be exposed without its required OpenAPI document.
  • Treat explicit serve_spec and deprecated swagger_json options consistently, including nested options and None values.
  • Reject configurations that enable the UI while disabling the specification; automatically disable the UI when only the specification is disabled.
  • Apply the same coupling to the access-control permissions API and cover the behavior with tests and migration/configuration docs.
foca/models/config.py
foca/api/register_openapi.py
foca/security/access_control/register_access_control.py
tests/api/test_register_openapi.py
tests/security/access_control/test_enforcement.py
docs/configuration/api.md
docs/access-control.md
docs/migration-0.16.md
Modernize the petstore access-control example around FOCA 0.16 resource ownership and role-management helpers.
  • Use add_owner, resource_filter, and remove_resource for creation, filtered listings, and deletion cleanup.
  • Route permission endpoints through ownership_server wrappers with pet existence checks and policies for owners and maintainers.
  • Add trusted pet-shop on-behalf-of behavior, update OpenAPI/README/configuration, and expand smoke coverage for role management, last-owner protection, deletion races, and service-client actions.
examples/petstore-access-control/controllers.py
examples/petstore-access-control/config.yaml
examples/petstore-access-control/petstore-access-control.yaml
examples/petstore-access-control/petstore_policies.conf
examples/petstore-access-control/README.md
tests/examples/test_petstore_access_control.py
Make lint CI tooling reproducible and keep Ruff versions synchronized across CI and pre-commit.
  • Pin Ruff, mypy, and required stubs in a dedicated lint requirements file.
  • Install the pinned tools in CI and fail when the pre-commit Ruff revision differs.
  • Separate Ruff Dependabot updates into their own group.
requirements/lint.txt
.github/workflows/checks.yml
.github/dependabot.yml
.pre-commit-config.yaml
Document the additional policy-loading cost of ownership role endpoints and correct access-control collection examples.
  • Fix get_collection() examples to pass database and collection arguments.
  • Explain repeated rule loads required to observe concurrent ownership changes, including the relative GET/PUT/DELETE costs.
docs/access-control.md

Possibly linked issues

  • fix: pre-release review low findings #388: The PR resolves each requested finding: fixes examples, handles Swagger spec dependencies, updates the ownership example, pins lint tools, and documents policy-load costs.

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 22, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #391   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           27        27           
  Lines         2487      2510   +23     
=========================================
+ Hits          2487      2510   +23     
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
uniqueg marked this pull request as ready for review October 22, 2026 05:00

@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 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="examples/petstore-access-control/controllers.py" line_range="120" />
<code_context>
     if "tag" in pet:
         record["tag"] = pet["tag"]
+    # Make the creator the owner of the new pet, before it can be found
+    add_owner(_pet_path(pet_id))
     db_collection.insert_one(record)
     del record["_id"]
</code_context>
<issue_to_address>
**Failed inserts leave orphaned roles**

When mongoDB rejects or fails the pet insert after `add_owner()` succeeds, `add_owner()` has already persisted the ownership rule, so the failed request leaves a rule for a pet that does not exist. Pet IDs are not reused, and the ownership-backed roles endpoint can expose the orphaned pet while stale rules accumulate.

Make creating the pet and its ownership rule atomic, or remove the ownership rule when the insert fails.
</issue_to_address>

### Comment 2
<location path="examples/petstore-access-control/controllers.py" line_range="198-199" />
<code_context>
+    Returns:
+        Subject type (`user`), user identifier and granted role.
+    """
+    role: dict[str, str] = ownership_server.putUserRole(
+        exists=_pet_exists(id), **kwargs
+    )
+    return role
</code_context>
<issue_to_address>
**Concurrent role updates retain both roles**

When two PUT requests concurrently replace roles for the same user on the same pet, `putPetUserRole` delegates replacement to `grant_role`, which removes the subject’s old roles before adding the requested one. Two concurrent PUTs for the same user can interleave so each adds its role after the other’s removal, leaving both roles stored; the roles endpoint then returns a state that neither request would produce sequentially.

Make replacement atomic for a subject/resource pair, or serialize concurrent role updates so only one requested role remains.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and the example now trusts pet-shop to create pets on behalf of any user named in the header, and lets pet owners grant roles that control who can view or manage those pets. If that trust or role policy is wrong, the access decision is effective immediately and may expose pets or leave persistent role grants; reverting the code does not undo grants or disclosures.

Blocking findings: examples/petstore-access-control/controllers.py:120, examples/petstore-access-control/controllers.py:199


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

If storing a new pet fails after its creator was made the owner, remove
the role again, so that no rules are left for pets that don't exist
(Sourcery review of #391).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 66beb4c into dev Oct 22, 2026
15 checks passed
@uniqueg
uniqueg deleted the fix/prr-low branch October 22, 2026 05:10
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.

1 participant