Skip to content

feat(auth): add userinfo_cache_ttl option - #669

Merged
uniqueg merged 3 commits into
devfrom
feat/615-userinfo-cache-ttl
Nov 4, 2026
Merged

uniqueg merged 3 commits into
devfrom
feat/615-userinfo-cache-ttl

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

  • New option security.auth.userinfo_cache_ttl (seconds; by default cache_ttl), so that changes of groups read from user info apply sooner, without fetching keys more often. AuthConfig.get_userinfo_cache_ttl() resolves it. The default doesn't change behaviour.
  • The age of cached user info now counts from before the request, and a slow response no longer replaces what a later request found, so that the time set is a real bound.
  • Docs: authentication ("Caching of user info": applies only to claims the token lacks; cost of short times), configuration reference.

Closes #615

Verification

  • ruff check, ruff format --check, mypy, ast-grep scan, mkdocs build --strict: pass.
  • coverage run -m pytest with MongoDB 7.0: 3382 passed, 1 skipped, 100% coverage.
  • Both reviewer subagents, then a second adversarial round (no high or medium findings in round 2).
  • CI: see the checks of this PR.

Declined review findings

  • A bullet in the 0.20.0 release notes: 0.20.0 is released, and this PR does no release preparation.
  • A test of userinfo_cache_ttl: 0 with validate_userinfo: existing tests of validate_userinfo cover fetching on each request.

🤖 Generated with Claude Code

Summary by Sourcery

Allow user-info caching to expire independently from discovery and key caches while preserving cache consistency during concurrent requests.

New Features:

  • Add a configurable userinfo_cache_ttl that independently controls user-info caching and defaults to cache_ttl.

Bug Fixes:

  • Prevent slow user-info requests from overriding newer cached results and ensure cache age is measured from request start.

Enhancements:

  • Clarify user-info caching behavior, claim precedence, process-local cache effects, and identity-provider request costs in the authentication documentation.
  • Expose user-info TTL resolution through AuthConfig.

Documentation:

  • Document the new user-info cache setting and its operational trade-offs in the authentication and configuration references.

Tests:

  • Add coverage for inherited, shorter, and longer user-info TTLs, invalid values, request-age handling, and concurrent response ordering.

Changes of a user's groups in user info apply only when the cached user
info expires, after cache_ttl, which also governs discovery documents and
keys. Add security.auth.userinfo_cache_ttl, by default cache_ttl.

Count the age of cached user info from before the request, and don't let
a slow response replace what a later request found, so that the time set
is a bound on how long changes take.

Closes #615

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds a userinfo_cache_ttl option that defaults to cache_ttl but can refresh user-info-derived claims independently from discovery documents and keys. The implementation resolves the effective TTL in AuthConfig, applies it to bounded per-token caching, timestamps entries from request initiation, and prevents slower requests from replacing newer results; documentation and comprehensive configuration/concurrency tests accompany the change.

Sequence diagram for user info cache refresh and safe concurrent updates

sequenceDiagram
    participant Request
    participant Auth as AuthConfig
    participant Cache as UserInfoCache
    participant IdP as IdentityProvider

    Request->>Auth: get_userinfo_cache_ttl()
    Auth-->>Request: userinfo_cache_ttl or cache_ttl
    Request->>Cache: Check token entry and TTL
    alt Cache entry is fresh
        Cache-->>Request: Return cached user info
    else Cache entry is expired or missing
        Request->>Cache: Record started = time.monotonic()
        Request->>IdP: _fetch_json(user info)
        IdP-->>Request: User info claims
        Request->>Cache: Recheck entry under lock
        alt Newer request already updated cache
            Cache-->>Request: Keep newer cached entry
        else No newer entry
            Request->>Cache: Store result with started + effective TTL
        end
        Request-->>Request: Return user info claims
    end
Loading

File-Level Changes

Change Details Files
Adds an independently configurable cache lifetime for user-info responses, while preserving the existing cache_ttl default.
  • Introduces nullable validation for userinfo_cache_ttl and resolves unset values through get_userinfo_cache_ttl().
  • Uses the resolved TTL for user-info cache expiry and token-expiry bounds.
  • Covers inherited, shorter, longer, zero, and invalid TTL configurations.
foca/models/config.py
foca/security/auth.py
tests/security/test_auth.py
Makes user-info cache freshness and concurrent updates follow stricter timing semantics.
  • Starts cache-age measurement before the identity-provider request.
  • Stores the request start time as the cache entry timestamp.
  • Avoids overwriting an entry created by a later request after a slower response completes.
  • Adds tests for request-age accounting and newer-entry preservation.
foca/security/auth.py
tests/security/test_auth.py
Documents user-info caching behavior, propagation limits, and configuration.
  • Explains that the setting affects only claims absent from the token.
  • Documents per-process caching, revocation propagation timing, request costs, timeout behavior, and validate_userinfo interaction.
  • Adds userinfo_cache_ttl to the authentication configuration reference and model documentation.
docs/authentication.md
docs/configuration/auth.md
foca/models/config.py
foca/security/auth.py

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 Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (2c47558) to head (2bb4a3b).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #669   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           57        57           
  Lines         7395      7405   +10     
=========================================
+ Hits          7395      7405   +10     
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 November 4, 2026 04:31

@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 5 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="728" />
<code_context>
     with _userinfo_cache_lock:
+        cached = _userinfo_cache.get(key)
+        if cached is not None and cached[0] > started:
+            return userinfo
         _userinfo_cache.pop(key, None)
         if not conf.validate_userinfo and lifetime > 0:
</code_context>
<issue_to_address>
**Revoked groups still authorize**

