Skip to content

feat(auth): add claims from user info - #308

Merged
uniqueg merged 5 commits into
devfrom
feat/userinfo-claims
Oct 19, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/userinfo-claims

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Some identity providers provide group claims via user info only, not in access tokens. LS Login is one of them: its access tokens carry sub, aud (the client ID), scope etc., but eduperson_entitlement is only available via user info. Access control based on group claims (access_control.claim_groups / group_mapping, e.g., an admin role from an entitlement) therefore cannot be used with LS Login. This came up when checking whether cloud-registry's permission model (elixir-cloud-aai/cloud-registry#62) can be implemented with FOCA 0.14.0: everything else works with config and the existing helpers.

This PR adds security.auth.userinfo_claims:

  • Listed claims that a validated token lacks are added from the issuer's user info endpoint (after local signature verification). Claims of the token are never replaced; user info is not requested if the token has all listed claims.
  • The user info needs to report the token's subject (as with validate_userinfo).
  • Unless validate_userinfo is set (which fetches user info on every validation to detect revoked tokens), user info is cached per token (by SHA-256 hash) for cache_ttl seconds, but not beyond the token's expiry, for at most 1000 tokens.
  • Opt-in; default [], so behavior is unchanged.

Docs: configuration reference, authentication guide (validation step and a tip with the LS Login example) and access control guide (group claims).

Verification

  • pytest: all pass (18 tests for userinfo_claims, 1 extended) except the 7 tests marked mongodb, which need a live MongoDB (CI runs them); coverage of foca 100%.
  • ruff check, ruff format --check, mypy foca, mkdocs build --strict: pass.
  • End to end: feat!: add owner-based access control cloud-registry#66 builds the app from its real config with a mock LS Login that serves entitlements via user info only; its 11 access control tests pass with this branch, and 7 of them fail without userinfo_claims (admins are not recognized).
  • Sourcery review: 5 findings fixed in dba2a5a (subject required, claims copied, per-app cache_ttl honored, cache guarded by a lock, non-numeric exp not cached), 3 declined with reasons; threads resolved.
  • CI on dba2a5a: all checks pass.
  • Merged locally on top of dev together with feat(api)!: keep operation fields set in specs #310 and feat(access-control): add configured policies #311 (in that order) without conflicts: 684 tests pass.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Support enriching validated authentication claims from user info so identity-provider group claims can be used for access control.

New Features:

  • Add optional authentication configuration to populate missing token claims from the issuer’s user info endpoint.

Enhancements:

  • Preserve token claims while validating the user info subject and cache user info per token within configured TTL, token expiry, and cache-size limits.
  • Enable access-control group and role mappings to use claims supplied only through user info.

Documentation:

  • Document user-info claim enrichment in authentication, access-control, and configuration guides.

Tests:

  • Add coverage for user-info claim enrichment, validation, caching, subject checks, expiry, and cache limits.

Some identity providers, such as LS Login, provide group claims (e.g.,
eduperson_entitlement) via user info only, not in access tokens, so
that access control based on group claims (claim_groups) cannot be
used with them.

Add security.auth.userinfo_claims: listed claims that a validated token
lacks are added from the issuer's user info endpoint, which needs to
report the token's subject. Claims of the token are never replaced.
Unless validate_userinfo is set, user info is cached per token for
cache_ttl seconds, but not beyond the token's expiry, and for at most
1000 tokens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR adds opt-in user-info claim enrichment after local JWT verification, with subject validation, token-claim precedence, bounded expiry-aware caching, and uncached revocation checks when configured; documentation and tests cover the new authentication and group-access-control behavior.

Sequence diagram for user-info claim enrichment during token validation

sequenceDiagram
    participant Client
    participant Auth as validate_token
    participant JWT as Local JWT verification
    participant Cache as _userinfo_cache
    participant IdP as UserInfo endpoint

    Client->>Auth: validate_token(token)
    Auth->>JWT: _verify_signature(token)
    JWT-->>Auth: verified claims
    alt configured claims are missing
        Auth->>Cache: lookup SHA-256 token hash
        alt valid cached user info
            Cache-->>Auth: cached user info
        else cache miss
            Auth->>IdP: GET user info with Bearer token
            IdP-->>Auth: user info including sub
            Auth->>Auth: verify userinfo sub matches token sub
            Auth->>Cache: cache until cache_ttl or token expiry
        end
        Auth->>Auth: add only missing claims
    end
    Auth-->>Client: claims
Loading

State diagram for user-info retrieval and caching

stateDiagram-v2
    [*] --> LocalVerification
    LocalVerification --> Complete: all userinfo_claims present
    LocalVerification --> CacheLookup: claims missing
    LocalVerification --> FetchUserInfo: validate_userinfo enabled
    CacheLookup --> UseCachedInfo: unexpired entry
    CacheLookup --> FetchUserInfo: cache miss or expired
    FetchUserInfo --> Reject: userinfo sub differs
    FetchUserInfo --> CacheUserInfo: subject matches and caching enabled
    FetchUserInfo --> EnrichClaims: validate_userinfo enabled
    CacheUserInfo --> EnrichClaims
    UseCachedInfo --> EnrichClaims
    EnrichClaims --> Complete: token claims take precedence
    Complete --> [*]
    Reject --> [*]
