Skip to content

fix(token): prevent reload loop from refresh-token rotation race - #1450

Open
solracsf wants to merge 2 commits into
mainfrom
fix/token-refresh-rotation-race
Open

solracsf wants to merge 2 commits into
mainfrom
fix/token-refresh-rotation-race

Conversation

@solracsf

@solracsf solracsf commented Jun 7, 2026 •

Copy link
Copy Markdown
Member

Fix #1449

After #1391 introduced proactive token refresh at half the token lifetime, users on rotating-refresh-token IdPs (reported with Authentikk #1175 and #1449 for context.) get bounced through the full OIDC re-login flow during active sessions, losing unsaved work.

TokenService::checkLoginToken() runs on every request (wired in Application::boot). Once the token passes half-life, every request, including parallel background polls (notifications, user_status heartbeat), attempts a refresh. With refresh-token rotation, two concurrent requests race: the winner refreshes and the IdP rotates/invalidates the old refresh token; the loser then presents that already-rotated token, which the IdP rejects (or treats as token-reuse and revokes the whole family).

The token can no longer be refreshed, so reauthenticate() issues a hard redirect.

The per-session lock added in #1391 didn't prevent this: its double-check read $this->session (a per-request in-memory snapshot), which is stale on non-locking session backends (Redis/memcached), exactly the setups where parallel requests aren't serialized.

🤖 AI (if applicable)

  • The content of this PR was reviewed and tests generated using AI

Signed-off-by: Git'Fellow <12234510+solracsf@users.noreply.github.com>
@solracsf
solracsf force-pushed the fix/token-refresh-rotation-race branch from 049c6d1 to 56c7353 Compare June 10, 2026 10:53
@solracsf
solracsf marked this pull request as draft June 10, 2026 10:56
…bsence

Signed-off-by: Git'Fellow <12234510+solracsf@users.noreply.github.com>
@solracsf
solracsf force-pushed the fix/token-refresh-rotation-race branch from 6aa6f52 to f97e9a4 Compare June 11, 2026 08:56
@solracsf
solracsf marked this pull request as ready for review June 11, 2026 09:05
@NK-IT-CLOUD

Copy link
Copy Markdown

We tested this PR (head f97e9a4, only the lib/ changes applied on top of 8.11.0) in production for ~90 minutes. Short version: the race fix works, but the no-logout-on-background part together with the throttle caused a regression for us, so we rolled back. Details below, in case they help.

Setup: Nextcloud 35.0.1, user_oidc 8.11.0, store_login_token = 1, Keycloak 26.7, access token lifetime 300 s. PHP sessions in Redis with redis.session.locking_enabled = 1, memcache.locking and memcache.distributed = Redis. Refresh token rotation is currently disabled on the IdP; we measured whether the same refresh token is redeemed more than once (IdP refresh events grouped by refresh token ID).

Before the patch (8.11.0): Over 8 days, 615 of ~2,300 refresh tokens were redeemed more than once (up to 13 times), always less than 1 s apart, same IdP session, same Nextcloud host. In the debug log it is two parallel background requests of the same browser session (e.g. POST /apps/notify_push/pre_auth and GET /ocs/v2.php/apps/notifications/...): both see "token is expiring", the lock serializes them, but the second one still refreshes with the already used refresh token because its re-check reads its own session snapshot. This happens even with Redis session locking enabled; presumably Nextcloud closes the session early in these requests.

With the patch, race: 43 of 44 refresh tokens were redeemed exactly once (90 min before: 2 of 31 redeemed 2× and 5×). One real concurrent case was adopted from the cache ("Token already refreshed by another request (cache)"), 48 proactive refreshes were throttled. So the core idea — re-reading from the distributed cache after taking the lock and refreshing with the freshest refresh token — fixes the race for us.

With the patch, regression: After the IdP session ended (the IdP session was ended by another app sharing it), the IdP rejected the refresh token ("Session not active"). With the patch, background requests kept the Nextcloud session ("reauthenticate skipped: not a top-level HTML navigation, keeping the session") and the same dead refresh token was retried roughly every 30 s (throttle TTL) with no end — 53 rejected attempts in ~30 min until we rolled back. The Nextcloud session stayed open without a valid IdP session. With 8.11.0 the same situation ends after a few attempts with a logout.

Suggestions:

  1. Would you consider splitting the PR? The race fix (cache mirror in storeToken() plus the cache re-check and freshest refresh token in refresh()) is small and solves the reported race on its own. The navigation classification / no-logout-on-background change and the throttle address different problems (Nextcloud site constantly reloading due to token refresh #1449, hammering a dead refresh token) and change behaviour that is security relevant.
  2. When the IdP rejects the refresh token with invalid_grant / an inactive session, the refresh token is dead. Instead of retrying it every 30 s, drop it from the session and cache, and end the Nextcloud session (or at least stop serving data: e.g. answer background requests with 401 without destroying the session, and force re-authentication on the next navigation). Otherwise an IdP-side logout or account disable is not enforced while background polls keep the session alive.
  3. In refreshOrAdopt(), an expired session token plus an active throttle marker returns the expired token (testGetTokenThrottlesRefreshOfExpiredToken). Concurrently with a successful refresh this can trigger reauthenticate() on a navigation and hand an expired token to apps requesting an exchanged token. For expired tokens, waiting for the lock and re-checking the cache seems safer; the throttle could apply to the proactive path and to failed refreshes only. ICache::add() would make the marker atomic.
  4. The cached entry (access and refresh token, encrypted) stays until its TTL after logout or token invalidation; deleting it on logout / in the token-invalidated listener would be cleaner.
  5. Without a distributed cache the fix silently has no effect (NullCache), and with APCu only per node. Maybe document the requirement, or fall back to ISession::reopen() after acquiring the lock to re-read the session.
  6. The unit tests mock the cache per step. A test with two service instances sharing an in-memory cache, each holding the same stale session token, would cover the actual interleaving (exactly one IdP call), plus a test that a rejected refresh token is not retried indefinitely.

Happy to test an updated version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

3. to review bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Nextcloud site constantly reloading due to token refresh

2 participants