Skip to content

feat: grant resource roles to groups - #319

Merged
uniqueg merged 6 commits into
devfrom
feat/group-resource-roles
Oct 20, 2026
Merged

uniqueg merged 6 commits into
devfrom
feat/group-resource-roles

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Apps can grant resource-scoped roles to groups, not only to users (#316), e.g., so that a team maintained as a group in LS Login owns a resource.

  • Option access_control.keep_group_subjects (default false, behaviour unchanged): with a group_mapping, all group claim values are kept as group:<value> subjects next to the mapped roles, so a role granted to group:<value> on a resource applies to every user whose group claim contains <value>. Without a mapping, values are already group: subjects (a warning is logged if the option is set without a mapping). All values are kept, not only unmapped ones, so a role granted to a group also applies if that group is mapped to a role.
  • Resource role helpers: add_resource_role() and remove_resource_role() take subject_type ("user", the default, or "group"); list_resource_roles() takes an optional subject_type to list only users or only groups, without their prefix (without it, the 0.14 behaviour is kept). User and group subjects can't collide. New SubjectType alias exported.
  • Roles that look like subjects can't be granted: add_resource_role() raises ValueError for roles starting with the user prefix or group:, because Casbin resolves roles transitively, so such a rule would give the user that group's rights. Removing such rules still works, so existing ones can be revoked (the docs suggest looking for them). Empty subjects raise ValueError too (they produced a meaningless user: rule before).
  • Warnings: when keep_group_subjects is set without a group_mapping (no effect), and when a role is granted to a group while group subjects are not kept (the rule would never apply).
  • get_current_group_values(): the raw group claim values of the current request, so that apps can enforce rules such as "users may only grant roles to groups they are a member of".
  • Docs (docs/access-control.md): "Granting roles to groups" with a config example, listing, a controller example (allowlisted roles, validated subject_type, membership check) and security considerations (allowlist grantable roles, map groups only to global roles such as admin); a "Policy types" heading for the existing ptype paragraph; reference entry.

Closes #316

Verification

Locally (Python 3.12):

  • ruff check ., ruff format --check .: passed
  • mypy foca: no issues in 34 source files
  • pytest (unit tests, MongoDB 7 locally, integration tests excluded) under coverage: 898 passed; coverage 100% (1627 statements)
  • mkdocs build --strict: no warnings
  • gitleaks: no leaks
  • Two review rounds (adversarial and quality); all findings fixed. The adversarial reviews also checked with Casbin directly that a role named admin granted on a resource gives no global rights, that roles don't extend to other resources or parent paths, and that the default behaviour is unchanged.
  • Sourcery: 4 threads, all addressed (startup-time warning for legacy subject-like role rules, logged on the first policy load without extra database calls; revoking empty subjects; duplicates listed once and removed together; docs note on enabling keep_group_subjects only after all instances are upgraded). The fixes went through two more review rounds.

Not run locally: the integration tests (need the Docker petstore app); CI runs them.

CI: all required checks passed (lint, type check and build; unit tests on Python 3.10–3.14 with MongoDB 7.0; petstore integration tests; Codecov; Read the Docs). The MongoDB 8.0 job failed to start MongoDB on the runner (allowed to fail, cf. the kernel note in the workflow; it also failed on dev after #318).

Notes

  • Listing filters by subject type instead of returning the type with each entry, so existing for subject, role in ... loops keep working; apps listing both call it twice.

🤖 Generated with Claude Code

uniqueg and others added 3 commits October 20, 2026 22:54
Add the access control option `keep_group_subjects` (default false):
with it, all group claim values are kept as `group:<value>` subjects
next to the mapped roles, so resource roles granted to groups apply also
when `group_mapping` is set. The resource role helpers take a
`subject_type` (`user` or `group`) to grant, revoke and list roles of
groups, and `get_current_group_values()` returns the raw group claim
values of the current request, so that apps can restrict granting to
groups the user is a member of. Document the pattern and its security
considerations.

Closes #316

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reject roles starting with the subject prefix or `group:` in the
resource role helpers: Casbin resolves roles transitively, so granting
a user the "role" `group:<value>` would give them that group's rights
and bypass any membership check of the app. Check for empty subjects
before prefixing them, and document both `ValueError`s.

Branch once in `list_resource_roles()`, simplify the error message of
unsupported subject types, export `SubjectType` and warn on
registration if `keep_group_subjects` is set without `group_mapping`,
where it has no effect.

Docs: validate `subject_type` and `role` (allowlist) in the controller
example, recommend declaring them as enums in API specifications and
extend the security notes. Also move the paragraph on `ptype` under a
new "Policy types" heading, so it is not part of "Granting roles to
groups".

Tests: validate subject type and role in the test controller, split
the group role helper tests, cover subject-like roles (including the
chaining scenario) and the new warning, and inspect rules via the
enforcer instead of the adapter's collection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Only reject roles starting with the subject prefix or `group:` when
granting them, so that existing rules with such roles (e.g., stored
before the check was added) can still be revoked via
`remove_resource_role()`. Both helpers still validate rules.

Warn when granting a role to a group while `group_mapping` is set and
`keep_group_subjects` is not, as the role would not apply. Document
`SubjectType` and list it in the API reference.

Docs: recommend always passing `subject_type` to
`list_resource_roles()`, looking for and removing subject-like roles
when upgrading, and mapping group values only to global roles such as
`admin`, not to resource-scoped role names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds namespaced group subjects and group-aware resource-role helpers, with configuration, validation, warnings, tests, and comprehensive documentation while preserving existing user and mapped-group behavior.

Sequence diagram for group-based resource role enforcement

sequenceDiagram
    actor User
    participant App
    participant AccessControl
    participant Casbin

    User->>App: Request resource
    App->>AccessControl: get_current_group_values()
    AccessControl-->>App: Raw group claim values
    App->>AccessControl: get_current_groups()
    AccessControl-->>App: Mapped roles and group subjects
    App->>Casbin: enforce_access_control()
    Casbin->>Casbin: Resolve group:<value> resource role
    Casbin-->>App: Allow or deny
    App-->>User: Resource response
Loading

Sequence diagram for granting a resource role to a group

sequenceDiagram
    actor User
    participant Controller
    participant AccessControl
    participant Casbin

    User->>Controller: Submit subject, role, resource, subject_type
    Controller->>AccessControl: get_current_group_values()
    AccessControl-->>Controller: Current group claim values
    Controller->>AccessControl: add_resource_role(subject, role, resource, subject_type)
    AccessControl->>AccessControl: Validate subject and grantable role
    AccessControl->>Casbin: Add g2 group:<subject>, role, resource
    Casbin-->>AccessControl: Policy result
    AccessControl-->>Controller: Granted or already exists
Loading

Flow diagram for group subject configuration

flowchart TD
    Claims[Group claim values]
    Mapping{group_mapping configured?}
    Keep{keep_group_subjects enabled?}
    Roles[Mapped roles]
    Subjects[group:value subjects]

    Claims --> Mapping
    Mapping -->|No| Subjects
    Mapping -->|Yes| Roles
    Mapping --> Keep
    Keep -->|Yes| Subjects
    Keep -->|No| Warning[Group resource grants do not apply]
Loading

File-Level Changes

Change Details Files
Preserve raw group claim values as namespaced subjects when configured, enabling resource-scoped roles to be granted to groups while retaining existing mapped-role behavior.
  • Add keep_group_subjects configuration and startup warning for ineffective settings.
  • Expose raw group claim values and include deduplicated group: subjects alongside mapped roles.
  • Cover group-subject enforcement, mapping combinations, and user/group isolation.
foca/models/config.py
foca/security/access_control/enforcement.py
foca/security/access_control/register_access_control.py
foca/security/access_control/__init__.py
tests/security/access_control/test_enforcement.py
tests/security/access_control/test_register_access_control.py
Extend resource-role helper APIs to manage and query either user or group subjects safely.
  • Add subject_type support to add, remove, and list helpers with filtering and prefix handling.
  • Export the SubjectType alias while preserving default listing behavior.
  • Validate empty and invalid subjects, reject subject-like roles on grant, and retain removal support for legacy unsafe rules.
  • Warn when group roles cannot apply because group subjects are disabled.
foca/security/access_control/enforcement.py
foca/security/access_control/__init__.py
tests/security/access_control/test_enforcement.py
Document group role configuration, API usage, authorization safeguards, and policy semantics.
  • Add configuration and controller examples for membership checks and grantable-role allowlists.
  • Document subject-type listing, security implications, token-based membership, and rule-value constraints.
  • Add get_current_group_values and SubjectType to the reference documentation and clarify policy types.
docs/access-control.md
docs/reference.md
foca/security/access_control/api/resource_role_model.conf

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (b42d0f1) to head (287d0ab).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #319   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           24        24           
  Lines         1583      1627   +44     
=========================================
+ Hits          1583      1627   +44     
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 20, 2026 21:27

@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/enforcement.py" line_range="504" />
<code_context>
+    rule = _get_resource_role_rule(
+        subject, role, resource, ptype, subject_type, enforcer
+    )
+    _validate_grantable_role(role)
+    conf = _get_access_control_config()
+    if (
</code_context>
<issue_to_address>
**Legacy chained grants remain active**

When the policy collection contains a resource-role row whose role starts with the user subject prefix or `group:`, `add_resource_role()` now rejects subject-like roles, but existing `g2` rows are still loaded into Casbin and can continue granting the referenced subject’s rights to their grantee; the upgrade therefore leaves those grants active until someone finds and removes them.

Add an upgrade migration or load-time handling that identifies and removes or disables these legacy rows, rather than relying only on manual cleanup.
</issue_to_address>

### Comment 2
<location path="foca/security/access_control/enforcement.py" line_range="428-429" />
<code_context>
+            or the rule is not valid (cf.
+            :py:func:`foca.security.access_control.foca_casbin_adapter.casbin_rule.validate_rule`).
+    """
+    if not subject:
+        raise ValueError("Subjects must not be empty")
+    rule = [_prefix_subject(subject, subject_type), role, resource]
+    validate_rule(ptype, rule, enforcer.get_model())
</code_context>
<issue_to_address>
**Empty-subject rows cannot be revoked**

When the policy collection contains a `g2` row with subject `user:` created before this check, `remove_resource_role()` shares `_get_resource_role_rule()` with the add helper, so it raises before constructing the `user:` rule and cannot revoke an empty-subject resource-role row created by the previous helper behavior; the stored row remains.

Allow the revoke helper to construct the legacy `user:` rule for an empty subject, or provide a migration/removal path for those rows while keeping empty subjects invalid for new grants.
</issue_to_address>

### Comment 3
<location path="foca/models/config.py" line_range="636" />
<code_context>
     subject_prefix: str = "user:"
     claim_groups: str | None = None
     group_mapping: dict[str, str] | None = None
+    keep_group_subjects: bool = False
     resource_roles_cover_subpaths: bool = True
     id_charset: str = DEFAULT_ID_CHARSET
</code_context>
<issue_to_address>
**Older instances reject new setting**

When a rolling deployment enables `keep_group_subjects` in shared configuration before all instances run this release, the previous release's `AccessControlConfig` does not define `keep_group_subjects` and inherits `FOCABaseConfig`'s `extra="forbid"`, so an older instance started with this setting fails configuration validation and does not start.

Deploy the release with the option unset first, then enable it after older instances have been drained.
</issue_to_address>

### Comment 4
<location path="foca/security/access_control/enforcement.py" line_range="462" />
<code_context>
     resource: str,
     ptype: str = RESOURCE_ROLE_PTYPE,
+    subject_type: SubjectType = "user",
 ) -> bool:
     """Grant a subject a role on a resource.

</code_context>
<issue_to_address>
**Duplicate grants appear in listings**

When two requests concurrently grant the same role to the same subject on the same resource, both `add_resource_role()` calls load an enforcer before either rule is stored, so each inserts a separately identified row and returns `True`; `list_resource_roles()` then returns duplicate grants.

Make concurrent grants of the same rule persist only one row.

Also at `foca/security/access_control/enforcement.py:518`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and a group-scoped resource-role rule can grant every user whose request claims that group the role’s permissions, potentially exposing protected resources if a grant or group claim is wrong. The rule is persisted, so reverting the code does not remove it, and any access that occurred cannot be undone.

Blocking findings: foca/security/access_control/enforcement.py:504, foca/security/access_control/enforcement.py:429, foca/models/config.py:636, foca/security/access_control/enforcement.py:462


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

Comment thread foca/models/config.py Resolved
uniqueg and others added 3 commits October 20, 2026 23:36
Warn on startup about each stored resource-scoped role rule whose role
starts with the subject prefix or `group:`, as it gives its subject the
rights of that subject on the resource (one query when the enforcer is
registered). Such rules are not removed automatically; the warning
explains how to revoke them.

Accept empty subjects in `remove_resource_role()`, so that rules for
them (e.g., `user:`) stored before they were rejected can be revoked;
`add_resource_role()` still rejects them.

List each role once in `list_resource_roles()`, also if a rule was
stored twice by concurrent requests. Revoking already removes all
stored copies of a rule, as the adapter deletes all matching documents;
document and test this.

Docs: only enable `keep_group_subjects` once all instances of an app
run a FOCA version that supports it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check for stored resource-scoped roles that are subjects when policies
are first loaded (once per app), on the rules the enforcer already
loaded, instead of querying the database when the enforcer is
registered. App creation thus again needs no database connection, the
check cannot fail on database errors, and private adapter attributes
and regular expressions are no longer used. Values in the warning are
quoted, so that control characters cannot forge log lines; the
meaningless rule identifier is dropped from the message.

Add `get_resource_role_ptypes()` to get the resource-scoped role
definitions of a model, and use it wherever they were detected.

Explain in `remove_resource_role()` why empty subjects are accepted.
Test the warning via requests to an app with a custom subject prefix
containing `.`, and that clean rules log nothing; check duplicate
removal via the enforcer instead of the adapter's collection.

Docs: refer to resource-scoped role rules (by default `g2`), say when
the warning is logged and that listing returns each subject and role
pair once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Make the helper detecting resource-scoped role definitions private and
drop it from the API reference, as no external caller needs it.

Guard the check-and-set of the flag of the subject-like role check
with a lock, so that concurrent first requests do not warn twice, and
document that the check runs on the first policy load of each app
instance (per worker process).

Move the comment on accepting empty subjects to `add_resource_role()`,
where they are rejected, and shorten the one in
`remove_resource_role()`.

Docs: explain how to revoke rules of group subjects
(`subject_type="group"`) and that the permissions API stores rules as
given, i.e., without rejecting subject-like roles.

Tests: capture the warnings via caplog, re-enabling the module logger
and its propagation if app creation disabled them, and assert on the
quoted rule values instead of parsing messages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 85e2e78 into dev Oct 20, 2026
12 of 13 checks passed
@uniqueg
uniqueg deleted the feat/group-resource-roles branch October 20, 2026 22:51
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