Skip to content

OAuth: serialise token refreshes across processes sharing a token cache - #650

Merged
Caushi merged 2 commits into
mainfrom
fix/oauth-shared-token-lock
Nov 18, 2026
Merged

Caushi merged 2 commits into
mainfrom
fix/oauth-shared-token-lock

Conversation

@Caushi

@Caushi Caushi commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Problem

Several processes sharing one token cache file (gunicorn workers of a web app, an RQ worker that unpickled a client, several CLI processes) each refreshed with their own in-memory copy of the token. OAuthCredentialProvider._ensure_token never re-read the cache before refreshing, and its only lock was a threading.Lock.

B-Fabric rotates the refresh token on every refresh, so only the first refresh succeeds and the others get invalid_grant. If a rotated token is presented again more than 10 s later, the server treats it as reuse and revokes all refresh tokens of that user and client (OAuthConstants.REFRESH_TOKEN_REUSE_GRACE_SECONDS, OAuthService.revokeAllOnRefreshTokenReuse).

Two related bugs:

  • __init__ always wrote an explicitly passed token over the cache. Unpickling goes through __init__, so unpickling a stale client overwrote a newer token in the shared file.
  • TokenCache.save named its temp file after the PID, so threads of one process saving at once shared the temp file and failed with FileNotFoundError on rename.

We saw all three in a bfabric-web-apps deployment: 4 gunicorn workers, and an RQ queue view that unpickles job arguments.

Fix

  • Refresh under a file lock. When a cache path is set and the token is missing or expired, the provider takes flock(LOCK_EX) on <cache>.lock (0o600). Under the lock it re-reads the cache and adopts the cached token if it expires later. It refreshes only if still needed, and saves before releasing the lock. While the in-memory token is valid there is no file I/O and no lock.
  • __init__. Of an explicit token and the cached one, the one with the larger expires_at is kept. The cache is written only if the explicit token is newer, or the cache is empty or unreadable. Fresh login tokens (PKCE, device code, WebappClient exchange) still win.
  • TokenCache.save. Each save gets a unique temp file (mkstemp, 0o600) in the cache directory. The replace stays atomic, and the temp file is removed on failure.
  • Windows. The lock does nothing on Windows, which the package does not support; importing the module still works there.

Behaviour changes

  • A passed-in token replaces the cache only if it expires later. A token without expires_at loses to a cached one that has it; on equal expiry the cached token is kept.
  • A <name>.lock file appears next to each token cache.
  • Callers that point several identities at the same cache file could now pick up each other's token, where before they overwrote each other. The default per-identity cache paths are not affected.

Tests

  • TestSharedTokenCache:
    • a second provider adopts the first one's refreshed token without calling the endpoint;
    • an unpickled stale token neither overwrites the file nor gets used;
    • a newer explicit token wins and is saved;
    • a valid token takes no lock and reads no file;
    • a three-process spawn test (marked slow) shows exactly one refresh.
  • test_token_cache.py:
    • 16 threads × 20 saves to one cache raise nothing and leave no .tmp files;
    • a failed rename leaves no temp file.
  • Without the fix, the three-process test sees the same refresh token presented three times, and the thread test hits 15 FileNotFoundErrors.
  • With the fix: tests/bfabric 1309 passed and tests/bfabric_scripts 278 passed. ruff, black and basedpyright pass on bfabric/src/bfabric/oauth.
  • nox was not run.

Claudio Cannizzaro and others added 2 commits November 17, 2026 15:15
B-Fabric rotates refresh tokens and, once a rotated one is presented again
after the 10 s grace period, revokes every refresh token of that user and
client. Processes sharing one token cache file (gunicorn workers, an RQ
worker that unpickled the client, several CLI processes) each refreshed
with their own in-memory copy, so all but the first got invalid_grant and
could trigger the revocation.

- When the in-memory token is expired (or missing), _ensure_token now
  takes an flock on <cache>.lock, adopts the cached token if it expires
  later, and only refreshes if that one is expired too; the refreshed
  token is persisted before the lock is released. A valid token still
  takes the fast path with no file I/O.
- __init__ keeps the newer (by expires_at) of an explicit token and the
  cached one, under the same lock, and persists only an explicit token
  that is newer. A fresh login/exchange token still wins; an unpickled
  stale token no longer overwrites a newer cache entry.
- client_credentials uses the same lock: harmless, and workers then share
  one fetched token instead of each fetching their own.
- flock is POSIX-only; on Windows (not a supported/CI'd platform) the
  lock is a no-op and behaviour is unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
The temp file was named .<name>.<pid>.tmp, so two threads of one process
(e.g. gunicorn with 16 threads) saving the same cache shared it: one
renamed it into place and the other's replace() failed with
FileNotFoundError. Use tempfile.mkstemp in the cache directory (0o600)
for a unique name per write, keep the atomic replace, and remove the
temp file if the write or rename fails.

Co-Authored-By: Claude <noreply@anthropic.com>
@Caushi
Caushi merged commit ec3bfb6 into main Nov 18, 2026
23 checks passed
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