Repository navigation
feat(access-control): add role controllers - #382
Conversation
Add foca.security.access_control.ownership, extracted from cloud-registry's permissions module: the creator of a resource becomes its owner (the user an allowed service client acts for, else the client, else the user), roles of the new option `resource_roles` (default owner and maintainer) are granted to and revoked from users, groups and service clients, the last owner can't be removed (LastOwner, 409), with owners removed concurrently restored, and listings are filtered to the caller's resources unless it is an admin. Role changes are logged for auditing. Refs #341, #354 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add a "Resource ownership" section to the access control guide, the `resource_roles` option to the configuration and migration guides, and the ownership module to the API reference. Refs #341, #354 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review findings on the ownership helpers: - Reject roles for groups while group claim values aren't used as subjects, and for clients that aren't service clients, so that a resource can't be left with owners that never apply. - Reject `admin` in `resource_roles`. - Let `add_owner()` check users named in request fields (`on_behalf_of`). - Load the rules once per `list_roles()` call. - Document deleting resources, `exists` and the costs, and test `revoke_roles()` with `exists`. Refs #341, #354 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the second review round: - Count only owners whose role applies for the last-owner rule. - Reject `add_owner()` calls with both `subject` and `on_behalf_of`. - Test duplicate rules in `list_roles()` and `on_behalf_of` with the header. - Document the trade-off of revoking roles before deleting, and don't send error messages naming options to clients in the example. Refs #341, #354 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Service clients are tied to issuers since #376, so the claims of the ownership tests name the trusted issuer. Refs #341, #354 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add foca.security.access_control.ownership_server with controllers that apps route to from their own specifications to list, grant and revoke roles of users and groups on owned resources, like cloud-registry's permission endpoints. Resource and subject are taken from the route; resources without owners are not found, roles granted on resources deleted meanwhile are revoked again, and only members (or admins) may grant roles to a group. Closes #341, #355 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document the ready-made controllers for managing roles on resources, with a specification snippet and the policies apps need, and add them to the API reference. Refs #341, #355 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address Sourcery's review: - Revoke a granted role again if the existence check raises. - Don't grant non-owner roles on resources without owners. - Document that `resource_filter()` selects by identifier only, and what concurrent or failing requests can leave behind. Refs #341, #354 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review findings on the role controllers: - Replace the owner-based guess whether a resource was deleted, which missed deletions and could revoke the only owner during a hand-over, by an optional `exists` argument that apps pass via wrappers. - Parse routes once. - Test traffic logging, invalid bodies, misconfigured routes and the group cases, and document enums, layouts and responses. Refs #341, #355 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…trollers # Conflicts: # docs/access-control.md # docs/reference.md
Keep owners restored after a revocation if the existence check of the resource fails, so that the resource is not left without owners. Return 404 instead of 400 if a resource is deleted while a role is granted. Document that `exists` is reserved by the role controllers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideIntroduces optional Flask/Connexion controllers for role management on owned resources, with route-based resource resolution, validation, authorization constraints, logging, existence-check handling, and comprehensive API/documentation coverage; also fixes restoration of owners when existence checks fail. Sequence diagram for role management controllerssequenceDiagram
actor Caller
participant Connexion
participant ownership_server
participant Ownership
participant PolicyStore
Caller->>Connexion: PUT /tasks/{id}/permissions/users/{userId}
Connexion->>ownership_server: putUserRole(body, exists)
ownership_server->>ownership_server: _get_resource(true)
ownership_server->>ownership_server: _get_subject()
ownership_server->>Ownership: grant_role(resource, subject, role, exists)
Ownership->>PolicyStore: add_resource_role()
Ownership->>Caller: 200 granted role
Caller->>Connexion: DELETE /tasks/{id}/permissions/groups/{group}
Connexion->>ownership_server: deleteGroupRole(exists)
ownership_server->>Ownership: revoke_roles(resource, group, exists)
Ownership->>PolicyStore: remove resource roles
Ownership->>Caller: 200 revoked subject
State diagram for owner restoration during existence checksstateDiagram-v2
[*] --> OwnerMissing
OwnerMissing --> RestoreOwner: _restore_owner_if_none
RestoreOwner --> ExistsCheck: _grant(revoke_on_error=false)
ExistsCheck --> OwnerRestored: exists() true
ExistsCheck --> ResourceDeleted: exists() false
ExistsCheck --> OwnerRestored: exists() raises
ResourceDeleted --> RoleRevoked
OwnerRestored --> [*]
RoleRevoked --> [*]
Flow diagram for route-based role controller validationflowchart TD
Request[Role management request] --> Route[Resolve resource and subject from matched route]
Route --> Owned{Resource has owners?}
Owned -- No --> NotFound[404 NotFound]
Owned -- Yes --> Operation{Grant or revoke?}
Operation -- Grant --> Body[Read role from request body]
Body --> Valid{Role is grantable?}
Valid -- No --> BadRequest[400 BadRequest]
Valid -- Yes --> Group{Group grant?}
Group -- Yes --> Member{Caller is group member or admin?}
Member -- No --> Forbidden[403 Forbidden]
Member -- Yes --> Grant[grant_role]
Group -- No --> Grant
Operation -- Revoke --> Revoke[revoke_roles]
Grant --> Exists{exists check supplied and resource remains?}
Exists -- No --> ResourceGone[404 NotFound and revoke granted role]
Exists -- Yes --> Success[Return role result]
Revoke --> Success
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 #382 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 26 27 +1
Lines 2337 2419 +82
=========================================
+ Hits 2337 2419 +82
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 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/security/access_control/ownership_server.py" line_range="200" />
<code_context>
+ role = _get_role(body)
+ resource = _get_owned_resource(with_subject=True)
+ try:
+ grant_role(resource, subject, role, subject_type=subject_type, exists=exists)
+ # Messages may name configuration options, so they are only logged
+ except ValueError as exc:
</code_context>
<issue_to_address>
**Stale requests mutate replacement roles**
When a resource identifier is reused while a role request authorized against the prior resource is in flight, the original resource is deleted and its identifier reused after a controller checks its owners but before it changes roles. The stale `PUT` can grant a role to the replacement, or the stale `DELETE` can revoke a role from it, so the replacement ends with permissions from an operation authorized for the prior resource.
Bind each role mutation to the resource generation it was authorized for, or prevent identifier reuse until in-flight role requests have completed.
Also at `foca/security/access_control/ownership_server.py:240`.
</issue_to_address>
### Comment 2
<location path="foca/security/access_control/ownership_server.py" line_range="269" />
<code_context>
+
+@log_traffic_if(_permissions_traffic_logged)
+def putUserRole(
+ body: Any = None,
+ exists: Callable[[], bool] | None = None,
+ **kwargs: Any,
</code_context>
<issue_to_address>
**PUT requests cannot grant roles**
When a PUT route uses `body` as a path-parameter name, connexion supplies both the path parameter and JSON payload to `putUserRole()` or `putGroupRole()` under `body`, so the controller or a wrapper receives the wrong value or cannot perform its existence check; the grant fails.
Give the JSON payload and path parameter distinct controller argument names.
Also at `foca/security/access_control/ownership_server.py:312-314`, `docs/access-control.md:846-847`.
</issue_to_address>
### Comment 3
<location path="foca/security/access_control/ownership.py" line_range="442" />
<code_context>
subject_type: SubjectType,
ptype: str,
exists: Callable[[], bool] | None,
+ revoke_on_error: bool = True,
) -> None:
"""Grant a subject a role on a resource, unless it was deleted.
</code_context>
<issue_to_address>
**Failed retries revoke existing roles**
When a subject already has a role and the controller’s `exists` check raises during a repeated grant of that role, `_grant` does not distinguish a newly added role from one already present: when `exists` raises, its cleanup removes the role either way. A repeated `PUT` for an existing sole owner therefore leaves the resource ownerless, and the caller sees an error while subsequent role-management requests see `404`.
Track whether this call added the role, and only roll it back on an existence-check failure when it did.
Also at `foca/security/access_control/ownership_server.py:200`.
</issue_to_address>
### Comment 4
<location path="foca/security/access_control/ownership_server.py" line_range="245" />
<code_context>
+ return subject
+
+
+@log_traffic_if(_permissions_traffic_logged)
+def getResourceRoles(**kwargs: Any) -> list[dict[str, str]]:
+ """List the roles granted on the resource of the route.
</code_context>
<issue_to_address>
**Failed calls lack response logs**
When a role controller raises an HTTP or dependency exception while traffic logging is enabled, `log_traffic` invokes each controller before logging its response, so a raised 4xx/5xx exception exits the wrapper without recording the response status; operators see an incoming-request log but no corresponding failure response for these endpoints.
Log the exception or its resulting HTTP status in the traffic-logging path before propagating or handling it.
Also at `foca/security/access_control/ownership_server.py:267`, `foca/security/access_control/ownership_server.py:294`, `foca/security/access_control/ownership_server.py:310`, `foca/security/access_control/ownership_server.py:350`.
</issue_to_address>
### Comment 5
<location path="tests/security/access_control/test_ownership_server.py" line_range="307-309" />
<code_context>
+ "token_info": mock_token_info("alice")
+ }
+ with pytest.raises(NotFound):
+ put(body={"role": "maintainer"}, exists=lambda: False)
+ put(body={"role": "maintainer"}, exists=lambda: True)
+ assert _roles(app)[-1] == ResourceRole(subject_type, "devs", "maintainer")
+
+ def test_existence_checked_on_restore(self, app: Flask) -> None:
</code_context>
<issue_to_address>
**Failed existence check is masked**
When the `exists=lambda: False` grant leaves its role in the policy store, `TestUserRoles.test_existence_checked` retries the same grant with `exists=lambda: True` at line 308 and only checks that the role is present at line 309. A role left behind by the failed check therefore makes the test pass.
Assert that the role is absent immediately after the expected `NotFound`, before retrying the grant.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 5 findings to address first, and if a controller derives the wrong resource or subject, it could grant access to the wrong identity or revoke someone’s access; the resulting role rules persist after a revert, and any data exposed before cleanup cannot be undisclosed. Reverting stops future controller calls but does not remove roles already written.
Blocking findings: foca/security/access_control/ownership_server.py:200, foca/security/access_control/ownership_server.py:269, foca/security/access_control/ownership.py:442, foca/security/access_control/ownership_server.py:245, tests/security/access_control/test_ownership_server.py:309
Revoke roles again after a failing existence check only if the call granted them, so that repeating a grant of an existing role cannot leave a resource without owners. Document that `body` is reserved by the role controllers, and check that roles on deleted resources are revoked before granting them again in tests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Adds optional controllers for managing roles on owned resources, built on the ownership helpers from #378:
foca.security.access_control.ownership_serverwithgetResourceRoles,putUserRole,deleteUserRole,putGroupRoleanddeleteGroupRole, all logged like the permissions API./tasks/{id}/permissions/users/{userId}) to the controllers. Connexion 2 needs unique operationIds, so apps alias or wrap them.ValueErrormessages are only logged, because they may name configuration options.existsthrough a wrapper. The role is revoked again if the resource was deleted meanwhile;existsis therefore reserved and must not be the name of a path parameter.docs/access-control.md(table, spec and policy examples, wrapper example) and an entry indocs/reference.md.Fix to #378
_grant()revoked a role again whenever the existence check raised, also for restored owners and for roles granted before (repeated grants), which could leave a resource without owners. It now revokes only roles it granted itself, and never restored owners.Verification
ruff check,ruff format --check: passmypy: no issues in 75 source filescoverage run --source foca -m pytest: 1514 passed, 100% coverage (MongoDB 7 locally)mkdocs build --strict: passDeclined review findings
existsinstead, because ownerless resources may still exist.Open questions
None.
Closes #341
Closes #355
🤖 Generated with Claude Code
Summary by Sourcery
Provide ready-made role-management controllers for owned resources while preserving ownership when existence checks fail.
New Features:
Bug Fixes:
Documentation:
Tests: