Repository navigation
feat(auth): add claims from user info - #308
Conversation
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]>
Reviewer's GuideThis 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 validationsequenceDiagram
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
State diagram for user-info retrieval and cachingstateDiagram-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 --> [*]
File-Level Changes
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 #308 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 22 22
Lines 1322 1356 +34
=========================================
+ Hits 1322 1356 +34
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:
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
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
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]>
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),scopeetc., buteduperson_entitlementis 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:validate_userinfo).validate_userinfois set (which fetches user info on every validation to detect revoked tokens), user info is cached per token (by SHA-256 hash) forcache_ttlseconds, but not beyond the token's expiry, for at most 1000 tokens.[], 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 foruserinfo_claims, 1 extended) except the 7 tests markedmongodb, which need a live MongoDB (CI runs them); coverage offoca100%.ruff check,ruff format --check,mypy foca,mkdocs build --strict: pass.userinfo_claims(admins are not recognized).cache_ttlhonored, cache guarded by a lock, non-numericexpnot cached), 3 declined with reasons; threads resolved.devtogether 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:
Enhancements:
Documentation:
Tests: