Repository navigation
fix: pre-release review low findings - #391
Conversation
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]>
Reviewer's GuideThis 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 managementsequenceDiagram
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
Flow diagram for Swagger UI and specification validationflowchart 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]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #391 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 27 27
Lines 2487 2510 +23
=========================================
+ Hits 2487 2510 +23
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.
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
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]>
Summary
Fixes the remaining low findings of the FOCA 0.16.0 pre-release review.
get_collection()doc examples (docs/access-control.md): they now passdbandcollection. They passed the collection only, which raisesTypeError.500):serve_spec: false(oroptions: {serve_spec: false}, or Connexion's deprecatedswagger_json: false) inapi.specs[].connexion, the UI is disabled too.swagger_ui: truetogether with a disabled spec is rejected on config validation. Unset (None) options are ignored, as Connexion does.security.access_control.api_swagger_ui: truealso serves the specification of the permissions API.api_serve_spec: false, when set explicitly, is then rejected.docs/configuration/api.md,docs/access-control.md, and a behaviour change note indocs/migration-0.16.md.examples/petstore-access-controluses the 0.16 ownership API:add_owner()makes creators owners. It also works for users that the new example service clientpet-shopacts for (X-On-Behalf-Of).resource_filter()filters the listing./pets/{id}/permissions[/users/{userId}]are routed toownership_servervia an alias and wrappers with existence checks.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.yamlhas the same version.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): cleancoverage run -m pytest(Python 3.13, MongoDB 7.0 via mise on port 12345): 1572 passed, coverage 100%--resolution lowest-direct): 1570 passed, 1 skippedmkdocs build --strict: OK0.17.1=0.17.1). actionlint reports only the info-level SC2102 thatdevalready has.swagger_jsonandNoneoptions, the duplicated UI option logic, the untested existence checks, docstring wording, link order, and exact load counts in the docs.addPetnow removes them, covered bytest_pet_not_stored). Answered: concurrent role replacements may keep both roles; the race is in FOCA'sgrant_role(), out of scope here and benign.Declined review findings
deletePetleaves the pet without owners if deleting from MongoDB fails after the roles were removed. It is documented in the example, as in the docs'DeleteTaskpattern; admins can still delete the pet. Restoring all roles on failure would complicate the template.deletePetUserRole's existence check.deleteUserRole()only usesexistswhen 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._pet_existsin the wrappers (quality reviewer): kept as a helper, as the new smoke test patches it.🤖 Generated with Claude Code