From e2407cbeeec22694c32f03235adcafa1b79a20cd Mon Sep 17 00:00:00 2001 From: Claudio Cannizzaro Date: Tue, 17 Nov 2026 15:15:15 +0100 Subject: [PATCH 1/2] Serialise OAuth token refreshes across processes sharing a token cache 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 .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 --- bfabric/docs/changelog.md | 1 + .../src/bfabric/oauth/_credential_provider.py | 108 +++++++++---- .../bfabric/oauth/test_credential_provider.py | 145 +++++++++++++++++- 3 files changed, 224 insertions(+), 30 deletions(-) diff --git a/bfabric/docs/changelog.md b/bfabric/docs/changelog.md index 3e0fc4d78..d1fe68416 100644 --- a/bfabric/docs/changelog.md +++ b/bfabric/docs/changelog.md @@ -16,6 +16,7 @@ Minor breaking changes are still possible in `1.X.Y` but we try to announce them - `use_client` reports a `ValueError`, `OSError`, YAML error or HTTP error status from the command or from loading the config (e.g. no config file yet) as one `Error:` line instead of a traceback; the new `report_user_errors` context manager applies the same handling elsewhere. - An unknown config environment (e.g. a typo in `--config-env`) raises a `ValueError` listing the available environments instead of a `KeyError`. - On a CPU without the features polars needs (e.g. AVX2), importing polars through `bfabric` raises polars' `RuntimeWarning` telling you to install `polars[rtcompat]`, instead of the process dying with "Illegal instruction". +- `OAuthCredentialProvider` processes sharing one token cache file (web app workers, an unpickled client in a job worker, several CLI processes) no longer each refresh the same token: refreshes are serialised by a `.lock` file and the others adopt the refreshed token, so B-Fabric no longer rejects the reused refresh token and revokes all of the user's sessions. A token passed in (or restored by unpickling) only replaces the cached one if it expires later. ## \[1.24.0\] - 2026-10-05 diff --git a/bfabric/src/bfabric/oauth/_credential_provider.py b/bfabric/src/bfabric/oauth/_credential_provider.py index e4524d520..ff168ea45 100644 --- a/bfabric/src/bfabric/oauth/_credential_provider.py +++ b/bfabric/src/bfabric/oauth/_credential_provider.py @@ -8,15 +8,21 @@ * **Thread safety** — a :class:`threading.Lock` serialises token operations. * **Disk caching** — tokens are persisted to a JSON file (0o600) so they - survive process restarts. + survive process restarts. Processes sharing one cache file serialise refreshes + on a sibling ``.lock`` file, because B-Fabric rotates refresh tokens and revokes + every token of the user once a rotated one is presented again. * **BfabricAuth wrapping** — the current access token is returned as ``BfabricAuth(login="__oauth__", password=)``. """ from __future__ import annotations +import os +import sys import threading -from typing import TYPE_CHECKING +import time +from contextlib import contextmanager +from typing import TYPE_CHECKING, cast from authlib.common.errors import AuthlibBaseError from authlib.integrations.base_client.errors import OAuthError @@ -32,6 +38,8 @@ from bfabric.oauth._token_cache import TokenCache, compute_token_cache_path if TYPE_CHECKING: + from collections.abc import Iterator + from bfabric.config.base_url import BaseUrl from pathlib import Path @@ -46,6 +54,37 @@ def _canonical_token(token: dict[str, object]) -> dict[str, object]: return dict(OAuth2Token(dict(token))) +def _expires_at(token: dict[str, object] | None) -> float: + """Absolute expiry of *token*, the measure of which of two tokens is newer; ``0`` when unknown.""" + value = _canonical_token(token).get("expires_at") if token else None + return value if isinstance(value, int | float) else 0 + + +def _is_expired(token: dict[str, object], leeway: int) -> bool: + """Whether *token* expires within *leeway* seconds, by authlib's rule (no ``expires_at`` never expires).""" + expires_at = _expires_at(token) + return expires_at > 0 and expires_at - leeway < time.time() + + +@contextmanager +def _cache_file_lock(cache_path: Path | None) -> Iterator[None]: + """Hold an exclusive cross-process lock on ``.lock``; a no-op without a cache path.""" + # flock is POSIX-only; on Windows processes sharing a cache file stay unsynchronised as before. + if cache_path is None or sys.platform == "win32": + yield + return + import fcntl + + lock_path = cache_path.with_name(f"{cache_path.name}.lock") + lock_path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + os.close(fd) # closing the descriptor releases the lock + + class OAuthCredentialProvider: """Manages an OAuth 2.0 token and exposes it as :class:`BfabricAuth`. @@ -109,17 +148,20 @@ def __init__( leeway=leeway, ) - # Seed the session with an existing token (from caller or disk). - # An explicitly provided token (e.g. fresh from PKCE) always takes - # priority over a stale cache entry. - initial = token - if initial is None and self._cache: + # Seed the session with the newer of the caller's token and the cached one. A fresh login + # token (PKCE, device code, webapp exchange) expires later than any cached token, so it wins + # and is persisted; a stale one (e.g. from unpickling) must not overwrite a newer cache entry. + if self._cache is None: + if token is not None: + self._session.token = token + return + with _cache_file_lock(token_cache_path): cached = self._cache.load() - if cached is not None: - initial = cached - if initial is not None: - self._session.token = initial - self._persist() + if token is not None and (cached is None or _expires_at(token) > _expires_at(cached)): + self._session.token = token + self._persist() + elif cached is not None: + self._session.token = cached @classmethod def for_client_credentials( @@ -202,22 +244,28 @@ def get_auth(self) -> BfabricAuth: def _ensure_token(self) -> None: """Make sure the session has a valid token, fetching if needed. - Must be called while holding ``self._lock``. + Must be called while holding ``self._lock``. While the in-memory token is valid this does no + file I/O; otherwise it takes the cache file lock, adopts a newer token another process cached, + and only refreshes if that one is expired too. """ - token = self._session.token # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] + token = cast("dict[str, object] | None", self._session.token) + needs_token = not token or _is_expired(token, self._leeway) try: - if token: - self._strip_unusable_refresh_token() - # Let authlib check expiry + refresh/re-fetch as appropriate (operates on self.token). - logger.debug("Ensuring token is active (refresh if needed)") - self._session.ensure_active_token() # pyright: ignore[reportUnknownMemberType] - else: - # No token at all — perform the initial fetch. - logger.debug("No token present, fetching initial token") - token_endpoint: str | None = self._session.metadata.get("token_endpoint") # pyright: ignore[reportAny] - self._session.fetch_token(token_endpoint) # pyright: ignore[reportUnknownMemberType] - self._strip_unusable_refresh_token() - self._persist() + with _cache_file_lock(self._token_cache_path if needs_token else None): + if needs_token: + self._adopt_newer_cached_token() + if self._session.token: # pyright: ignore[reportUnknownMemberType] + self._strip_unusable_refresh_token() + # Let authlib check expiry + refresh/re-fetch as appropriate (operates on self.token). + logger.debug("Ensuring token is active (refresh if needed)") + self._session.ensure_active_token() # pyright: ignore[reportUnknownMemberType] + else: + # No token at all — perform the initial fetch. + logger.debug("No token present, fetching initial token") + endpoint = self._session.metadata.get("token_endpoint") # pyright: ignore[reportAny] + self._session.fetch_token(endpoint) # pyright: ignore[reportUnknownMemberType, reportAny] + self._strip_unusable_refresh_token() + self._persist() # authlib's errors extend Exception (not RuntimeError) and transport failures raise requests # exceptions, so either would otherwise escape the CLI's error handling as a raw traceback. # Wrap them in the domain error (a RuntimeError) with an actionable message. @@ -235,6 +283,14 @@ def _ensure_token(self) -> None: except RequestException as e: raise BfabricOAuthError(f"Could not reach the OAuth token endpoint ({self._token_url}): {e}") from e + def _adopt_newer_cached_token(self) -> None: + """Replace the session token with the cached one if another process stored a newer token.""" + cached = self._cache.load() if self._cache else None + current = cast("dict[str, object] | None", self._session.token) + if cached is not None and _expires_at(cached) > _expires_at(current): + logger.debug("Adopting newer token from cache") + self._session.token = cached + def _strip_unusable_refresh_token(self) -> None: """Drop the ``refresh_token`` from a client-credentials session token. diff --git a/tests/bfabric/oauth/test_credential_provider.py b/tests/bfabric/oauth/test_credential_provider.py index 9f739bff9..dc4640591 100644 --- a/tests/bfabric/oauth/test_credential_provider.py +++ b/tests/bfabric/oauth/test_credential_provider.py @@ -1,16 +1,22 @@ from __future__ import annotations +import fcntl +import json +import multiprocessing import pickle import threading import time +from types import SimpleNamespace import pytest from authlib.integrations.base_client.errors import OAuthError +from authlib.integrations.requests_client import OAuth2Session from requests.exceptions import ConnectionError as RequestsConnectionError from bfabric.config.bfabric_auth import OAUTH_LOGIN from bfabric.errors import BfabricOAuthError from bfabric.oauth._credential_provider import OAuthCredentialProvider +from bfabric.oauth._token_cache import TokenCache @pytest.fixture @@ -349,14 +355,12 @@ def do_fetch(*args, **kwargs): assert saved["access_token"] == "fresh" def test_supplied_token_preferred_over_disk_cache(self, tmp_path, mock_oauth2_session): - """Explicitly provided token takes precedence over stale disk cache.""" - import json - + """A freshly obtained token (expiring later than the cached one) wins and is persisted.""" cache_path = tmp_path / "token.json" cached = {"access_token": "from_disk", "expires_at": time.time() + 3600} cache_path.write_text(json.dumps(cached)) - supplied = {"access_token": "from_caller", "refresh_token": "rt", "expires_at": time.time() + 3600} + supplied = {"access_token": "from_caller", "refresh_token": "rt", "expires_at": time.time() + 7200} provider = OAuthCredentialProvider( client_id="id", client_secret="", @@ -442,3 +446,136 @@ def test_cache_path_survives(self, tmp_path): token_cache_path=cache_path, ) assert pickle.loads(pickle.dumps(provider))._token_cache_path == cache_path + + +def _expired_token() -> dict[str, object]: + return {"access_token": "old", "refresh_token": "rt0", "token_type": "Bearer", "expires_at": int(time.time()) - 100} + + +def _refreshed_token(n: object) -> dict[str, object]: + return {"access_token": f"at{n}", "refresh_token": f"rt{n}", "token_type": "Bearer", "expires_in": 3600} + + +def _refresh_provider(cache_path, token=None) -> OAuthCredentialProvider: + return OAuthCredentialProvider( + client_id="app-id", + client_secret="", + token_url="https://example.com/rest/oauth/token", + scope="", + grant_type="refresh_token", + token=token, + token_cache_path=cache_path, + ) + + +class TestSharedTokenCache: + """Providers in several processes share one cache file; B-Fabric rotates refresh tokens and revokes all of + a user's tokens when a rotated one is reused, so only one of them may refresh and the others adopt its token. + + Uses the real ``OAuth2Session`` with its HTTP POST to the token endpoint mocked. + """ + + @pytest.fixture + def token_endpoint(self, mocker): + calls = [] + + def post(url, data=None, **kwargs): + calls.append(data) + return SimpleNamespace(status_code=200, json=lambda: _refreshed_token(len(calls))) + + return mocker.patch.object(OAuth2Session, "post", side_effect=post) + + @pytest.fixture + def cache_path(self, tmp_path): + path = tmp_path / "tokens" / "token.json" + TokenCache(path).save(_expired_token()) + return path + + def test_second_provider_adopts_token_refreshed_by_first(self, cache_path, token_endpoint): + provider_a = _refresh_provider(cache_path) + provider_b = _refresh_provider(cache_path) + + auth_a = provider_a.get_auth() + assert token_endpoint.call_count == 1 + assert json.loads(cache_path.read_text())["access_token"] == "at1" + + auth_b = provider_b.get_auth() + assert token_endpoint.call_count == 1 + assert auth_b.password.get_secret_value() == auth_a.password.get_secret_value() == "at1" + + def test_unpickled_stale_token_does_not_overwrite_newer_cache(self, cache_path, token_endpoint): + pickled = pickle.dumps(_refresh_provider(cache_path)) + newer = {"access_token": "newer", "refresh_token": "rt-newer", "expires_at": int(time.time()) + 3600} + TokenCache(cache_path).save(newer) + + restored = pickle.loads(pickled) + + assert json.loads(cache_path.read_text()) == newer + assert restored.get_auth().password.get_secret_value() == "newer" + token_endpoint.assert_not_called() + + def test_explicit_newer_token_is_persisted(self, cache_path, token_endpoint): + fresh = {"access_token": "fresh", "refresh_token": "rt-fresh", "expires_in": 3600} + + provider = _refresh_provider(cache_path, token=fresh) + + assert json.loads(cache_path.read_text())["access_token"] == "fresh" + assert provider.get_auth().password.get_secret_value() == "fresh" + token_endpoint.assert_not_called() + + def test_valid_token_takes_no_file_lock(self, cache_path, token_endpoint, mocker): + provider = _refresh_provider(cache_path, token=_refreshed_token("valid")) + flock = mocker.patch("fcntl.flock") + load = mocker.spy(TokenCache, "load") + + assert provider.get_auth().password.get_secret_value() == "atvalid" + + flock.assert_not_called() + load.assert_not_called() + + def test_expired_token_refreshes_under_file_lock(self, cache_path, token_endpoint, mocker): + provider = _refresh_provider(cache_path) + flock = mocker.spy(fcntl, "flock") + + provider.get_auth() + + flock.assert_called_once() + assert cache_path.with_name("token.json.lock").stat().st_mode & 0o777 == 0o600 + + @pytest.mark.slow + def test_concurrent_processes_refresh_once(self, cache_path, tmp_path): + ctx = multiprocessing.get_context("spawn") + n_processes = 3 + barrier = ctx.Barrier(n_processes) + results = ctx.Queue() + counter_path = tmp_path / "refreshes.txt" + processes = [ + ctx.Process(target=_refresh_in_child, args=(cache_path, counter_path, barrier, results)) + for _ in range(n_processes) + ] + for process in processes: + process.start() + access_tokens = [results.get(timeout=30) for _ in processes] + for process in processes: + process.join(timeout=30) + assert process.exitcode == 0 + + assert counter_path.read_text().splitlines() == ["rt0"] + assert len(set(access_tokens)) == 1 + + +def _refresh_in_child(cache_path, counter_path, barrier, results) -> None: + """Child process: refresh through a fake token endpoint that records each refresh token presented.""" + + def post(self, url, data=None, **kwargs): + with counter_path.open("a") as f: + f.write(f"{data['refresh_token']}\n") + time.sleep(0.2) # widen the race window + return SimpleNamespace( + status_code=200, json=lambda: _refreshed_token(f"-{multiprocessing.current_process().pid}") + ) + + OAuth2Session.post = post # only patches this child process + provider = _refresh_provider(cache_path) + barrier.wait() + results.put(provider.get_auth().password.get_secret_value()) From 7624fb1f64d1f6820250e5127122cbaa63420a77 Mon Sep 17 00:00:00 2001 From: Claudio Cannizzaro Date: Tue, 17 Nov 2026 15:15:15 +0100 Subject: [PATCH 2/2] Give each TokenCache.save its own temporary file The temp file was named ...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 --- bfabric/docs/changelog.md | 1 + bfabric/src/bfabric/oauth/_token_cache.py | 21 ++++++++----- tests/bfabric/oauth/test_token_cache.py | 36 +++++++++++++++++++++++ 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/bfabric/docs/changelog.md b/bfabric/docs/changelog.md index d1fe68416..8ea1f64e0 100644 --- a/bfabric/docs/changelog.md +++ b/bfabric/docs/changelog.md @@ -17,6 +17,7 @@ Minor breaking changes are still possible in `1.X.Y` but we try to announce them - An unknown config environment (e.g. a typo in `--config-env`) raises a `ValueError` listing the available environments instead of a `KeyError`. - On a CPU without the features polars needs (e.g. AVX2), importing polars through `bfabric` raises polars' `RuntimeWarning` telling you to install `polars[rtcompat]`, instead of the process dying with "Illegal instruction". - `OAuthCredentialProvider` processes sharing one token cache file (web app workers, an unpickled client in a job worker, several CLI processes) no longer each refresh the same token: refreshes are serialised by a `.lock` file and the others adopt the refreshed token, so B-Fabric no longer rejects the reused refresh token and revokes all of the user's sessions. A token passed in (or restored by unpickling) only replaces the cached one if it expires later. +- `TokenCache.save` uses a unique temporary file per write, so several threads saving the same cache at once no longer fail with `FileNotFoundError`. ## \[1.24.0\] - 2026-10-05 diff --git a/bfabric/src/bfabric/oauth/_token_cache.py b/bfabric/src/bfabric/oauth/_token_cache.py index 9da3ac880..20c188068 100644 --- a/bfabric/src/bfabric/oauth/_token_cache.py +++ b/bfabric/src/bfabric/oauth/_token_cache.py @@ -5,6 +5,7 @@ import hashlib import json import os +import tempfile from pathlib import Path from typing import TYPE_CHECKING @@ -57,18 +58,24 @@ def save(self, token: dict[str, object]) -> None: The write is atomic: data is written to a temporary file (0o600) and then ``Path.replace``-d into place, so a concurrent reader (possibly in - another process sharing this cache path) never sees a torn file. + another process sharing this cache path) never sees a torn file. The + temporary name is unique per write, so concurrent writers (threads or + processes) never rename each other's file away. """ logger.debug("Saving token cache to {}", self._path) self._path.parent.mkdir(parents=True, exist_ok=True) data = json.dumps(token).encode() - tmp = self._path.with_name(f".{self._path.name}.{os.getpid()}.tmp") - fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + fd, tmp_name = tempfile.mkstemp(dir=self._path.parent, prefix=f".{self._path.name}.", suffix=".tmp") # 0o600 + tmp = Path(tmp_name) try: - _ = os.write(fd, data) - finally: - os.close(fd) - _ = tmp.replace(self._path) + try: + _ = os.write(fd, data) + finally: + os.close(fd) + _ = tmp.replace(self._path) + except BaseException: + tmp.unlink(missing_ok=True) + raise def clear(self) -> None: """Remove the cache file if it exists.""" diff --git a/tests/bfabric/oauth/test_token_cache.py b/tests/bfabric/oauth/test_token_cache.py index 4ba3e4d66..0af5fe5c5 100644 --- a/tests/bfabric/oauth/test_token_cache.py +++ b/tests/bfabric/oauth/test_token_cache.py @@ -3,6 +3,8 @@ import json import os import stat +import threading +from pathlib import Path import pytest @@ -61,6 +63,40 @@ def test_clear_removes_file(self, cache): def test_clear_when_no_file(self, cache): cache.clear() # should not raise + def test_concurrent_saves_from_threads(self, tmp_path): + """Threads of one process saving the same cache must not share a temp file (one would rename it away).""" + cache = TokenCache(tmp_path / "token.json") + tokens = [{"access_token": f"t{i}"} for i in range(16)] + barrier = threading.Barrier(len(tokens)) + errors = [] + + def save(token): + barrier.wait() + try: + for _ in range(20): + cache.save(token) + except Exception as e: # noqa: BLE001 + errors.append(e) + + threads = [threading.Thread(target=save, args=(token,)) for token in tokens] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert errors == [] + assert cache.load() in tokens + assert [p.name for p in tmp_path.iterdir()] == ["token.json"] + + def test_failed_save_leaves_no_temp_file(self, tmp_path, mocker): + cache = TokenCache(tmp_path / "token.json") + mocker.patch.object(Path, "replace", side_effect=OSError("boom")) + + with pytest.raises(OSError, match="boom"): + cache.save({"access_token": "x"}) + + assert list(tmp_path.iterdir()) == [] + class TestComputeTokenCachePath: def test_deterministic(self):