Skip to content

feat(access-control): add opt-in roles - #508

Merged
uniqueg merged 4 commits into
devfrom
feat/opt-in-roles
Oct 26, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/opt-in-roles

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

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.

  • Config: access_control.opt_in_roles (default: none) lists roles of group_mapping that apply only to requests that ask for them. Requests ask in the header access_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.
  • Semantics:
    • Without the header, an admin's request gets regular-user permissions plus their other roles; with it, admin permissions.
    • Asking grants nothing that the token's groups don't entitle to: unknown roles, roles the subject doesn't have, and roles that aren't opt-in are ignored.
    • Roles of service clients (client_mapping) always apply.
  • Helpers: get_available_opt_in_roles() and get_active_opt_in_roles() tell apps which opt-in roles a subject may use and which apply, e.g., for /me endpoints (admin_available, admin).
  • Coverage: 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.
  • Rules can't bypass it:
    • opt-in roles must be roles of group_mapping;
    • configured role rules (g, g2) must not grant them to any subject, also not to other opt-in roles;
    • the permissions API (400) and add_resource_role() refuse such rules;
    • stored ones are warned about when policies are first loaded.
  • Header checks: opt_in_header must be a valid header name without _ (which Gunicorn drops), and must differ from auth.on_behalf_of_header.
  • Caching and CORS:
    • Responses carry the header in Vary, so caches keep both modes apart.
    • FOCA warns on startup if CORS doesn't allow the header (allow_headers entries are matched as flask-cors patterns).
    • These checks also run without access control, since gateway plugins use the roles too.
  • Docs: a section "Opt-in roles" in the access control guide, the config page, the startup checks and the API reference.

The default (no opt-in roles) keeps today's behaviour.

Closes #502

Verification

Run locally on 3b4fcbd:

  • ruff check and ruff format --check: pass.
  • mypy: pass.
  • pytest -m "not mongodb": pass, with 100% coverage of foca.
  • 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.

  • Round 1 (fixed in 924e593):
    • role rules stored in the database or posted via the permissions API could still grant opt-in roles;
    • configured g2 rules weren't checked;
    • the CORS check ignored pattern entries;
    • header names with _ were accepted;
    • no check for a clash with on_behalf_of_header;
    • the startup checks were inline in create_app();
    • API reference entries were missing;
    • gaps in tests and docs.
  • Round 2 (fixed in 741246e):
    • add_resource_role() still accepted opt-in roles;
    • the CORS check treated every entry as a pattern (a typo such as X-Request-Role hid the warning);
    • the opt-in predicate existed in three forms;
    • object groupings of custom models (g2 = _, _) are checked like role rules, which is now documented;
    • doc wording, duplicate docs, reference entries for internal helpers, and a test of the custom header.

Sourcery: 3 findings.

  • Fixed in 3b4fcbd: rules between opt-in roles let one opt-in role give another, unreported. Such rules are now refused like all grants of opt-in roles.
  • Clarified: stored g2 rules were already warned about (the model's g section holds all grouping types). A test now covers it.
  • Declined: see below.

Declined review findings

  • Sourcery: more regex characters in the CORS check: declined. _REGEX_CHARS is 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.claims still carries the raw group claim (round 1, adversarial, noted as not a defect): plugins that read claims directly see the group values; roles come from Principal.groups, which respects opt-in.

🤖 Generated with Claude Code

uniqueg and others added 3 commits October 26, 2026 00:17
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implements 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 roles

sequenceDiagram
    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
Loading

Flow diagram for opt-in role validation and policy protection

flowchart 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
Loading

File-Level Changes

Change Details Files
Adds configurable request-scoped activation for roles mapped from group claims, while preserving existing behavior when no opt-in roles are configured.
  • Introduces opt_in_roles and opt_in_header configuration with validation for mapped roles, valid header syntax, and header conflicts.
  • Parses requested roles from one or multiple comma-separated headers and exposes available versus active opt-in role helpers.
  • Filters inactive opt-in roles from current groups so enforcement, admin checks, ownership helpers, and gateway plugin principals use the effective request roles.
  • Keeps service-client roles and non-opt-in mapped roles always active.
  • Adds Vary response handling to separate cached responses by opt-in header state.
  • files
foca/models/config.py
foca/security/access_control/enforcement.py
foca/security/access_control/__init__.py
foca/foca.py
tests/security/access_control/test_enforcement.py
tests/test_foca.py
Prevents Casbin role rules and resource ownership operations from bypassing opt-in semantics, with compatibility warnings for persisted invalid policies.
  • Rejects configured g/g2 rules that grant opt-in roles to non-opt-in subjects.
  • Rejects equivalent permissions API rules and add_resource_role() calls.
  • Warns once when loaded stored policies contain grants that bypass opt-in activation.
  • Keeps role-to-role grants between opt-in roles valid and documents custom-model g* grouping behavior.
foca/models/config.py
foca/security/access_control/access_control_server.py
foca/security/access_control/enforcement.py
tests/models/test_config.py
tests/security/access_control/test_enforcement.py
Adds startup validation and diagnostics for the opt-in request header and browser interoperability.
  • Logs configured opt-in roles and warns when CORS does not allow the configured header.
  • Matches CORS allow-header literals, wildcard entries, and regex-style patterns consistently with flask-cors behavior.
  • Runs the check even when access control is disabled for gateway-plugin use cases.
  • Adds coverage for custom headers, CORS patterns, invalid patterns, response variance, and default behavior.
foca/security/access_control/register_access_control.py
foca/foca.py
tests/test_foca.py
Documents configuration, request semantics, helper APIs, policy restrictions, startup checks, and public references.
  • Adds an opt-in roles guide with configuration and client-request examples.
  • Documents rule restrictions, service-client behavior, CORS requirements, and helper usage.
  • Adds the new helper functions to the API reference and configuration/deployment documentation.
docs/access-control.md
docs/configuration/access-control.md
docs/deployment.md
docs/reference.md

Assessment against linked issues

Issue Objective Addressed Explanation
#502 Make configured group-mapped roles opt-in per request, while preserving all other group and service-client roles and keeping existing behavior when no opt-in roles are configured. ✅
#502 Provide a configurable, documented request mechanism for asking for opt-in roles, without granting roles the subject is not entitled to, and expose helpers for roles available to the subject and active on the request. ✅
#502 Ensure opt-in roles are respected across access-control enforcement and integrations, and prevent policy or resource-role grants from bypassing opt-in 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 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (801a618) to head (3b4fcbd).

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     
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 26, 2026 00:11

@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 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


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

Comment thread foca/models/config.py Resolved
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]>
@uniqueg
uniqueg merged commit bcb9c3b into dev Oct 26, 2026
30 checks passed
@uniqueg
uniqueg deleted the feat/opt-in-roles branch October 26, 2026 00:28
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(access-control): opt in to privileged roles

1 participant