Repository navigation
feat(access-control): add ownership helpers - #378
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]>
Reviewer's GuideAdds 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 assignmentsequenceDiagram
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)
Sequence diagram for safe resource role replacementsequenceDiagram
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
Flow diagram for admin-aware ownership listingflowchart 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]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
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 Report✅ All modified and coverable lines are covered by tests. 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
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 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
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]>
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 fromfoca.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 oron_behalf_offrom 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 optionsecurity.access_control.resource_roles(default[owner, maintainer], must containowner, must not containadmin), 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_mappingwithoutkeep_group_subjects), and to clients that aren't service clients.revoke_roles(resource, subject, subject_type="user", exists=None): revokes them.LastOwner(a werkzeugConflict,409) for the last owner (user, group or client) whose role applies; owners removed by concurrent requests are restored. Withexists, roles granted on a resource deleted meanwhile are revoked again (NotFound).list_roles(resource, role=None): users, then groups, then clients, asResourceRole(subject_type, subject, role).list_subject_roles(prefix)(like cloud-registry'sGET /me) andresource_filter(prefix, field="id"): MongoDB filter for owner-filtered listings;{}for admins.is_admin(): roleadminfromgroup_mapping,client_mappingorgrules (transitively).Role changes are logged on
INFOfor 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.dev(feat(auth): tie service clients to issuers #376 ties service clients to issuers), the test claims name the issuer; 1473 passed locally.Reviewed by the adversarial and quality reviewer subagents (2 rounds); fixed: roles that would not apply,
admininresource_roles,on_behalf_of, a single policy load inlist_roles(), docs examples (deleting,exists, error details), tests forrevoke_roles(exists=...)and duplicates.Declined review findings
grant_role/revoke_roles/list_rolesto matchadd_resource_roleand 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).enforcement.py: same package, asaccess_control_server.pydoes._check_other_owners: the patch is the simplest deterministic way to interleave a concurrent removal; commented.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 (documentedremove_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:
Enhancements:
Documentation:
Tests:
Chores: