Skip to content

fix: let admins manage ownerless resources - #666

Merged
uniqueg merged 4 commits into
devfrom
fix/608-admins-manage-ownerless
Nov 4, 2026
Merged

uniqueg merged 4 commits into
devfrom
fix/608-admins-manage-ownerless

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Resources stored before an app adopted ownership have no owners, so the role controllers respond with 404 and nobody can assign the first owner via the API.

  • getResourceRoles, putUserRole and putGroupRole: if the caller is an admin and the existence check passed as exists finds the resource, the operation works on a resource without owners. getResourceRoles takes exists as a new optional argument.
  • Other callers, operations without an existence check and resources that don't exist get the same responses as before. Resources with owners work as before, and the check isn't called to find them.
  • The DELETE operations don't change.
  • The access control example routes getPetRoles to a wrapper with the check. Docs: new section "Adopting ownership in an existing app".

Closes #608

Verification

  • ruff check, ruff format --check, mypy, ast-grep scan, mkdocs build --strict: pass.
  • coverage run -m pytest with MongoDB 7.0: 3387 passed, 1 skipped, 100% coverage.
  • Both reviewer subagents, one round: only low findings, all fixed.
  • CI: see the checks of this PR.

🤖 Generated with Claude Code

Summary by Sourcery

Enable administrators to recover and assign ownership of existing ownerless resources through the permissions API.

New Features:

  • Allow admins to list roles and assign the first owner on existing resources that currently have no owners when an application provides an existence check.

Bug Fixes:

  • Restore API management of resources created before ownership was adopted instead of incorrectly returning 404 for administrators.

Enhancements:

  • Update the petstore access-control example to support administrative management of ownerless pets.
  • Document how applications can adopt ownership for existing ownerless resources while preserving existing behavior for other callers and operations.

Documentation:

  • Add guidance for adopting ownership in an existing application and clarifying administrator access to ownerless resources.

Tests:

  • Add coverage for administrative access, first-owner assignment, missing resources, unchanged owned resources, policy enforcement, and deletion races.

Resources stored before an app adopted ownership have no owners, so the
role controllers didn't find them and nobody could assign the first
owner via the API. If the operation passes an existence check, admins
can now list the roles of such resources and assign owners. Everyone else
still gets the same responses, as do admins if the resource doesn't
exist. DELETE doesn't change.

Closes #608

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR enables admins to adopt legacy ownerless resources through existence-aware role controllers: admins can list roles and assign the first owner when the application confirms the resource exists, while existing behavior for other callers, owned resources, missing resources, and DELETE operations remains unchanged.

Sequence diagram for admin ownership adoption

sequenceDiagram
    actor Admin
    participant API
    participant Controller
    participant Exists as ResourceExistenceCheck
    participant Roles as RoleStore

    Admin->>API: GET permissions or PUT owner role
    API->>Controller: getResourceRoles or putUserRole
    Controller->>Roles: _get_owners
    Roles-->>Controller: No owners
    Controller->>Exists: exists()
    Exists-->>Controller: Resource exists
    Controller->>Roles: list_roles or grant_role
    Roles-->>Controller: Roles or owner assignment
    Controller-->>API: Success
Loading

File-Level Changes

Change Details Files
Allow admins to discover and initialize ownership for existing resources that currently have no owners, while preserving existing authorization and deletion behavior.
  • Add an optional existence callback to resource-role listing and ownership-grant flows.
  • Treat an ownerless resource as manageable only when the caller is an admin and the callback confirms existence.
  • Permit the first assigned role to be an owner, including group ownership, while retaining post-grant deletion checks and prior error behavior.
  • Keep existence checks lazy: skip them for resources with owners and for non-admin callers.
foca/security/access_control/ownership_server.py
Update the access-control example and documentation to show how applications can adopt ownership for legacy resources.
  • Wrap role-listing and role-grant routes with resource-specific existence checks.
  • Document admin-only adoption, expected responses, and unchanged DELETE semantics.
  • Explain that existence-aware wrappers are required for legacy ownerless resources.
examples/petstore-access-control/controllers.py
docs/access-control.md
Add comprehensive coverage for ownerless-resource adoption and regression behavior.
  • Test admin listing and first user/group owner assignment.
  • Verify non-owner roles, missing resources, absent checks, non-admin callers, and policy enforcement responses.
  • Verify resources with owners skip existence checks, deletion behavior remains unchanged, and concurrent removal revokes newly granted roles.
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 Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (e0ee433) to head (108b088).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #666   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        56           
  Lines         7228      7230    +2     
