Skip to content

feat(access-control): add role controllers - #382

Merged
uniqueg merged 18 commits into
devfrom
feat/resource-role-controllers
Oct 22, 2026
Merged

uniqueg merged 18 commits into
devfrom
feat/resource-role-controllers

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds optional controllers for managing roles on owned resources, built on the ownership helpers from #378:

  • foca.security.access_control.ownership_server with getResourceRoles, putUserRole, deleteUserRole, putGroupRole and deleteGroupRole, all logged like the permissions API.
  • The resource is derived from the matched route: the subject is the last path parameter, and the resource ends at the parameter before it. Apps route their own operations (e.g. /tasks/{id}/permissions/users/{userId}) to the controllers. Connexion 2 needs unique operationIds, so apps alias or wrap them.
  • Resources without owners give 404, bad bodies give 400, and the last owner cannot be removed (409). Group roles can only be granted by group members or admins. ValueError messages are only logged, because they may name configuration options.
  • Apps can pass an existence check as exists through a wrapper. The role is revoked again if the resource was deleted meanwhile; exists is therefore reserved and must not be the name of a path parameter.
  • Docs: "Endpoints for managing roles" in docs/access-control.md (table, spec and policy examples, wrapper example) and an entry in docs/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: pass
  • mypy: no issues in 75 source files
  • coverage run --source foca -m pytest: 1514 passed, 100% coverage (MongoDB 7 locally)
  • mkdocs build --strict: pass
  • CI: all checks pass (unit tests on Python 3.11 to 3.14 with MongoDB 7.0 and 8.0, lowest dependencies, petstore integration and chart tests, docs, Codecov). After the Sourcery fixes, the chart test pod on kind failed once right after rollout (it had passed on the previous commit; the change does not touch the petstore app) and passed on re-run.

Declined review findings

  • Deriving whether a resource exists from its owners alone: removed after review; apps pass exists instead, because ownerless resources may still exist.
  • Atomic grants and revocations: the policy store has no transactions (as declined in feat(access-control): add ownership helpers #378).
  • Sourcery: binding role changes to resource generations (no generation identifiers in FOCA, as in feat(access-control): add ownership helpers #378).
  • Sourcery: logging failed responses in the traffic-logging decorator (shared with the permissions API; errors are logged by the exception handler).
  • Listings by a service client acting for a user show the client's resources, not the user's: out of scope here, left for a follow-up if needed.

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:

  • Add optional controllers for listing, granting, and revoking user and group roles on owned resources.
  • Support route-derived resources and subjects, configurable existence checks, group-membership restrictions, traffic logging, and documented API integration.

Bug Fixes:

  • Prevent failed or repeated role grants and restored owners from being incorrectly revoked when resource existence checks fail.

Documentation:

  • Document the ready-made role-management controllers, routing requirements, policies, wrappers, responses, and reference API.

Tests:

  • Add comprehensive controller coverage for user and group roles, route parsing, validation, ownership constraints, existence checks, authorization, and traffic logging.

uniqueg and others added 16 commits October 22, 2026 03:30
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

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

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

State diagram for owner restoration during existence checks

stateDiagram-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 --> [*]
Loading

Flow diagram for route-based role controller validation

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

File-Level Changes

Change Details Files
Added ready-made, route-derived controllers for listing, granting, and revoking user and group roles on owned resources.
  • Derives resources and subjects from Flask route parameters, including nested resources and slash-containing groups.
  • Validates role request bodies and maps ownership, subject, group-membership, last-owner, and missing-resource cases to API responses.
  • Supports optional existence checks to clean up grants when resources are deleted concurrently.
  • Applies permissions-API traffic logging to all controllers and documents operation aliasing for unique Connexion operation IDs.
foca/security/access_control/ownership_server.py
tests/security/access_control/test_ownership_server.py
docs/access-control.md
docs/reference.md
Corrected owner restoration behavior when an existence check fails.
  • Added a configurable revoke-on-error behavior to the internal grant helper.
  • Preserves a restored owner if the existence check raises, while still revoking it when the resource is confirmed deleted.
  • Added regression coverage for failed and negative existence checks during restoration.
foca/security/access_control/ownership.py
tests/security/access_control/test_ownership_server.py

Possibly linked issues


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 (be98454) to head (c48ed06).

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     
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 02:26

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


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

uniqueg and others added 2 commits October 22, 2026 04:32
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]>
@uniqueg
uniqueg merged commit 58e18e4 into dev Oct 22, 2026
15 checks passed
@uniqueg
uniqueg deleted the feat/resource-role-controllers branch October 22, 2026 02:44
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