Loading

File-Level Changes

Change Details Files
Adds opt-in enrichment of validated JWT claims from the issuer’s user info endpoint.
  • Introduces security.auth.userinfo_claims, defaulting to an empty list.
  • Fetches user info only after local JWT verification and only when configured claims are absent.
  • Preserves token claims when the same claim is present in both sources.
  • Requires the user info subject to match the verified token subject.
foca/models/config.py
foca/security/auth.py
Adds bounded, expiry-aware caching for user info lookups while preserving revocation-check behavior.
  • Caches responses by SHA-256 token hash for cache_ttl, capped at token expiry.
  • Bounds storage to 1000 tokens and removes expired entries before eviction.
  • Disables caching when validate_userinfo is enabled so every validation rechecks the issuer.
foca/security/auth.py
Documents configuration and usage of user-info claims for authentication and group-based access control.
  • Adds the new setting to the authentication configuration reference.
  • Describes claim enrichment in the authentication validation flow and returned token claims.
  • Documents the LS Login entitlement example and its use with group claims.
docs/configuration/auth.md
docs/authentication.md
docs/access-control.md
Adds comprehensive tests for enrichment, validation, caching, and default behavior.
  • Covers missing, configured, overlapping, and token-present claims.
  • Verifies signature ordering, subject mismatch, fetch failures, TTL and token-expiry limits, cache bounds, eviction, and uncached validation.
  • Extends configuration default assertions.
tests/security/test_auth.py

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 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (99030b8) to head (dba2a5a).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #308   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines         1322      1356   +34     
=========================================
+ Hits          1322      1356   +34     
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 19, 2026 21:21

@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 8 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="379-381" />
<code_context>
         headers={"Authorization": f"Bearer {token}"},
     )
-    if not isinstance(userinfo, dict) or userinfo.get("sub") != subject:
+    if not isinstance(userinfo, dict) or userinfo.get("sub") != claims.get(
+        "sub"
+    ):
         raise Unauthorized("User info does not match JWT subject")
+    lifetime = min(conf.cache_ttl, float(claims["exp"]) - time.time())
</code_context>
<issue_to_address>
**Unbound user info accepted**

When `claim_identity` is configured to a claim other than `sub` and both the token and user-info response omit `sub`, `_get_userinfo` compares two missing `sub` values as equal and accepts the response, so `_validate` adds claims that were not bound to the token subject and access control can grant roles from that user info.

Require a present token `sub` and user-info `sub` before accepting the response.
</issue_to_address>

### Comment 2
<location path="foca/security/auth.py" line_range="148" />
<code_context>
         )
+        for claim in missing_claims:
+            if claim in userinfo:
+                claims[claim] = userinfo[claim]
     return claims

</code_context>
<issue_to_address>
**Mutated claims persist across requests**

When application code mutates a mutable user-info-derived claim returned for a token, `_validate` assigns cached user-info values into `claims` by reference, and `_get_userinfo` returns the cached dictionary directly, so the mutation changes the cached claim and later validations use caller-modified values for access control.

Copy mutable user-info claim values before adding them to the returned claims.

Also at `foca/security/auth.py:149`, `foca/security/auth.py:372-374`, `foca/security/auth.py:393`.
</issue_to_address>