=========================================
+ Hits          7228      7230    +2     
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 November 4, 2026 03: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 4 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="192-193" />
<code_context>
+        Whether the resource has owners (whose role applies) or, if not, the
+        caller is an admin and `exists` finds the resource.
+    """
+    return bool(_get_owners(resource, RESOURCE_ROLE_PTYPE)) or (
+        exists is not None and is_admin() and exists()
+    )
+
</code_context>
<issue_to_address>
**Interrupted grant leaves phantom owner**

When the resource is deleted and the worker stops after the first owner role is persisted but before the post-grant existence check and cleanup, `grant_role` persists the owner role before its post-grant existence check, so process termination in that gap leaves the role behind. `_is_manageable` then treats the resource as manageable from that owner role without calling `exists`; a later resource reusing the same path inherits the stale ownership and permissions.

Make resource deletion and role cleanup crash-safe, for example with a durable cleanup/reconciliation mechanism or a transaction covering both stores.
</issue_to_address>

### Comment 2
<location path="foca/security/access_control/ownership_server.py" line_range="271" />
<code_context>
     """
     role = _get_role(body)
-    resource = _get_owned_resource(with_subject=True)
+    resource = _get_owned_resource(with_subject=True, exists=exists)
     try:
         grant_role(resource, subject, role, subject_type=subject_type, exists=exists)
</code_context>
<issue_to_address>
**Failed grant removes concurrent owner**

When two admin requests grant the same first owner and the resource is deleted and recreated between their existence checks, `_grant` removes the exact role whenever its existence check returns `False`, even if another request has since reused that same role and its own check succeeds. If two admins grant the same first owner while the resource is deleted and recreated between checks, one request returns success but its owner rule is removed, leaving the existing resource ownerless.

Make rollback conditional on the grant instance that failed, or coordinate concurrent grants and their existence checks so a failed request cannot remove a successful request's role.
</issue_to_address>

### Comment 3
<location path="foca/security/access_control/ownership_server.py" line_range="321" />
<code_context>
 @_require_enforcement
-def getResourceRoles(**kwargs: Any) -> list[dict[str, str]]:
+def getResourceRoles(
+    exists: Callable[[], bool] | None = None, **kwargs: Any
+) -> list[dict[str, str]]:
     """List the roles granted on the resource of the route.
</code_context>
<issue_to_address>
**Ownerless role lists return 500**

When an admin lists an ownerless resource on a route with a path parameter named `exists`, connexion binds the path value to `getResourceRoles`’s `exists` parameter, so `_is_manageable` calls that string as a callback and raises `TypeError` instead of returning the role list.

Rename the callback parameter and update its callers so a route parameter named `exists` cannot bind to it.
</issue_to_address>

### Comment 4
<location path="examples/petstore-access-control/controllers.py" line_range="202" />
<code_context>
+    Returns:
+        Subject type, subject and role of each role granted on the pet.
+    """
+    return ownership_server.getResourceRoles(exists=_pet_exists(id), id=id, **kwargs)


</code_context>
<issue_to_address>
**Example spec excludes admin access**

The example’s OpenAPI descriptions still say the role endpoints are for “owners only” (`examples/petstore-access-control/petstore-access-control.yaml:169` and `:214-216`), while these wrappers now let admins list roles and assign the first owner on existing ownerless pets. Users of the served specification are told that supported admin operations are unavailable.

Update the example OpenAPI descriptions to mention admins when the existence check confirms the pet exists.

Also at `foca/security/access_control/ownership_server.py:271`.
</issue_to_address>

Linked issues

#608 fix(access-control): let admins manage ownerless · 6 of 6 met

# Requirement Status Notes
1 Admins can list roles and grant the first owner on an existing ownerless resource. ✅ Met The existence-aware controllers support listing and granting user or group ownership; tests cover listing, both owner types, and refusal of a non-owner role as the first grant.
2 Non-admins get 404 for ownerless resources. ✅ Met A test confirms a non-admin gets 404 when policies allow the request through; requests denied by policy still receive 403.
3 Missing resources get 404. ✅ Met Tests cover admin listing and granting against a resource the existence check does not find.
4 Existing behavior for resources with roles is unchanged. ✅ Met A test verifies existing roles remain accessible and the existence check is not called when the resource already has an owner.
5 100% coverage. ✅ Met Coverage is configured to fail below 100%, and the PR verification reports a passing test run with 100% coverage.
6 Document adopting ownership in an existing app on the access-control page. ✅ Met The new section explains how to wrap the role controllers with existence checks and describes the resulting behavior.

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and an admin can now inspect roles on an existing ownerless resource and assign its first owner, which can enable that owner to access the resource. Reverting stops the new behavior, but it cannot undo any access or data exposure that occurred before the grant is removed.

Blocking findings: foca/security/access_control/ownership_server.py:193, foca/security/access_control/ownership_server.py:271, foca/security/access_control/ownership_server.py:321


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

@uniqueg
uniqueg merged commit af4a738 into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the fix/608-admins-manage-ownerless branch November 4, 2026 04:38
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.

fix(access-control): let admins manage ownerless

1 participant