Skip to content

feat: grant roles on services to groups - #129

Merged
uniqueg merged 5 commits into
devfrom
feat/group-roles
Oct 21, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/group-roles

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Owners can grant the roles owner and maintainer on their services to groups (values of the group claim, eduperson_entitlement for LS Login), so that team changes are handled centrally in Perun.

  • Endpoints (additions spec): PUT and DELETE /services/{serviceId}/permissions/groups/{entitlement} (body {"role": "owner" | "maintainer"}), next to the user endpoints. The entitlement is URL-encoded in the path; the parameter has format: path, so entitlements containing / (e.g. URL-style entitlements of other IdPs) work too (policy /services/:id/permissions/groups/*). Entitlements starting with / can't be addressed: Werkzeug merges the double slash and redirects (308) before the app sees the request; documented in the spec (LS Login entitlements start with urn:).
  • Who may grant: owners only to groups they are members of (entitlement in their own group claim values, get_current_group_values()), otherwise 403; admins to any group. Changing the role of a group is granting, so it needs membership too.
  • Revoking (DELETE): any owner (or admin), also for groups they are not a member of (removing rights can't escalate, and an owner must be able to remove a group someone else added).
  • Group owners count as owners (via FOCA's group subjects: security.access_control.keep_group_subjects: True in the base config, keeping all group values as group: subjects; resource role helpers with subject_type). The app warns on startup if an overlay sets group_mapping but unsets keep_group_subjects, as group roles then don't apply.
  • Last-owner rule (409) considers users and groups: the last user owner can be removed while a group is owner; a group that is the only owner can't be removed or downgraded (not even by admins); the race safeguard (_restore_owner_if_none) restores groups too.
  • GET /services/{serviceId}/permissions stays one list: user entries unchanged (user_id, name if known, role), then group entries {"group": <entitlement>, "role": <role>}; in the spec, items are oneOf Permission / new GroupPermission. User entries are now listed with subject_type="user", so a group never shows up as a user group:… (and a user whose sub starts with group: is not mistaken for a group).
  • GET /me also lists roles the caller has through groups: same ServiceRole entries with an extra optional group (the entitlement); a service is listed once per role (e.g. own role and a group role), sorted by service identifier, user roles first. Group subjects are taken from get_current_groups() (only group: subjects, i.e. as enforced). Display names are only stored for services with roles granted to the user (as only they are listed with names).
  • Audit logs like for users, with escape_log_value: Role 'owner' on service 'X' granted to group 'G' by 'alice' (previous roles: none)., Roles on service 'X' of group 'G' revoked by 'alice'., plus an INFO log for refused grants to non-member groups.
  • Shared logic for users and groups (_put_role(), _delete_roles()); the user endpoints behave as before.
  • Docs: README (API table, access control, GET /me, audit logs), spec descriptions, config comments, and docs/releases/0.3.0.md (the feat: grant roles on services to groups #105 TODO replaced by the notes; no TODO left).

Verification

  • coverage run --source cloud_registry -m pytest -W ignore::DeprecationWarning on Python 3.10 and 3.12 (incl. chart tests with helm 3.18.6): 711 passed; coverage report: 100 %.
  • ruff check ., ruff format --check ., mypy, ast-grep scan, ast-grep test --skip-snapshot-tests, semgrep --config=.semgrep --error: clean.
  • grep TODO docs/releases/0.3.0.md: nothing.
  • New tests (tests/test_access_control.py): grant/list/revoke group roles; members of an owner/maintainer group can update (and manage/delete as owners), non-members can't; owners can't grant to (or change roles of) groups they aren't members of (403), admins can; invalid roles/groups, unknown services, missing roles; entitlements with /, ? and #; users named group:… vs groups; last-owner rule with a group as only owner and removing the last user owner while a group owns the service; restoring a group owner after racing changes; grant racing a deletion; GET /me with group roles; audit log messages.
  • CI: all checks pass (static analysis, tests on 3.10/3.12, Helm chart, Docker Compose smoke test, Read the Docs, codecov/patch and codecov/project).

Declined review findings

Internal review (adversarial + quality subagents, 2 rounds); fixed: startup warning for unset keep_group_subjects (medium), consistent last-owner log, exact test assertions, README wrapping, empty-mapping case of the warning, documented leading-slash limitation. Declined:

  • Split test_group_roles into several tests: kept as one scenario, like the existing access control tests (test_owners_manage_permissions, test_last_owner).
  • Soften the startup warning for deployments that only map the admin group: the warning is accurate there too (roles granted to groups don't apply), and the base config sets the option.
  • Assert the last-owner log message in tests: cosmetic; the message wasn't asserted before either.
  • Cross-reference the format: path spec comment and the policy comment: both say why; no change needed.
  • Reject entitlements starting with / in the app: the redirect happens in routing, before the app sees the request; documented instead (changing merge_slashes would change routing for all endpoints).

Sourcery (fixed: the membership test now reaches the membership check, fc98f4a). Declined, as pre-existing, best-effort race handling shared with user roles (not introduced here; atomicity would need transactions across the policy store, a design change beyond #105):

  • a grant racing a deletion plus admin re-registration of the same identifier could keep the role on the new service;
  • concurrent role replacements of the same subject could leave both roles;
  • a worker crash during concurrent removals of all other owners could leave a service to admins.

Open questions

None.

Closes #105.

🤖 Generated with Claude Code

uniqueg and others added 4 commits October 21, 2026 15:37
Add PUT and DELETE
/services/{serviceId}/permissions/groups/{entitlement} to grant groups
(values of the group claim, eduperson_entitlement for LS Login) the
roles owner or maintainer on a service, using FOCA 0.15's group subjects
(keep_group_subjects, subject_type of the resource role helpers). Owners
may only grant roles to groups they are members of; admins to any group.
Any owner may revoke roles of groups.

Groups count as owners for the last-owner rule (409), also when racing
requests remove all owners. GET /services/{serviceId}/permissions lists
user and group roles in one list (group entries: group, role); user
entries now only list user subjects. GET /me also lists roles through
groups, with the group. Role changes of groups are logged like those of
users.

Closes #105.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Document the group permission endpoints, the membership rule, group
owners and GET /me in the README, and replace the TODO for #105 in the
0.3.0 release notes with the notes of the feature.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Warn on startup if groups are mapped to roles, but
security.access_control.keep_group_subjects is unset, as roles on
services granted to groups then don't apply. Log last owners with the
same subject description as other role changes, document that
entitlements can't start with a slash (redirected by the router), and
tighten the group role tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FOCA drops unmapped group claim values once group_mapping is set, also
if it is empty, so warn about roles of groups not applying then, too.
Rewrap the audit paragraph of the README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sourcery-ai

sourcery-ai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces centrally managed service roles for entitlement-based groups, integrating group subjects into FOCA authorization, ownership and last-owner safeguards, permission listings, GET /me, auditing, configuration, API schemas, documentation, and comprehensive tests while preserving existing user permission behavior.

Sequence diagram for granting a service role to a group

sequenceDiagram
    actor Owner
    participant API
    participant AccessControl
    participant FOCA

    Owner->>API: PUT /services/{serviceId}/permissions/groups/{entitlement}
    API->>AccessControl: get_current_group_values()
    alt owner is not a group member
        AccessControl-->>API: Forbidden
        API-->>Owner: 403 Forbidden
    else member or admin
        API->>FOCA: add_resource_role(subject=entitlement, role=role, subject_type=group)
        FOCA-->>API: role granted
        API-->>Owner: GroupPermission
    end
Loading

Sequence diagram for resolving a user's group service roles

sequenceDiagram
    actor User
    participant API
    participant AccessControl
    participant FOCA

    User->>API: GET /me
    API->>AccessControl: get_current_groups()
    AccessControl-->>API: group subjects
    loop user and group subjects
        API->>FOCA: get_filtered_named_grouping_policy(subject)
        FOCA-->>API: service roles
    end
    API-->>User: ServiceRole entries with optional group
Loading

Entity relationship diagram for user and group service permissions

erDiagram
    SERVICE ||--o{ USER_PERMISSION : grants
    SERVICE ||--o{ GROUP_PERMISSION : grants
    USER_PERMISSION {
        string user_id
        string role
    }
    GROUP_PERMISSION {
        string entitlement
        string role
    }
    GROUP_PERMISSION }o--o{ USER : includes
    USER {
        string user_id
        string group_claim
    }
Loading

File-Level Changes

Change Details Files
Added group-based service permissions alongside user permissions.
  • Added URL-encoded group entitlement PUT and DELETE endpoints.
  • Restricted owner grants and role changes to groups the owner belongs to, while allowing admins to grant to any group and owners to revoke any group.
  • Applied shared grant/revoke logic, validation, audit logging, and race handling to both users and groups.
  • Added group permission schemas, wildcard policy coverage, and documentation of entitlement path limitations.
cloud_registry/ga4gh/registry/permissions.py
cloud_registry/api/additions.openapi.yaml
cloud_registry/config.yaml
README.md
docs/releases/0.3.0.md
Integrated group subjects into access-control enforcement and ownership semantics.
  • Enabled keep_group_subjects in the base configuration and added a startup warning for incompatible overlays.
  • Counted group owners in last-owner checks, conflict handling, and concurrent owner restoration.
  • Separated user and group subjects when listing permissions, including protection for user IDs beginning with group:.
cloud_registry/ga4gh/registry/permissions.py
cloud_registry/config.yaml
cloud_registry/api/additions.openapi.yaml
Exposed group-derived roles through the current-user endpoint and display-name tracking.
  • Included roles inherited from the caller's current group subjects in GET /me.
  • Kept user-granted roles ordered before group-derived roles and stored names only for services with direct user roles.
cloud_registry/ga4gh/registry/permissions.py
cloud_registry/api/additions.openapi.yaml
README.md
Added comprehensive coverage for group permissions and configuration behavior.
  • Tested grant, update, revoke, membership authorization, invalid entitlements, encoded special characters, user/group subject separation, and last-owner safeguards.
  • Tested concurrent deletion/restoration behavior, GET /me, audit messages, and startup warnings.
tests/conftest.py
tests/test_access_control.py
tests/test_app.py

Assessment against linked issues

Issue Objective Addressed Explanation
#105 Add service permission endpoints to grant and revoke owner or maintainer roles for groups, list user and group roles together with distinguishable types, and restrict owner grants to groups they belong to while allowing admins to grant to any group. ✅
#105 Make group-granted roles effective for group members, include those roles in GET /me, and treat groups as owners when enforcing the last-owner rule. ✅
#105 Document group permissions, configuration requirements, and the consequences of a group being a service’s only owner, and add tests for the new behavior. ✅

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 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (7d99c4e) to head (fc98f4a).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #129   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            9         9           
  Lines          704       732   +28     
=========================================
+ Hits           704       732   +28     

☔ 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 21, 2026 14:16

@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="cloud_registry/ga4gh/registry/permissions.py" line_range="387" />
<code_context>
+        known) and role of each role granted to a user, followed by group
+        and role of each role granted to a group.
     """
     if not service_exists(serviceId):
         raise NotFound
-    roles = list_resource_roles(service_path(serviceId))
</code_context>
<issue_to_address>
**Stale grant reaches replacement service**

When a group grant starts on a service, that service is deleted and re-registered with the same identifier before the grant’s post-add existence check, `_grant()` checks only whether `serviceId` exists after adding the group role. If the old service was deleted and an admin registered a different service with the same identifier before that check, `_grant()` leaves the stale request’s role on the replacement service, granting the group access to it.

Check that the same service record still exists, using a generation or immutable record identifier, before retaining the policy change; coordinate this check with deletion and re-registration.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="461-473" />
<code_context>
         for other_role in ROLES:
</code_context>
<issue_to_address>
**Role replacements retain extra access**

When two concurrent PUTs replace the same subject’s role with `owner` and `maintainer`, `_put_role()` removes existing roles before `_grant()` adds the requested role, so overlapping requests can both remove first and then grant, leaving both roles assigned; the subject retains owner-level access after replacement.

Make role removal and granting atomic so concurrent replacements cannot interleave.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="511" />
<code_context>
     revoked = False
     for role in ROLES:
         try:
             revoked |= remove_resource_role(
-                subject=userId, role=role, resource=resource
+                subject=subject, role=role, resource=resource, subject_type=subject_type
</code_context>
<issue_to_address>
**Interrupted revocation leaves no owner**

When concurrent requests remove the remaining owners and the request removing the final owner stops or fails before restoration, the last concurrent owner removal can succeed before `_restore_owner_if_none()` runs; if the request then fails or its worker stops, the service has no owner and only admins can manage it.

Make owner removal and the last-owner safeguard atomic, or otherwise guarantee restoration after an interrupted role-removal sequence.

Also at `cloud_registry/ga4gh/registry/permissions.py:521`.
</issue_to_address>

### Comment 4
<location path="tests/test_access_control.py" line_range="741" />
<code_context>
+    assert revoke_group(client, service_id, OTHER_GROUP) == 200
+    assert update(client, service_id, BOB) == 403
+    # members of a group can't grant themselves roles through it
+    assert grant_group(client, service_id, TEAM_GROUP, "owner", as_user=ERIN) == 403
+
+
</code_context>
<issue_to_address>
**Self-grant check is bypassed**

When the group-membership guard is removed while FOCA's owner-only policy remains, `test_group_membership_required` sends this request as ERIN, who has no role on the service. FOCA rejects the request under the owner-only policy before the membership guard runs, so removing that guard still leaves the assertion passing.

Grant ERIN an owner role on the service before this request so the test reaches the membership guard.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and a group grant makes every member of that group eligible for the granted service role, including owner rights to update, delete, and manage permissions. Revoking the grant or reverting the code stops future access, but cannot undo data or service changes made while the group had access.

Blocking findings: cloud_registry/ga4gh/registry/permissions.py:387, cloud_registry/ga4gh/registry/permissions.py:473, cloud_registry/ga4gh/registry/permissions.py:511, tests/test_access_control.py:741


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

Comment thread tests/test_access_control.py Resolved
Let an owner who is not a member of the group grant it a role, so that
the test fails without the membership check (the request was refused
by the owner policy before).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

feat: grant roles on services to groups

1 participant