Repository navigation
feat(access-control): add opt-in roles - #508
Conversation
Roles of group_mapping listed in access_control.opt_in_roles apply only to requests that ask for them in the header opt_in_header (default: X-Request-Roles), e.g., an admin mode, so that admins act as regular users unless they opt in. Asking grants nothing the token's groups do not entitle to, and roles of service clients always apply. - get_available_opt_in_roles() and get_active_opt_in_roles() tell apps which opt-in roles a subject may use and which apply. - get_current_groups(), and so enforcement, is_admin() and the plugin roles, leave out opt-in roles that a request does not ask for. - Opt-in roles must be roles of group_mapping, and configured rules must not grant them, as roles granted by rules always apply. - Responses vary by the header; FOCA warns if CORS does not allow it. The default (no opt-in roles) keeps today's behaviour. Closes #502 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the review of the opt-in roles: - The permissions API refuses role rules (g, g2) that grant an opt-in role to a subject that is not one, and stored ones are warned about on the first policy load; configured g2 rules are checked, too. - opt_in_header must not contain "_" (dropped by Gunicorn) and must differ from auth.on_behalf_of_header. - The CORS check matches allow_headers as flask-cors does (patterns) and moved to check_opt_in_roles() with the other startup checks. - get_current_groups() maps group values once. - Docs: the new functions in the API reference, the exemption for rules between opt-in roles, and which check runs where. Refs #502 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the second review round of the opt-in roles: - add_resource_role() refuses opt-in roles, as the permissions API does. - One predicate, grants_opt_in_role(), for the configuration, the permissions API and the load warning. - The CORS check treats only entries with characters of regular expressions as patterns, as flask-cors does. - get_current_groups() reuses get_active_opt_in_roles(). - Docs: the CORS matching, object groupings that must not use names of opt-in roles, and shorter cross-references. Refs #502 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideImplements opt-in privileged roles activated by a configurable request header, propagates the effective roles through access-control and gateway integrations, blocks policy-based bypasses, adds cache/CORS handling and startup diagnostics, and documents and tests the complete behavior while retaining the no-opt-in default. Sequence diagram for request-scoped opt-in rolessequenceDiagram
participant Client
participant FocaApp
participant AccessControl
participant Gateway
Client->>FocaApp: HTTP request with opt_in_header
FocaApp->>AccessControl: get_current_groups()
AccessControl->>AccessControl: get_current_group_values()
AccessControl->>AccessControl: get_active_opt_in_roles()
AccessControl-->>FocaApp: Effective roles
FocaApp->>Gateway: Enforce request using effective roles
FocaApp-->>Client: Response with Vary opt_in_header
Flow diagram for opt-in role validation and policy protectionflowchart TD
Config[AccessControlConfig]
Validate[validate_opt_in_roles]
Startup[check_opt_in_roles]
Rules[Configured or stored g and g2 rules]
API[Permissions API]
Resource[add_resource_role]
Guard[grants_opt_in_role]
Warn[_warn_opt_in_grants]
Cors[CORS allow_headers]
Config --> Validate
Validate -->|reject unmapped roles or bypass rules| Config
Config --> Startup
Startup --> Cors
Cors -->|warn when header is not allowed| Startup
Rules --> Guard
API --> Guard
Resource --> Guard
Guard -->|reject direct grants to non-opt-in subjects| API
Guard -->|reject resource grants| Resource
Rules --> Warn
Warn -->|warn on legacy stored bypasses| Startup
File-Level Changes
Assessment against linked issues
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 #508 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 55 55
Lines 6408 6494 +86
=========================================
+ Hits 6408 6494 +86
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 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/models/config.py" line_range="1157" />
<code_context>
+ if (
+ len(rule) >= 3
+ and rule[0].startswith("g")
+ and grants_opt_in_role(rule[1], rule[2], self.opt_in_roles)
+ ):
+ raise ValueError(
</code_context>
<issue_to_address>
**Unrequested roles gain privileges**
When a configured, stored, or API-added grouping rule links two opt-in roles and a request asks for only one, `grants_opt_in_role()` accepts an opt-in subject, so validation lets the link through; Casbin follows it from `get_current_groups()` and grants the linked role’s permissions, while `get_active_opt_in_roles()` reports only the requested role. The caller gets privileges for a role they did not request.
Reject grouping rules that link two opt-in roles before they are added to or loaded into the enforcer.
Also at `foca/security/access_control/enforcement.py:376`, `foca/security/access_control/enforcement.py:406`.
</issue_to_address>
### Comment 2
<location path="foca/security/access_control/enforcement.py" line_range="436" />
<code_context>
+ """
+ if not _get_access_control_config().opt_in_roles:
+ return
+ for ptype in enforcer.get_model().model.get("g", {}):
+ for rule in enforcer.get_named_grouping_policy(ptype):
+ if len(rule) >= 2 and grants_opt_in_role(rule[0], rule[1]):
</code_context>
<issue_to_address>
**Stored resource rules bypass opt-in**
When a previously stored `g2` rule grants an opt-in role to a subject that is not itself an opt-in role, `_warn_opt_in_grants` scans only grouping policies under `g`, so a stored `g2` rule granting an opt-in role to a non-opt-in subject is not warned about and that subject keeps the role without requesting it.
Scan all grouping-policy types in the model, including `g2`, when warning about stored opt-in-role grants.
</issue_to_address>
### Comment 3
<location path="foca/security/access_control/register_access_control.py" line_range="268" />
<code_context>
+
+
+# Characters that make entries of `allow_headers` patterns, as for flask-cors
+_REGEX_CHARS = frozenset("*\\]?$^[()")
+
+
</code_context>
<issue_to_address>
**Allowed headers trigger false warnings**
When `allow_headers` contains a Flask-CORS regex that matches the opt-in header but uses a metacharacter omitted from `_REGEX_CHARS`, `_allows()` treats the regex as a literal because `_REGEX_CHARS` omits metacharacters such as `.`, `+` and `|`, so startup warns that browsers cannot send the header even though Flask-CORS allows it.
Recognize all relevant Flask-CORS regex metacharacters when deciding whether an `allow_headers` entry is a pattern.
Also at `foca/security/access_control/register_access_control.py:287`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 3 findings to address first, and if the role filtering or request-header handling is wrong, a request could receive permissions from an opt-in role without the intended group entitlement or opt-in condition, exposing protected data or access. Reverting would stop future requests from using the feature, but it cannot undo data or access already exposed.
Blocking findings: foca/models/config.py:1157, foca/security/access_control/enforcement.py:436, foca/security/access_control/register_access_control.py:268
Rules must not grant opt-in roles to any subject, also not to other opt-in roles: asking for one opt-in role would otherwise give another, which get_active_opt_in_roles() would not report (Sourcery). The configuration, the permissions API and the load warning share grants_opt_in_role(), and a test covers the warning for stored g2 rules. Refs #502 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Lets apps make privileged roles opt-in (e.g., an admin mode), so that admins act as regular users unless a request asks for the role.
access_control.opt_in_roles(default: none) lists roles ofgroup_mappingthat apply only to requests that ask for them. Requests ask in the headeraccess_control.opt_in_header(default:X-Request-Roles), as a comma-separated list. There's no established convention for such a header (Kubernetes'Impersonate-*headers grant other identities, which is a different thing), so the name follows the issue and can be configured.client_mapping) always apply.get_available_opt_in_roles()andget_active_opt_in_roles()tell apps which opt-in roles a subject may use and which apply, e.g., for/meendpoints (admin_available,admin).get_current_groups()leaves out opt-in roles that a request doesn't ask for. Enforcement,is_admin(), self-service, the ownership helpers and the roles of gateway plugins all follow from that.group_mapping;g,g2) must not grant them to any subject, also not to other opt-in roles;400) andadd_resource_role()refuse such rules;opt_in_headermust be a valid header name without_(which Gunicorn drops), and must differ fromauth.on_behalf_of_header.Vary, so caches keep both modes apart.allow_headersentries are matched as flask-cors patterns).The default (no opt-in roles) keeps today's behaviour.
Closes #502
Verification
Run locally on 3b4fcbd:
ruff checkandruff format --check: pass.mypy: pass.pytest -m "not mongodb": pass, with 100% coverage offoca.mkdocs build --strict: pass.pre-commit: pass.The MongoDB tests and semgrep did not run locally (CI runs them). CI on 3b4fcbd: 28 checks pass, and 2 are skipped as intended.
Review: two rounds of adversarial and quality review.
g2rules weren't checked;_were accepted;on_behalf_of_header;create_app();add_resource_role()still accepted opt-in roles;X-Request-Rolehid the warning);g2 = _, _) are checked like role rules, which is now documented;Sourcery: 3 findings.
g2rules were already warned about (the model'sgsection holds all grouping types). A test now covers it.Declined review findings
Sourcery: more regex characters in the CORS check: declined.
_REGEX_CHARSis flask-cors' own set of hint characters; entries without them are literal header names for flask-cors, too.Narrowing the check to role definitions of the model (round 2, adversarial): declined. Which grouping types are role rules depends on the model's matchers, so all
g*rules are checked, and object groupings must not use names of opt-in roles (documented).Same strict validator for
on_behalf_of_header(round 1, quality): declined here, as it would change validation of an existing option, which is out of scope for this issue. The clash between the two headers is checked.Principal.claimsstill carries the raw group claim (round 1, adversarial, noted as not a defect): plugins that read claims directly see the group values; roles come fromPrincipal.groups, which respects opt-in.🤖 Generated with Claude Code