Repository navigation
feat(auth): add userinfo_cache_ttl option - #669
Conversation
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]>
Reviewer's GuideAdds 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 updatessequenceDiagram
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
File-Level Changes
Possibly linked issues
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 #669 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 57 57
Lines 7395 7405 +10
=========================================
+ Hits 7395 7405 +10
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:
|
There was a problem hiding this comment.
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
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
Summary
security.auth.userinfo_cache_ttl(seconds; by defaultcache_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.Closes #615
Verification
ruff check,ruff format --check,mypy,ast-grep scan,mkdocs build --strict: pass.coverage run -m pytestwith MongoDB 7.0: 3382 passed, 1 skipped, 100% coverage.Declined review findings
userinfo_cache_ttl: 0withvalidate_userinfo: existing tests ofvalidate_userinfocover 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:
userinfo_cache_ttlthat independently controls user-info caching and defaults tocache_ttl.Bug Fixes:
Enhancements:
AuthConfig.Documentation:
Tests: