Repository navigation
OAuth: serialise token refreshes across processes sharing a token cache - #650
Merged
Merged
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_tokennever re-read the cache before refreshing, and its only lock was athreading.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.savenamed its temp file after the PID, so threads of one process saving at once shared the temp file and failed withFileNotFoundErroron rename.We saw all three in a bfabric-web-apps deployment: 4 gunicorn workers, and an RQ queue view that unpickles job arguments.
Fix
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 largerexpires_atis 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,WebappClientexchange) 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.Behaviour changes
expires_atloses to a cached one that has it; on equal expiry the cached token is kept.<name>.lockfile appears next to each token cache.Tests
TestSharedTokenCache:spawntest (markedslow) shows exactly one refresh.test_token_cache.py:.tmpfiles;FileNotFoundErrors.tests/bfabric1309 passed andtests/bfabric_scripts278 passed. ruff, black and basedpyright pass onbfabric/src/bfabric/oauth.