Skip to content

fix(plugins): align Principal with access control - #527

Merged
uniqueg merged 5 commits into
devfrom
fix/plugin-principal-identity
Oct 26, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/plugin-principal-identity

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

The Principal that plugins see now identifies the caller the same way access control does. This fixes finding 4 of the v0.18.0 pre-release review.

  • New get_current_roles() (foca.security.access_control): returns the roles that access control applies to the request.
    • It includes the role of a service client (client_mapping), the roles from group claims, and the roles granted via global role rules (g), also transitively.
    • It follows only the g role manager, within Casbin's maximum hierarchy level, as enforce() and is_admin() do. Default-model g2 object groups and resource-scoped roles don't count.
    • Unidentified callers get no roles, as in is_admin().
  • Principal.groups now comes from get_current_roles(). Plugin roles and client_pipelines.roles therefore match access control. For example, client_mapping: {portal: admin} now satisfies roles: [admin].
  • Principal.subject is the client ID for service tokens. The new subject_type is user or client and defaults to user when there is a subject. Users and clients with the same identifier no longer share one namespace.
  • New Principal.acting_for: the user that a service client acts for (auth.on_behalf_of_header), i.e. the owner of the resources it creates.
    • It is resolved for service clients only. A client that may not act for users gets 403, and an invalid name gets 400.
    • The header of other callers is ignored here; the ownership helpers still reject it.
  • Test helpers: make_principal() takes subject_type and acting_for. The shared callers of the access control tests moved to tests/security/access_control/callers.py.
  • Docs: docs/plugins.md (the caller), docs/access-control.md (get_current_groups() vs. get_current_roles()) and docs/reference.md.

Plugins and Principal are new in 0.18 (they are in no released tag), so this needs no migration note. proTES (planned consumer) should key quotas and provenance on (subject_type, subject), and ownership on acting_for or else the subject.

Closes #519

Verification

  • pytest tests/plugins tests/security -m "not mongodb": 1487 passed. Coverage of foca/plugins, enforcement.py and ownership.py is 100%.
  • New unmocked tests:
    • tests/plugins/test_plugin_adapter.py::TestPrincipalIdentity: user, client_mapping, g rules, on-behalf-of, access control disabled.
    • tests/security/access_control/test_current_roles.py: hierarchy limit, other role definitions, opt-in roles, unidentified callers.
  • ruff check, ruff format --check, mypy, ast-grep scan, semgrep (.semgrep) and mkdocs build --strict are all clean.
  • I did not run the mongodb-marked tests locally because no MongoDB server was available; CI runs them.
  • CI: all checks passed, including the MongoDB-backed tests (skips are image pushes on PRs).

Declined review findings

  • g targets that look like subjects (e.g., g, group:devs, client:protes) appear as roles (low). Enforcement applies them the same way. The point of this change is consistency with access control, and filtering by prefix would make the two diverge again.
  • The mocked test_current_principal overlaps the unmocked tests (low). I kept it for the bearer-scheme and non-string-issuer cases.
  • Extract the role traversal into a helper (optional, low). The traversal is short, and it is covered end to end.

🤖 Generated with Claude Code

Summary by Sourcery

Align plugin principals with access-control identity, roles, and ownership semantics.

New Features:

  • Add get_current_roles() to expose the complete set of roles applied by access control, including mapped client, group, and global-rule roles.
  • Extend plugin principals with client-aware identity, subject_type, and service-client acting_for information.

Bug Fixes:

  • Align plugin principal identities and roles with access-control enforcement, including correct service-client mapping and on-behalf-of behavior.

Enhancements:

  • Consolidate shared access-control test callers and expand coverage for role inheritance, identity handling, and service-client behavior.

Documentation:

  • Document current roles and the updated plugin principal identity, role, and ownership semantics.

Tests:

  • Add unmocked tests covering current-role resolution, role hierarchy limits, client mappings, on-behalf-of handling, and disabled access control.

uniqueg and others added 4 commits October 26, 2026 21:05
Principal.groups held only the roles from group claims, and
Principal.subject the identity claim, so plugins saw neither the role
of a service client (client_mapping) nor roles from global role rules,
and could not tell clients from users or see the user a client acts
for.

- Add get_current_roles(): client role, group roles and roles granted
  via g rules, transitively, as access control applies them.
- Principal: subject is the client ID for service tokens, with the new
  subject_type (user or client) and acting_for (on-behalf-of user);
  groups come from get_current_roles().
- Test the principal against a real access control setup.

Closes #519

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- get_current_roles() follows only the g role manager and keeps roles
  within Casbin's maximum hierarchy level, as enforcement does; object
  groups (default model g2) and resource roles no longer count.
- Principal defaults subject_type to user and rejects a type without
  a subject; the adapter no longer derives it.
- Move shared callers of the access control tests into a module, test
  get_current_roles() and the builder arguments, and clarify the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- get_current_roles() returns no roles for tokens without a user or
  service client, as is_admin() does (is_permitted() refuses them).
- current_principal() resolves acting_for for service clients only, so
  the on-behalf-of header of other callers no longer makes the plugin
  listing fail; the ownership helpers still reject it.
- Simplify the adapter and rewrap the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.18.0 milestone Oct 26, 2026
@uniqueg uniqueg added the type: security Related to security label Oct 26, 2026
@sourcery-ai

