Skip to content

fix(auth): namespace subjects of several issuers - #512

Merged
uniqueg merged 4 commits into
devfrom
fix/issuer-namespaces
Oct 26, 2026
Merged

uniqueg merged 4 commits into
devfrom
fix/issuer-namespaces

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

With several trusted issuers, equal subjects of different issuers were the same user for access control, so they got each other's rights. Subjects are now namespaced by issuer.

  • Namespaced subjects: with several trusted issuers, subjects become <namespace>|<subject> (in rules user:<namespace>|<subject>). This applies to get_current_subject(), policies, resource roles, owners (also document owner fields) and plugin principals. By default the namespace is the issuer URL.
  • Single issuer unchanged: with one trusted issuer, subjects stay bare, as before.
  • Per-issuer settings: security.auth.issuers takes URLs or objects (IssuerConfig: issuer, namespace).
    • Set namespace to choose a shorter one.
    • Set namespace: "" to keep an issuer's subjects bare, e.g., for the first issuer when a second one is added, so that stored rules stay valid.
  • Collisions refused at config load: issuers that share a namespace, more than one bare issuer, the same issuer listed with different settings, and namespaces (or default URL namespaces) containing |, commas or line breaks. A bare subject containing | next to namespaced issuers is not identified: enforced operations answer 401.
  • Service clients: get_on_behalf_of_user() namespaces named users with the service client's issuer, and answers 400 if it can't.
  • Helpers: namespace_subject() and get_client_issuer() in foca.security.auth; AuthConfig.issuer_urls and AuthConfig.get_namespaces().
  • Sharing API docs: default namespaces contain slashes, so the documented userId path parameter gets format: path and the rules use users/*, as for groups.
  • Startup warning: the warning about several issuers now covers only group claim values, which are still not namespaced.
  • Docs:
    • a section "Several trusted issuers" in the authentication guide, with a tip on going from one issuer to two (keeping the old issuer bare, or rewriting stored subjects);
    • the config page;
    • access control notes;
    • a breaking-change section in "Migrating to 0.18.0" (including the type change of issuers to Sequence[str | IssuerConfig]).

Per-issuer audience, group claims and user info claims follow in #510.

Closes #509

Verification

Run locally on c2d510e:

  • ruff check and ruff format --check: pass.
  • mypy: pass.
  • pytest -m "not mongodb": 2764 passed, 1 skipped, 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 c2d510e: 27 checks pass, and 3 are skipped as intended.

Review: two rounds of adversarial and quality review.

  • Round 1 (fixed in 1f09cd9):
    • namespaced users couldn't be addressed via the documented sharing API, because of the slashes;
    • namespaces were recomputed per issuer;
    • an enforcement-level test of unidentified subjects was missing;
    • the error message for named users was inaccurate;
    • a migration note on the issuers type was missing;
    • a duplicated docs line.
  • Round 2 (fixed in 6383502): docs only.
    • The migration notes are split into bullets, with a note on proxies that merge slashes.
    • Docstring wording and rewrapping.

Sourcery: 2 findings, both fixed in c2d510e.

  • Namespaces are limited to 256 characters, so that namespaced subjects fit into policy rules.
  • The test of the startup warning checks its new wording.

Declined review findings

  • Cache the namespaces: declined. get_namespaces() walks a few entries per call, which is negligible next to token validation. The config models don't validate assignment, so a cache could go stale when apps or tests change issuers. The docstring says that such changes are not validated.
  • Restructure the "Several trusted issuers" section further and split test_namespaced: declined, as cosmetic. The section is one paragraph per topic plus a tip, and the test covers one behaviour (named users) in two cases.
  • issuer: object instead of Any in namespace_subject(): declined. Claims are untyped (dict[str, Any]), and the docstring says that any value is accepted.

🤖 Generated with Claude Code

uniqueg and others added 3 commits October 26, 2026 02:17
With several trusted issuers, subjects are now namespaced by issuer as
<namespace>|<subject>, so that equal subjects of different issuers are
different users in policies, resource roles and owners. Before, they
got each other's rights.

Issuers may be listed with settings of their own (IssuerConfig): the
namespace defaults to the issuer with several issuers and to none with
one, so single-issuer apps are unchanged; an empty namespace keeps the
subjects of an issuer bare, e.g., the first one when a second is
trusted. Issuers with the same namespace, or several bare ones, are
refused at config load. get_on_behalf_of_user() namespaces named users
with the service client's issuer, and namespace_subject() lets apps
name users the same way. Bare subjects with '|' next to namespaced ones
are not identified. The docs describe the migration to two issuers.

Closes #509

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Route namespaced users, which contain the issuer and thus slashes,
  in the documented sharing API (userId with format: path, rules with
  users/*), with a test of two issuers and of bare subjects that look
  namespaced (401).
- Compute the namespaces of all issuers in one pass (get_namespaces())
  instead of per issuer and request.
- Clearer error for named users that cannot be identified, docstring
  fixes, a migration note on the issuers type, and a check for bare
  subjects with '|' before keeping an issuer bare.
- Fix a duplicated line in the deployment docs.

Refs #509

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Split the migration notes into one bullet per change, note proxies that
merge slashes, rewrap edited bullets and fix docstrings (unvalidated
changes of issuers, typo, wording).

Refs #509

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

This PR isolates equal subjects across multiple trusted issuers by deriving validated per-issuer namespaces and applying them consistently throughout authentication, access control, ownership, resource roles, and service-client impersonation, while retaining bare subjects for single-issuer deployments. It also updates routing, tests, configuration APIs, warnings, and migration documentation for the new behavior.

Sequence diagram for namespaced subject enforcement

sequenceDiagram
    participant Token as ValidatedToken
    participant Auth as foca.security.auth
    participant Enforcement as AccessControl
    participant Policy as PolicyEnforcer

    Token->>Auth: get_namespaces()
    Auth-->>Enforcement: namespace_subject(subject, issuer)
    Enforcement-->>Policy: get_current_subject()
    Policy->>Policy: enforce namespaced user subject
    Policy-->>Enforcement: allow or deny access

    alt single trusted issuer
        Auth-->>Enforcement: bare subject
    else multiple trusted issuers
        Auth-->>Enforcement: namespace|subject
    end
Loading

Sequence diagram for service-client user impersonation

sequenceDiagram
    participant Client as ServiceClient
    participant Access as AccessControl
    participant Auth as foca.security.auth
    participant Policy as PolicyEnforcer

    Client->>Access: get_on_behalf_of_user(user)
    Access->>Auth: get_client_issuer(client, auth)
    Auth-->>Access: trusted client issuer
    Access->>Auth: namespace_subject(user, issuer, auth)
    alt user can be identified
        Auth-->>Access: namespace|user or bare user
        Access-->>Policy: attributed user
    else user cannot be identified
        Auth-->>Access: None
        Access-->>Client: 400 Bad Request
    end
Loading

File-Level Changes

Change Details Files
Introduce issuer-aware subject namespacing while preserving single-issuer behavior and supporting explicit per-issuer namespaces.
  • Add IssuerConfig, flexible issuer configuration, namespace derivation, duplicate/conflict validation, and issuer URL helpers.
  • Namespace current subjects, policy principals, owners, resource roles, and service-client on-behalf-of users; reject ambiguous or unidentifiable subjects.
  • Expose namespace_subject() and get_client_issuer() for applications that name users or resolve service-client issuers.
  • Update issuer and service-client handling to use normalized issuer URLs and namespaces.
foca/models/config.py
foca/security/auth.py
foca/security/access_control/enforcement.py
foca/security/access_control/register_access_control.py
Adapt access-control routing and behavior for namespaced subjects, including issuer namespaces that contain URL slashes.
  • Use path parameters and wildcard policies for user role endpoints.
  • Add enforcement coverage for cross-issuer subject isolation and ambiguous bare subjects.
  • Add ownership and service-client tests covering namespaced users, routing, and invalid identifiers.
  • Update the multi-issuer startup warning to concern only unnamespaced group claim values.
tests/models/test_config.py
tests/security/access_control/test_enforcement.py
tests/security/access_control/test_ownership_server.py
tests/security/access_control/test_register_access_control.py
tests/security/access_control/test_service_clients.py
tests/security/test_auth.py
Document configuration, migration, operational, and API implications of multi-issuer subject namespacing.
  • Document default and custom namespaces, collision restrictions, bare-subject compatibility, and migration strategies.
  • Explain path handling and proxy slash-merging concerns for namespaced users.
  • Update access-control, deployment, and authentication warnings and examples.
  • Document the issuers type change and new IssuerConfig model.
docs/authentication.md
docs/access-control.md
docs/configuration/auth.md
docs/configuration/access-control.md
docs/deployment.md
docs/migration-0.18.md

Assessment against linked issues

Issue Objective Addressed Explanation
#509 Prevent equal subjects from different trusted issuers from mapping to the same access-control identity, including in policies, ownership records, plugin principals, and users named by service clients. ✅
#509 Preserve single-issuer behavior and support per-issuer namespaces, including an empty namespace for one issuer when multiple issuers are trusted; reject namespace configurations that could collide. ✅
#509 Document the migration impact on stored subjects when adding a second issuer and explain how to keep the original issuer's subjects bare. ✅

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 (bcb9c3b) to head (c2d510e).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #512   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           55        55           
  Lines         6494      6558   +64     
=========================================
+ Hits          6494      6558   +64     
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 10:18

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

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

## Individual Comments

### Comment 1
<location path="foca/security/auth.py" line_range="273" />
<code_context>
+    namespace = namespaces[issuer]
+    if namespace is None:
+        return None if NAMESPACE_SEPARATOR in subject else subject
+    return f"{namespace}{NAMESPACE_SEPARATOR}{subject}"
+
+
</code_context>
<issue_to_address>
**Namespaced users are denied access**

When a trusted issuer’s namespace and a valid subject together exceed `MAX_RULE_VALUE_LENGTH`, `namespace_subject()` returns an over-limit value, which `is_permitted()` rejects and `add_resource_role()` cannot accept; the issuer configuration is still accepted, but users cannot pass access control or receive resource roles or ownership.

Validate that configured namespaces leave room for allowed subjects, and reject any namespaced subject that exceeds `MAX_RULE_VALUE_LENGTH` before authorization or role assignment.

Also at `foca/models/config.py:1377`.
</issue_to_address>

### Comment 2
<location path="tests/security/access_control/test_register_access_control.py" line_range="619" />
<code_context>
         self, caplog: pytest.LogCaptureFixture, issuers: list[str], warned: bool
     ) -> None:
-        """Subjects of several issuers may collide, which is warned about."""
+        """Group claim values of several issuers may collide (warned about)."""
         config = Config(
             security=SecurityConfig(
</code_context>
<issue_to_address>
**Issuer warning test accepts stale warning**

When the multiple-issuer warning regresses to the old subject-only message, when the warning still says subjects can collide but omits group claim values, `test_several_issuers` passes: its assertion at line 631 checks only for the generic phrase `trusted token issuers`, which the old warning also contains.

Assert that the warning identifies group claim values as unscoped, and does not claim that subjects are unscoped.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and access-control checks now use issuer-namespaced subjects, so an incorrect mapping could attribute a request to the wrong user and grant that user another user's rights. Reverting restores the old subject interpretation, but role grants or owner values written with namespaced subjects can remain stored and may need cleanup.

Blocking findings: foca/security/auth.py:273, tests/security/access_control/test_register_access_control.py:619


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

Comment thread foca/security/auth.py Resolved
Namespaces have at most 256 characters, also issuers used as default
namespaces, so that namespaced subjects fit into policy rules (1024
characters per value); longer namespaced subjects are denied, as long
bare ones are (Sourcery). The test of the startup warning about several
issuers checks its new wording.

Refs #509

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit f7e2111 into dev Oct 26, 2026
30 checks passed
@uniqueg
uniqueg deleted the fix/issuer-namespaces branch October 26, 2026 10:42
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.

fix(auth): namespace subjects of several issuers

1 participant