### Comment 3
<location path="foca/security/auth.py" line_range="371-372" />
<code_context>
     """
+    key = hashlib.sha256(token.encode("utf-8")).hexdigest()
+    if not conf.validate_userinfo:
+        cached = _userinfo_cache.get(key)
+        if cached is not None and time.monotonic() < cached[0]:
+            return cached[1]
     userinfo = _fetch_json(
</code_context>
<issue_to_address>
**Stale claims outlive configured TTL**

When the same token is validated under app configurations with different `cache_ttl` values and an entry cached under a longer TTL is still live, `_get_userinfo` accepts the shared cache entry using only its saved deadline, so an app with a shorter or zero `cache_ttl` reuses stale user-info claims beyond its configured freshness window.

Apply the current app's `cache_ttl` when checking entries, or isolate cache entries by app configuration.

Also at `foca/security/auth.py:384-392`.
</issue_to_address>

### Comment 4
<location path="foca/security/auth.py" line_range="389" />
<code_context>
+        now = time.monotonic()
+        for cached_key, (valid_until, _) in list(_userinfo_cache.items()):
+            if valid_until <= now:
+                del _userinfo_cache[cached_key]
+        while len(_userinfo_cache) >= USERINFO_CACHE_SIZE:
+            del _userinfo_cache[next(iter(_userinfo_cache))]
</code_context>
<issue_to_address>
**Concurrent cache cleanup fails**

When multiple validations clean expired entries or insert user-info entries while the cache is near capacity, concurrent cleanup and insertion in `_get_userinfo` are not atomic, so one request can delete an entry another request already removed, raising `KeyError`; concurrent size checks can also exceed `USERINFO_CACHE_SIZE`. Requests then fail with server errors.

Protect cache lookup, cleanup, eviction, and insertion with synchronization.

Also at `foca/security/auth.py:391`.
</issue_to_address>

### Comment 5
<location path="foca/security/auth.py" line_range="384" />
<code_context>
+    ):
         raise Unauthorized("User info does not match JWT subject")
+    lifetime = min(conf.cache_ttl, float(claims["exp"]) - time.time())
+    _userinfo_cache.pop(key, None)
+    if not conf.validate_userinfo and lifetime > 0:
+        now = time.monotonic()
</code_context>
<issue_to_address>
**Malformed expiry causes server error**

When `allow_expired` is enabled, a signed token has a non-numeric `exp`, and user-info retrieval is triggered, `float(claims["exp"])` raises an uncaught `ValueError` while caching user info, so the request fails with a server error instead of an authorization failure.

Reject a non-numeric `exp` as an authorization failure before calculating the cache lifetime.
</issue_to_address>

### Comment 6
<location path="foca/models/config.py" line_range="774" />
<code_context>
     claim_identity: str = "sub"
     algorithms: list[str] = ["RS256"]
     validate_userinfo: bool = False
+    userinfo_claims: list[str] = []
     timeout: float = Field(default=10, gt=0)
     cache_ttl: float = Field(default=300, ge=0)
</code_context>
<issue_to_address>
**Old instances reject new config**

When a shared configuration containing `userinfo_claims` reaches an old-version instance during a rolling deploy or rollback, an old-version instance loading this configuration fails Pydantic validation because its `AuthConfig` does not define `userinfo_claims` and `FOCABaseConfig` forbids extra fields. The instance cannot start, so a config-first rollout or rollback while the setting remains deployed takes that instance out of service.

Document and enforce a staged rollout: upgrade all instances before adding the setting, and remove it before rolling back to a version that does not recognize it.
</issue_to_address>

### Comment 7
<location path="foca/security/auth.py" line_range="374" />
<code_context>
+        cached = _userinfo_cache.get(key)
+        if cached is not None and time.monotonic() < cached[0]:
+            return cached[1]
     userinfo = _fetch_json(
         url=url,
         conf=conf,
</code_context>
<issue_to_address>
**Provider outage amplifies requests**

When the user-info endpoint is unavailable and requests arrive for tokens without a valid cached entry, `_get_userinfo` does not cache failed fetches or apply a circuit breaker, so every cache miss during an identity-provider outage calls `_fetch_json` and waits up to `conf.timeout` before rejecting the request. A burst of protected requests therefore repeatedly hits the failing endpoint and returns authorization failures instead of quickly shedding load.

Add bounded failure backoff or a circuit breaker for repeated user-info endpoint failures while continuing to fail closed.
</issue_to_address>

### Comment 8
<location path="foca/security/auth.py" line_range="371-374" />
<code_context>
     """
+    key = hashlib.sha256(token.encode("utf-8")).hexdigest()
+    if not conf.validate_userinfo:
+        cached = _userinfo_cache.get(key)
+        if cached is not None and time.monotonic() < cached[0]:
+            return cached[1]
     userinfo = _fetch_json(
         url=url,
         conf=conf,
</code_context>
<issue_to_address>
**Concurrent misses duplicate requests**

When several requests validate the same token before its user info has been cached, requests for the same uncached token can all miss before any one finishes fetching and populating the cache, so each sends a user-info request. If the identity provider limits the burst, some validations fail with `Unauthorized` even when another request succeeds.

Coalesce concurrent cache misses for the same token so callers share one in-flight fetch.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 8 findings to address first, and configured user-info claims can feed access-control decisions, so an incorrect or misattributed group claim could grant access and expose protected data; reverting stops future use but cannot undo disclosures that already occurred.

Blocking findings: foca/security/auth.py:381, foca/security/auth.py:148, foca/security/auth.py:372, foca/security/auth.py:389, foca/security/auth.py:384, and 3 more


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

Comment thread foca/security/auth.py Resolved
Comment thread foca/security/auth.py Resolved
Comment thread foca/security/auth.py Resolved
Comment thread foca/security/auth.py Resolved
Comment thread foca/security/auth.py Resolved
Comment thread foca/models/config.py Resolved
Comment thread foca/security/auth.py Resolved
Comment thread foca/security/auth.py Resolved
uniqueg and others added 2 commits October 19, 2026 23:53
Address review findings on the user info cache:

- Require a subject in the token and a matching one in user info.
- Copy claims taken from user info, so that changes by callers do not
  affect cached user info.
- Honor the current app's cache_ttl for cached entries.
- Guard cache access with a lock.
- Do not cache user info for tokens with a non-numeric expiry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit b11cb41 into dev Oct 19, 2026
13 checks passed
@uniqueg
uniqueg deleted the feat/userinfo-claims branch October 19, 2026 23:22
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.

1 participant