When an earlier user-info fetch completes after another request has cached newer user info for the same token, `_get_userinfo` returns its older `userinfo` instead of the newer cached value, and `_validate` merges the stale group claims into the request, so a revoked user can still be authorized.

Return the newer cached user info when its timestamp is later than the current request’s start time.
</issue_to_address>

### Comment 2
<location path="foca/security/auth.py" line_range="727-728" />
<code_context>
         lifetime = 0
     with _userinfo_cache_lock:
+        cached = _userinfo_cache.get(key)
+        if cached is not None and cached[0] > started:
+            return userinfo
         _userinfo_cache.pop(key, None)
         if not conf.validate_userinfo and lifetime > 0:
</code_context>
<issue_to_address>
**Older data repopulates the cache**

When a newer entry for the same token is evicted while an older request is still fetching and that older request completes before its cache lifetime expires, `_get_userinfo` finds no entry and stores the slow response, even if a later request had already cached newer user info that was subsequently evicted. That stale response is then served to later requests until its remaining TTL expires.

Track the latest request generation or start time per token independently of the evictable value entries, and do not cache responses older than that marker.
</issue_to_address>

### Comment 3
<location path="foca/security/auth.py" line_range="722" />
<code_context>
         raise _unauthorized("User info does not match JWT subject")
     try:
-        lifetime = min(conf.cache_ttl, float(claims["exp"]) - time.time())
+        lifetime = min(ttl, float(claims["exp"]) - time.time())
     except (TypeError, ValueError):
         lifetime = 0
</code_context>
<issue_to_address>
**Longer TTL causes early refetch**

When two authentication configurations in one process request the same token, and the shorter-TTL configuration populates the shared cache first, `lifetime = min(ttl, ...)` sets the shared entry’s expiry using the shorter TTL, so the longer-TTL configuration rejects that entry and refetches early; if the identity provider is unavailable, it returns 401.

Partition the user-info cache by configured TTL so one configuration’s expiry does not govern another’s entry.

Also at `foca/security/auth.py:704`, `foca/security/auth.py:737`.
</issue_to_address>

### Comment 4
<location path="foca/security/auth.py" line_range="737" />
<code_context>
             while len(_userinfo_cache) >= USERINFO_CACHE_SIZE:
                 del _userinfo_cache[next(iter(_userinfo_cache))]
-            _userinfo_cache[key] = (now, now + lifetime, userinfo)
+            _userinfo_cache[key] = (started, started + lifetime, userinfo)
     return userinfo
</code_context>
<issue_to_address>
**Expired entries evict live cache data**

When a user-info request takes longer than its configured TTL while the cache is full of still-valid entries, `_get_userinfo` inserts an entry whose expiry is already past, then a later fetch removes it. If the cache is full, the insertion evicts a still-valid entry first, causing avoidable refetches for unrelated tokens and extra identity-provider load.

Skip the cache insertion unless its computed expiry is later than the current monotonic time.
</issue_to_address>

### Comment 5
<location path="foca/security/auth.py" line_range="704" />
<code_context>
             cached = _userinfo_cache.get(key)
         now = time.monotonic()
-        if cached is not None and now < cached[1] and now - cached[0] < conf.cache_ttl:
+        if cached is not None and now < cached[1] and now - cached[0] < ttl:
             return cached[2]
+    # The age of the entry counts from before the request, and a slow response
</code_context>
<issue_to_address>
**Concurrent refreshes flood identity provider**

When a frequently used token's user-info entry expires while multiple requests for that token arrive concurrently, `_get_userinfo` releases `_userinfo_cache_lock` before `_fetch_json`, so concurrent requests that all miss an expired entry each fetch user info independently. With a short `userinfo_cache_ttl`, this creates bursts of identity-provider requests for the same token, potentially exhausting rate limits and causing authentication failures.

Coalesce concurrent refreshes for the same token, or otherwise limit refreshes so only one in-flight request fetches its user info.
</issue_to_address>

Linked issues

#615 feat(auth): add separate user-info cache TTL · 3 of 5 met · 2 to check by hand

# Requirement Status Notes
1 Add userinfo_cache_ttl, defaulting to cache_ttl. ✅ Met AuthConfig defines the option and get_userinfo_cache_ttl() falls back to cache_ttl; user-info caching uses the resolved value.
2 Document that each process or replica caches separately, so an admin removal can take up to the TTL to apply at different times. ✅ Met docs/authentication.md explains that each worker of each replica has its own cache and describes the resulting delay.
3 Test default inheritance and an explicit userinfo_cache_ttl value. ✅ Met Tests cover inherited settings and explicit shorter and longer TTLs.
4 Achieve 100% coverage. 👀 Check by hand (runtime) The PR description reports 100% coverage; confirm that result in the test or CI output.
5 Update the docs and pass mkdocs build --strict. 👀 Check by hand (runtime) The docs are updated, and the PR description reports the strict build passed; confirm the build result in CI.

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and if userinfo_cache_ttl is set too high, a token can continue to receive authorization based on stale user-info group claims after a group revocation, until that cache entry expires. Reverting restores the prior cache behavior but cannot undo access or data exposure during that window.

Blocking findings: foca/security/auth.py:728, foca/security/auth.py:728, foca/security/auth.py:722, foca/security/auth.py:737, foca/security/auth.py:704


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
uniqueg and others added 2 commits November 4, 2026 06:16
A slow response returned its old groups although a later request had
already cached newer ones, e.g., after a revocation. Responses slower
than the TTL no longer evict live entries of a full cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e-ttl

# Conflicts:
#	docs/configuration/auth.md
@uniqueg
uniqueg merged commit f692c7b into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/615-userinfo-cache-ttl branch November 4, 2026 05:50
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(auth): add separate user-info cache TTL

1 participant