Repository navigation
feat: grant resource roles to groups - #319
Conversation
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]>
Reviewer's GuideAdds 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 enforcementsequenceDiagram
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
Sequence diagram for granting a resource role to a groupsequenceDiagram
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
Flow diagram for group subject configurationflowchart 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]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
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 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
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]>
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.
access_control.keep_group_subjects(defaultfalse, behaviour unchanged): with agroup_mapping, all group claim values are kept asgroup:<value>subjects next to the mapped roles, so a role granted togroup:<value>on a resource applies to every user whose group claim contains<value>. Without a mapping, values are alreadygroup: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.add_resource_role()andremove_resource_role()takesubject_type("user", the default, or"group");list_resource_roles()takes an optionalsubject_typeto list only users or only groups, without their prefix (without it, the 0.14 behaviour is kept). User and group subjects can't collide. NewSubjectTypealias exported.add_resource_role()raisesValueErrorfor roles starting with the user prefix orgroup:, 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 raiseValueErrortoo (they produced a meaninglessuser:rule before).keep_group_subjectsis set without agroup_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/access-control.md): "Granting roles to groups" with a config example, listing, a controller example (allowlisted roles, validatedsubject_type, membership check) and security considerations (allowlist grantable roles, map groups only to global roles such asadmin); a "Policy types" heading for the existingptypeparagraph; reference entry.Closes #316
Verification
Locally (Python 3.12):
ruff check .,ruff format --check .: passedmypy foca: no issues in 34 source filespytest(unit tests, MongoDB 7 locally, integration tests excluded) under coverage: 898 passed; coverage 100% (1627 statements)mkdocs build --strict: no warningsadmingranted 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.keep_group_subjectsonly 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
devafter #318).Notes
for subject, role in ...loops keep working; apps listing both call it twice.🤖 Generated with Claude Code