Skip to content

feat(access-control): add ownership helpers - #378

Merged
uniqueg merged 9 commits into
devfrom
feat/resource-ownership
Oct 22, 2026
Merged

uniqueg merged 9 commits into
devfrom
feat/resource-ownership

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Part 1 of #341: helpers that give FOCA apps resource ownership, extracted from cloud-registry's cloud_registry/ga4gh/registry/permissions.py. A follow-up (#355) adds optional ready-made controllers and closes #341.

New module foca.security.access_control.ownership, exported from foca.security.access_control:

  • add_owner(resource, on_behalf_of=None): the creator becomes owner: the user an allowed service client acts for (get_on_behalf_of_user(), feat(auth): support service tokens and roles #340; header or on_behalf_of from a request field), else the service client (client: subject), else the user.
  • grant_role(resource, subject, role, subject_type="user", exists=None): grants a role of the new option security.access_control.resource_roles (default [owner, maintainer], must contain owner, must not contain admin), replacing the subject's other such roles (revoked before granting); returns the previous roles. Roles that would not apply are rejected (ValueError): to groups while group claim values aren't subjects (group_mapping without keep_group_subjects), and to clients that aren't service clients.
  • revoke_roles(resource, subject, subject_type="user", exists=None): revokes them.
  • Both raise LastOwner (a werkzeug Conflict, 409) for the last owner (user, group or client) whose role applies; owners removed by concurrent requests are restored. With exists, roles granted on a resource deleted meanwhile are revoked again (NotFound).
  • list_roles(resource, role=None): users, then groups, then clients, as ResourceRole(subject_type, subject, role).
  • list_subject_roles(prefix) (like cloud-registry's GET /me) and resource_filter(prefix, field="id"): MongoDB filter for owner-filtered listings; {} for admins.
  • is_admin(): role admin from group_mapping, client_mapping or g rules (transitively).

Role changes are logged on INFO for auditing (resource, subject, caller, previous roles). Documented in a new "Resource ownership" section of the access control guide, the configuration page, the migration guide for 0.16 (new option) and the API reference.

Closes #354

Verification

  • coverage run --source foca -m pytest (MongoDB 7.0 on port 12345, Python 3.13): 1450 passed; coverage report: 100%.
  • ruff check, ruff format --check, mypy: clean.
  • mkdocs build --strict: builds.
  • After merging dev (feat(auth): tie service clients to issuers #376 ties service clients to issuers), the test claims name the issuer; 1473 passed locally.
  • CI: all checks pass (unit tests on Python 3.11-3.14 with MongoDB 7.0, lowest direct dependencies, MongoDB 8.0, lint/type-check/build, docs, charts, integration, codecov).

Reviewed by the adversarial and quality reviewer subagents (2 rounds); fixed: roles that would not apply, admin in resource_roles, on_behalf_of, a single policy load in list_roles(), docs examples (deleting, exists, error details), tests for revoke_roles(exists=...) and duplicates.

Declined review findings

  • Rename grant_role/revoke_roles/list_roles to match add_resource_role and friends: the names are those specified in feat(access-control): add resource ownership helpers #354; they differ on purpose (they replace roles, apply the last-owner rule and list typed subjects).
  • Avoid importing private helpers of enforcement.py: same package, as access_control_server.py does.
  • Simulate races without patching _check_other_owners: the patch is the simplest deterministic way to interleave a concurrent removal; commented.
  • Sourcery (fixed in f4095d3: revoke on failing exists, no non-owner grants on ownerless resources, scoped-listing docs). Declined with replies: removing configured rules (they belong to the deployment and are re-added on start), atomic role replacement and crash safety (the policy store has no transactions; revoke-before-grant keeps failures on the safe side; documented), generation identifiers for reused paths (documented remove_resource() before create and around delete).

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Add configurable resource ownership helpers that assign creators as owners, manage applicable roles safely, and scope listings to resources visible to the caller.

New Features:

  • Add resource ownership helpers for assigning creators, managing user/group/service-client roles, preserving the last applicable owner, and filtering resource listings by ownership.
  • Expose admin detection and typed resource-role listings, including support for acting on behalf of users.

Enhancements:

  • Add configurable and validated resource roles, defaulting to owner and maintainer, with safeguards against granting administrative or non-applicable roles.
  • Add INFO-level auditing for ownership and role changes, including handling of concurrent changes and resources deleted during role updates.

Documentation:

  • Document resource ownership usage, configuration, migration guidance, and API reference entries.

Tests:

  • Add comprehensive ownership, role-management, filtering, configuration-validation, concurrency, and resource-existence coverage.

Chores:

  • Export the ownership API from the access-control package and define shared ownership-related role constants.

uniqueg and others added 5 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]>
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds a new ownership layer to FOCA access control: configurable resource roles with safe owner lifecycle operations, support for users/groups/service clients and impersonation, admin-aware listing filters, concurrency/deletion safeguards, auditing, documentation, and extensive tests.

Sequence diagram for resource creation and ownership assignment

sequenceDiagram
    actor Caller
    participant Ownership as ownership
    participant Auth as access_control
    participant Roles as resource_roles

    Caller->>Ownership: add_owner(resource, on_behalf_of)
    Ownership->>Auth: get_on_behalf_of_user(on_behalf_of)
    alt acting for an allowed user
        Auth-->>Ownership: user
    else service client caller
        Ownership->>Auth: get_current_client()
        Auth-->>Ownership: client
    else user caller
        Ownership->>Auth: get_current_subject()
        Auth-->>Ownership: user
    end
    Ownership->>Roles: add_resource_role(resource, owner, subject)
    Roles-->>Ownership: owner granted
    Ownership-->>Caller: ResourceRole(subject_type, subject, owner)
Loading

Sequence diagram for safe resource role replacement

sequenceDiagram
    actor Caller
    participant Ownership as ownership
    participant Roles as resource_roles
    participant Resource as resource_store

    Caller->>Ownership: grant_role(resource, subject, role, exists)
    Ownership->>Ownership: list_roles(resource)
    Ownership->>Roles: remove_resource_role(previous resource_roles)
    alt replacing the last applicable owner
        Ownership->>Ownership: _restore_owner_if_none(resource)
        Ownership->>Roles: add_resource_role(owner)
        Ownership-->>Caller: LastOwner
    else role replacement succeeds
        Ownership->>Roles: add_resource_role(role)
        opt exists provided
            Ownership->>Resource: exists()
            alt resource deleted
                Ownership->>Roles: remove_resource_role(role)
                Ownership-->>Caller: NotFound
            end
        end
        Ownership-->>Caller: previous roles
    end
Loading

Flow diagram for admin-aware ownership listing

flowchart LR
    A["resource_filter(prefix)"] --> B{"is_admin()"}
    B -->|yes| C[Return empty MongoDB filter]
    B -->|no| D["list_subject_roles(prefix)"]
    D --> E[Collect directly owned or shared resource IDs]
    E --> F[Return field $in IDs filter]
Loading

File-Level Changes

Change Details Files
Added ownership lifecycle helpers for assigning, replacing, revoking, and inspecting resource roles across users, groups, and service clients, with last-owner and concurrent-update safeguards.
  • Added creator resolution, including service-client impersonation and request-field on-behalf-of support.
  • Added configurable managed roles and validation for applicable subjects.
  • Implemented role replacement, revocation, typed role listing, subject-resource listing, and MongoDB ownership filters.
  • Added admin detection through mappings and transitive global roles.
  • Added audit logging and handling for deleted resources via existence callbacks.
foca/security/access_control/ownership.py
foca/security/access_control/__init__.py
foca/security/access_control/constants.py
Introduced and validated the configuration for roles managed by ownership helpers.
  • Added resource_roles with default owner and maintainer.
  • Validated required owner role, uniqueness, policy-rule compatibility, subject-prefix restrictions, and prohibition of admin.
foca/models/config.py
Documented the ownership API, configuration, migration impact, and integration patterns.
  • Added usage guidance for creation, listing, deletion, role-management endpoints, concurrency, and resource existence checks.
  • Added configuration and 0.16 migration documentation.
  • Added API reference entries for ownership types and helpers.
docs/access-control.md
docs/configuration/access-control.md
docs/migration-0.16.md
docs/reference.md
Added comprehensive tests covering ownership behavior and persistence edge cases.
  • Covered creator selection, on-behalf-of authorization, subject applicability, configurable roles, admin detection, typed listings, filtering, audit logs, last-owner protection, concurrent changes, and deleted resources.
  • Ran tests against both mongomock and MongoDB-backed adapters.
tests/security/access_control/test_ownership.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

uniqueg and others added 2 commits October 22, 2026 03:53
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]>
@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 (7ae827f) to head (034de87).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #378    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           25        26     +1     
  Lines         2133      2337   +204     
==========================================
+ Hits          2133      2337   +204     
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 01:57

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

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

## Individual Comments

### Comment 1
<location path="foca/security/access_control/ownership.py" line_range="704-705" />
<code_context>
+        for _, role, resource in enforcer.get_filtered_named_grouping_policy(
+            ptype, 0, _prefix_subject(subject, subject_type)
+        ):
+            resource_id = resource.removeprefix(base)
+            if resource.startswith(base) and resource_id and "/" not in resource_id:
+                roles.append(
+                    SubjectResourceRole(resource_id, role, subject_type, subject)
</code_context>
<issue_to_address>
**Scoped listings include other tenants' rows**

When the collection contains documents from multiple path or tenant scopes that reuse an identifier, `list_subject_roles()` reduces each resource path to its ID, and `resource_filter()` queries only that ID field. Documents in the same collection with a matching ID under another tenant or path prefix are therefore returned even though the caller has no role on them.

Include the scope in the MongoDB filter (or use a globally unique field that identifies the full resource path).

Also at `foca/security/access_control/ownership.py:746-747`.
</issue_to_address>

### Comment 2
<location path="foca/security/access_control/ownership.py" line_range="578" />
<code_context>
+        subject_type, subject = _get_creator(on_behalf_of)
+    _check_applicable(subject, subject_type)
+    add_resource_role(
+        subject=subject,
+        role=OWNER_ROLE,
+        resource=resource,
</code_context>
<issue_to_address>
**Configured roles remain after replacement**

When a subject's managed resource role is declared in `access_control.policies` and `grant_role()` or `revoke_roles()` attempts to replace or remove it, `remove_resource_role()` returns `False` for the configured rule, but `grant_role()` and `revoke_roles()` ignore the result. The configured role remains effective while callers see a successful replacement or no roles to revoke.

Check the removal result and report that the configured role could not be removed instead of treating the requested change as successful.

Also at `foca/security/access_control/ownership.py:639-646`.
</issue_to_address>

### Comment 3
<location path="foca/security/access_control/ownership.py" line_range="578-586" />
<code_context>
+    for other in roles:
+        if other != role:
+            remove_resource_role(
+                subject=subject,
+                role=other,
+                resource=resource,
+                ptype=ptype,
+                subject_type=subject_type,
+            )
+    if OWNER_ROLE in previous and role != OWNER_ROLE:
+        _restore_owner_if_none(resource, subject, subject_type, ptype, exists)
+    _grant(resource, subject, role, subject_type, ptype, exists)
+    logger.info(
+        "Role '%s' on '%s' granted to %s by %s (previous roles: %s)",
</code_context>
<issue_to_address>
**Concurrent grants retain both roles**

When different managed roles are granted concurrently to the same subject on the same resource, both `grant_role()` calls can read the same prior roles, remove roles before either replacement is granted, and then persist their respective grants. The subject retains both roles and their combined permissions.

Make each role replacement atomic for a subject and resource, or otherwise serialize concurrent replacements.
</issue_to_address>

### Comment 4
<location path="foca/security/access_control/ownership.py" line_range="470" />
<code_context>
+        ptype=ptype,
+        subject_type=subject_type,
+    )
+    if exists is not None and not exists():
+        remove_resource_role(
+            subject=subject,
</code_context>
<issue_to_address>
**Failed grants remain stored**

When the supplied `exists` callback raises after `add_resource_role()` stores the role, `_grant()` propagates the exception without removing the stored role, so callers see a failed operation while the grant remains active.

Remove the newly added role if the post-grant existence check raises, then re-raise the exception.
</issue_to_address>

### Comment 5
<location path="foca/security/access_control/ownership.py" line_range="578-586" />
<code_context>
+    for other in roles:
+        if other != role:
+            remove_resource_role(
+                subject=subject,
+                role=other,
+                resource=resource,
+                ptype=ptype,
+                subject_type=subject_type,
+            )
+    if OWNER_ROLE in previous and role != OWNER_ROLE:
+        _restore_owner_if_none(resource, subject, subject_type, ptype, exists)
+    _grant(resource, subject, role, subject_type, ptype, exists)
+    logger.info(
+        "Role '%s' on '%s' granted to %s by %s (previous roles: %s)",
</code_context>
<issue_to_address>
**Interrupted downgrades remove every owner**

When two owners concurrently downgrade or revoke their roles, and both processes stop after removing their owner role but before restoration, both `grant_role()` calls can pass `_check_other_owners()` while the other owner still exists, then remove their own owner roles; if both processes stop before `_restore_owner_if_none()`, the resource has no owner and only admins can access it.

Use an atomic transaction or serialized owner-role updates so the last owner cannot be removed even if a worker stops mid-operation.
</issue_to_address>

### Comment 6
<location path="foca/security/access_control/ownership.py" line_range="574-586" />
<code_context>
+    _check_applicable(subject, subject_type)
+    previous = _get_roles_of(resource, subject, subject_type, ptype)
+    if role != OWNER_ROLE:
+        _check_other_owners(resource, subject, subject_type, ptype)
+    for other in roles:
+        if other != role:
+            remove_resource_role(
+                subject=subject,
+                role=other,
+                resource=resource,
+                ptype=ptype,
+                subject_type=subject_type,
+            )
+    if OWNER_ROLE in previous and role != OWNER_ROLE:
+        _restore_owner_if_none(resource, subject, subject_type, ptype, exists)
+    _grant(resource, subject, role, subject_type, ptype, exists)
+    logger.info(
+        "Role '%s' on '%s' granted to %s by %s (previous roles: %s)",
</code_context>
<issue_to_address>
**Role grants preserve ownerless state**

When a non-owner role is granted to a resource that has no applicable owner, such as a legacy or previously orphaned resource, when `_get_owners()` returns an empty set, `_check_other_owners()` does not raise; `grant_role()` then grants a non-owner role and leaves the resource ownerless, contrary to the documented invariant that each resource keeps an owner.

Reject non-owner grants when no applicable owner exists, or establish an owner before granting the role.
</issue_to_address>

### Comment 7
<location path="foca/security/access_control/ownership.py" line_range="576-584" />
<code_context>
+    if role != OWNER_ROLE:
+        _check_other_owners(resource, subject, subject_type, ptype)
+    for other in roles:
+        if other != role:
+            remove_resource_role(
+                subject=subject,
+                role=other,
+                resource=resource,
+                ptype=ptype,
+                subject_type=subject_type,
+            )
+    if OWNER_ROLE in previous and role != OWNER_ROLE:
+        _restore_owner_if_none(resource, subject, subject_type, ptype, exists)
+    _grant(resource, subject, role, subject_type, ptype, exists)
</code_context>
<issue_to_address>
**Failed role change removes last owner**

When the policy store errors after the owner role is removed but before the loop completes, `grant_role()` removes managed roles one at a time; if a policy-store error occurs after removing `owner`, the exception exits before `_restore_owner_if_none()` runs, leaving the resource without that owner and potentially inaccessible to non-admins.

Make the role replacement atomic, or ensure a failed removal sequence restores the owner when storage is available again.
</issue_to_address>

### Comment 8
<location path="foca/security/access_control/ownership.py" line_range="289-294" />
<code_context>
+        subject_type, subject = _get_creator(on_behalf_of)
+    _check_applicable(subject, subject_type)
+    add_resource_role(
+        subject=subject,
+        role=OWNER_ROLE,
+        resource=resource,
+        ptype=ptype,
+        subject_type=subject_type,
+    )
+    logger.info(
+        "Role '%s' on '%s' granted to %s by %s",
</code_context>
<issue_to_address>
**Reused paths lose role integrity**

When a resource is created or recreated at a path while deletion and its two role-cleanup calls are in progress, `add_owner()` writes roles keyed only by the path, while the documented post-delete `remove_resource()` also removes every role for that path. The new resource can therefore inherit a stale owner if creation races deletion, or lose its newly assigned roles if it is created before deletion’s final cleanup.

Serialize creation and deletion for each path, or key role rules by a resource-generation identifier so cleanup cannot affect another incarnation.

Also at `docs/access-control.md:745`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 8 findings to address first, and an incorrect owner, role, or admin check could persist a role rule that lets an unintended subject access resources; reverting the helpers would not undo stored rules or access that already occurred.

Blocking findings: foca/security/access_control/ownership.py:705, foca/security/access_control/ownership.py:578, foca/security/access_control/ownership.py:586, foca/security/access_control/ownership.py:470, foca/security/access_control/ownership.py:586, and 3 more


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:06
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]>
@uniqueg
uniqueg merged commit 2faeec7 into dev Oct 22, 2026
15 checks passed
@uniqueg
uniqueg deleted the feat/resource-ownership branch October 22, 2026 02:14
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