Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions bfabric/docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ 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 `<cache>.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

Expand Down
108 changes: 82 additions & 26 deletions bfabric/src/bfabric/oauth/_credential_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=<jwt>)``.
"""

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
Expand All @@ -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

Expand All @@ -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 ``<cache_path>.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`.

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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.
Expand All @@ -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.

Expand Down
21 changes: 14 additions & 7 deletions bfabric/src/bfabric/oauth/_token_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import hashlib
import json
import os
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING

Expand Down Expand Up @@ -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."""
Expand Down
145 changes: 141 additions & 4 deletions tests/bfabric/oauth/test_credential_provider.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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="",
Expand Down Expand Up @@ -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())
Loading
Loading