sourcery-ai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Aligns plugin Principal identity, delegated ownership, and roles with access-control semantics by introducing get_current_roles(), distinguishing users from service clients, and resolving authorized on-behalf-of users, with comprehensive documentation and unmocked test coverage.

Sequence diagram for access-control-aligned plugin Principal

sequenceDiagram
    participant Request
    participant Adapter as current_principal()
    participant Access as AccessControl
    participant Plugin as Plugin

    Request->>Adapter: current_principal()
    Adapter->>Access: get_current_client()
    Access-->>Adapter: client or none
    alt service client
        Adapter->>Access: get_on_behalf_of_user()
        Access-->>Adapter: acting_for user
    end
    Adapter->>Access: get_current_roles()
    Access-->>Adapter: client, group, and global roles
    Adapter-->>Plugin: Principal(subject, subject_type, acting_for, groups)
Loading

Flow diagram for current role resolution

flowchart TD
    Identity["Resolve service client or user identity"] --> BaseRoles["Collect client_mapping and group-claim roles"]
    BaseRoles --> Enabled{"Access control enabled?"}
    Enabled -->|No| Result["Return roles"]
    Enabled -->|Yes| Global{"Model defines global g roles?"}
    Global -->|No| Result
    Global -->|Yes| Traverse["Traverse g role links transitively"]
    Traverse --> Filter["Keep roles linked within hierarchy limit"]
    Filter --> Result
    Identity --> Unidentified{"Identity found?"}
    Unidentified -->|No| Empty["Return no roles"]
Loading

File-Level Changes

Change Details Files
Added role resolution that mirrors access-control enforcement for plugin callers.
  • Introduced get_current_roles() with client mappings, claim groups, transitive global g roles, hierarchy limits, opt-in handling, and exclusion of unsupported role definitions.
  • Reused the global-role model check between enforcement and ownership logic.
  • Exported and documented the new access-control helper.
foca/security/access_control/enforcement.py
foca/security/access_control/__init__.py
foca/security/access_control/ownership.py
docs/access-control.md
docs/reference.md
Updated plugin principals to represent service-client identity and delegated ownership consistently with access control.
  • Changed service-token subjects to client IDs and added subject_type to distinguish user and client namespaces.
  • Added acting_for resolution for authorized service clients using the on-behalf-of header, including 400/403 validation behavior.
  • Populated principal groups from get_current_roles() so plugin role checks match enforcement.
  • Added principal invariants and updated plugin documentation.
foca/plugins/adapter.py
foca/plugins/model.py
docs/plugins.md
Expanded test builders and unmocked coverage for principal identity and current-role semantics.
  • Extended make_principal() with subject_type and acting_for and validated invalid combinations.
  • Added shared access-control caller/app fixtures and tests for client mappings, role inheritance, hierarchy limits, opt-in roles, unidentified callers, alternate role definitions, and on-behalf-of behavior.
  • Migrated ownership tests to the shared helpers.
foca/plugins/testing.py
tests/plugins/test_plugin_adapter.py
tests/plugins/test_plugin_testing.py
tests/security/access_control/callers.py
tests/security/access_control/test_current_roles.py
tests/security/access_control/test_ownership.py

Assessment against linked issues

Issue Objective Addressed Explanation
#519 Make plugin Principal.groups reflect the roles access control applies, including client_mapping roles and roles granted by global g rules. ✅
#519 Represent service-client identity distinctly from user identity, and expose the user a service client acts for. ✅
#519 Add unmocked coverage and keep plugin documentation consistent with the updated Principal semantics. ✅

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 (fc356e7) to head (8cd8dcf).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #527   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           55        55           
  Lines         6636      6667   +31     
=========================================
+ Hits          6636      6667   +31     
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 21:19

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

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="docs/plugins.md" line_range="513-517" />
<code_context>
+The caller (`Principal`) is identified as by access control and its
+ownership helpers:
+
+- `subject` and `subject_type`: the client ID of a service client
+  (`client`), or else the user's subject (`user`); key quotas or records
+  on both, as a client and a user may have the same identifier;
+- `acting_for`: the user that a service client acts for (header
+  `auth.on_behalf_of_header`), who owns the resources it creates (e.g.,
+  tasks); service clients that may not act for users get `403`, invalid
+  names `400` (the header of other callers is ignored here, but rejected
</code_context>
<issue_to_address>
**Identity values include undocumented namespaces**

When the app uses issuer namespaces and a plugin interprets these fields as raw input values, when issuer namespaces are configured, `get_current_subject()` and `get_on_behalf_of_user()` return namespaced identifiers, so a plugin treating `subject` or `acting_for` as the raw subject/header value gets a different identity from access control and ownership helpers.

Clarify in the plugin contract that user `subject` and `acting_for` use the access-control namespace format when applicable.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and plugins now receive service-client identities, acting-for users, and the roles access control grants, including roles from global rules; a wrong identity or role could affect plugin access or who owns resources it creates. Reverting stops future requests from receiving these values, but cannot undo access or resource changes that already occurred.

Blocking findings: docs/plugins.md:517


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

Comment thread docs/plugins.md Resolved
@uniqueg
uniqueg merged commit c59ea1e into dev Oct 26, 2026
30 checks passed
@uniqueg
uniqueg deleted the fix/plugin-principal-identity branch October 26, 2026 21:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: security Related to security

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Plugin Principal differs from access control identity

1 participant