refactor(mcp-oauth): split the refresh fence into acquire/release functions, drop the lock sidecar on remove
The SDK drives a refresh as a generator (request yielded from _refresh_token, response consumed in _handle_refresh_response), so the fence was a hand-driven @asynccontextmanager: __aenter__ in one method, __aexit__ in another, generator object stashed on the provider. A plain `acquire_refresh_fence(path, timeout) -> fd` / `release_refresh_fence(fd)` pair says what actually happens and leaves nothing half-entered to leak. The descriptor is opened with os.open at 0600 and closed on every acquisition failure. The `_refresh_token` release-on-exception stays: `_refresh_token` is also reachable outside `async_auth_flow` (tests call it directly), and the wrapper's finally only covers the generator-driven path. HermesTokenStorage.remove() now unlinks the `.refresh.lock` sibling so logout leaves no stray file. It is deliberately NOT added to _state_paths(): snapshot()/restore(only_if_absent=True) treat any existing state path as "newer state exists", and a lingering lock file would silently veto a rollback. tests/tools/test_mcp_oauth.py: drop the unused `Path` import (`time` is still used by the socket poll helper).
This commit is contained in:
@@ -5,7 +5,6 @@ import stat
|
||||
import sys
|
||||
import time
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch, MagicMock
|
||||
from urllib.parse import quote
|
||||
|
||||
|
||||
@@ -835,14 +835,17 @@ async def test_refresh_fails_closed_while_a_peer_holds_the_fence(tmp_path, monke
|
||||
provider = _fenced_provider(tmp_path, monkeypatch, endpoint)
|
||||
await provider.context.storage.set_tokens(_token("A1", "R1"))
|
||||
monkeypatch.setattr(
|
||||
mcp_oauth, "_refresh_fence", functools.partial(mcp_oauth._refresh_fence, timeout=0.2)
|
||||
mcp_oauth, "acquire_refresh_fence", functools.partial(mcp_oauth.acquire_refresh_fence, timeout=0.2)
|
||||
)
|
||||
|
||||
sent = []
|
||||
|
||||
async with mcp_oauth._refresh_fence(provider.context.storage._tokens_path()):
|
||||
peer_fd = await mcp_oauth.acquire_refresh_fence(provider.context.storage._tokens_path())
|
||||
try:
|
||||
with pytest.raises(mcp_oauth.RefreshFenceTimeout):
|
||||
await _drive_flow(provider, sent.append)
|
||||
finally:
|
||||
mcp_oauth.release_refresh_fence(peer_fd)
|
||||
|
||||
assert sent == []
|
||||
assert provider.context.current_tokens.refresh_token == "R1"
|
||||
@@ -922,6 +925,5 @@ async def test_refresh_fence_surfaces_non_contention_lock_errors_immediately(tmp
|
||||
monkeypatch.setattr(mcp_oauth.fcntl, "flock", broken_flock)
|
||||
started = time.monotonic()
|
||||
with pytest.raises(mcp_oauth.RefreshFenceTimeout, match="unavailable on this filesystem"):
|
||||
async with mcp_oauth._refresh_fence(tmp_path / "srv.json", timeout=5.0):
|
||||
pass
|
||||
await mcp_oauth.acquire_refresh_fence(tmp_path / "srv.json", timeout=5.0)
|
||||
assert time.monotonic() - started < 1.0, "must fail fast, not wait out the deadline"
|
||||
|
||||
+32
-29
@@ -73,9 +73,12 @@ class RefreshFenceTimeout(RuntimeError):
|
||||
_FENCE_CONTENTION_ERRNOS = frozenset({errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES, errno.EDEADLK})
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def _refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOUT_SECONDS):
|
||||
"""Own one refresh generation across read -> POST -> persist.
|
||||
def _refresh_lock_path(path: "Path") -> "Path":
|
||||
return path.with_suffix(path.suffix + ".refresh.lock")
|
||||
|
||||
|
||||
async def acquire_refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOUT_SECONDS) -> int:
|
||||
"""Take the fence that owns one refresh generation across read -> POST -> persist.
|
||||
|
||||
Token files are written atomically (``_write_json``), so a reader never
|
||||
sees a torn file; the only cross-process hazard is the read-modify-write
|
||||
@@ -98,13 +101,16 @@ async def _refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOU
|
||||
already excludes sibling tasks and threads of the same process.
|
||||
|
||||
Acquisition failure RAISES. Degrading to "proceed unlocked" would
|
||||
reintroduce the exact race.
|
||||
reintroduce the exact race. Returns the locked descriptor; the caller
|
||||
hands it back to ``release_refresh_fence`` from its own exit path (the
|
||||
SDK drives the refresh as a generator, so no single ``with`` block can
|
||||
span the critical section).
|
||||
"""
|
||||
lock_path = path.with_suffix(path.suffix + ".refresh.lock")
|
||||
lock_path = _refresh_lock_path(path)
|
||||
try:
|
||||
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
secure_parent_dir(lock_path)
|
||||
lock_fd = open(lock_path, "a+", encoding="utf-8")
|
||||
fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600)
|
||||
except OSError as exc:
|
||||
# No lock file means no ownership proof. Fail closed: see the
|
||||
# class docstring for why proceeding is worse than aborting.
|
||||
@@ -112,24 +118,19 @@ async def _refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOU
|
||||
f"refresh fence unavailable ({lock_path.name}): {exc}"
|
||||
) from exc
|
||||
|
||||
acquired = False
|
||||
deadline = time.monotonic() + timeout
|
||||
try:
|
||||
lock_fd.seek(0)
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
try:
|
||||
if fcntl is not None:
|
||||
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
elif msvcrt is not None:
|
||||
getattr(msvcrt, "locking")(
|
||||
lock_fd.fileno(), getattr(msvcrt, "LK_NBLCK"), 1
|
||||
)
|
||||
getattr(msvcrt, "locking")(fd, getattr(msvcrt, "LK_NBLCK"), 1)
|
||||
else: # pragma: no cover - no advisory locking primitive
|
||||
raise RefreshFenceTimeout(
|
||||
"refresh fence unsupported: no flock/msvcrt on this platform"
|
||||
)
|
||||
acquired = True
|
||||
break
|
||||
return fd
|
||||
except OSError as exc:
|
||||
if exc.errno not in _FENCE_CONTENTION_ERRNOS:
|
||||
# Not "a peer holds it" but "this filesystem cannot lock"
|
||||
@@ -143,21 +144,23 @@ async def _refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOU
|
||||
f"refresh fence held by a peer for {timeout:.0f}s ({lock_path.name})"
|
||||
) from None
|
||||
await asyncio.sleep(0.05)
|
||||
except BaseException:
|
||||
os.close(fd)
|
||||
raise
|
||||
|
||||
yield
|
||||
|
||||
def release_refresh_fence(fd: int) -> None:
|
||||
"""Unlock and close a descriptor returned by ``acquire_refresh_fence``. Never raises."""
|
||||
try:
|
||||
if fcntl is not None:
|
||||
fcntl.flock(fd, fcntl.LOCK_UN)
|
||||
elif msvcrt is not None:
|
||||
getattr(msvcrt, "locking")(fd, getattr(msvcrt, "LK_UNLCK"), 1)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
if acquired:
|
||||
if fcntl is not None:
|
||||
fcntl.flock(lock_fd, fcntl.LOCK_UN)
|
||||
elif msvcrt is not None:
|
||||
getattr(msvcrt, "locking")(
|
||||
lock_fd.fileno(), getattr(msvcrt, "LK_UNLCK"), 1
|
||||
)
|
||||
except (OSError, IOError):
|
||||
pass
|
||||
finally:
|
||||
lock_fd.close()
|
||||
with contextlib.suppress(OSError):
|
||||
os.close(fd)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -563,7 +566,7 @@ class HermesTokenStorage:
|
||||
|
||||
def remove(self) -> None:
|
||||
"""Delete all stored OAuth state for this server."""
|
||||
for p in (*self._state_paths(), self._cimd_rejected_path()):
|
||||
for p in (*self._state_paths(), self._cimd_rejected_path(), _refresh_lock_path(self._tokens_path())):
|
||||
p.unlink(missing_ok=True)
|
||||
|
||||
def snapshot(self) -> dict[str, bytes]:
|
||||
|
||||
+10
-14
@@ -74,9 +74,9 @@ class HermesProviderMixin:
|
||||
self._coerce_client_secret_post()
|
||||
return self._prepare_token_request(await super()._exchange_token_authorization_code(*args, **kwargs))
|
||||
|
||||
# Set while this provider owns the refresh fence; cleared by
|
||||
# Locked descriptor while this provider owns the refresh fence; cleared by
|
||||
# _hermes_release_refresh_fence. Never shared across instances.
|
||||
_hermes_fence: Any = None
|
||||
_hermes_fence: int | None = None
|
||||
|
||||
async def async_auth_flow(self, request):
|
||||
"""Guarantee fence release even if the auth generator is abandoned.
|
||||
@@ -130,7 +130,7 @@ class HermesProviderMixin:
|
||||
The fence is acquired BEFORE the final read of the refresh token and is
|
||||
released only after _handle_refresh_response has persisted the
|
||||
replacement, so one refresh generation is consumed by exactly one
|
||||
process. See tools.mcp_oauth._refresh_fence for the interleaving this
|
||||
process. See tools.mcp_oauth.acquire_refresh_fence for the interleaving this
|
||||
closes.
|
||||
|
||||
Holding a lock across ``yield`` in the SDK's generator-based auth flow
|
||||
@@ -176,26 +176,22 @@ class HermesProviderMixin:
|
||||
be POSTed. A stale fence from an aborted attempt is replaced rather
|
||||
than stacked, so a crashed generator cannot leak ownership.
|
||||
"""
|
||||
from tools.mcp_oauth import _refresh_fence
|
||||
from tools.mcp_oauth import acquire_refresh_fence
|
||||
|
||||
await self._hermes_release_refresh_fence()
|
||||
storage = self.context.storage
|
||||
tokens_path = getattr(storage, "_tokens_path", None)
|
||||
if tokens_path is None: # pragma: no cover - non-Hermes storage
|
||||
return
|
||||
fence = _refresh_fence(tokens_path())
|
||||
await fence.__aenter__()
|
||||
self._hermes_fence = fence
|
||||
self._hermes_fence = await acquire_refresh_fence(tokens_path())
|
||||
|
||||
async def _hermes_release_refresh_fence(self) -> None:
|
||||
"""Release the fence if held. Idempotent and never raises."""
|
||||
fence, self._hermes_fence = self._hermes_fence, None
|
||||
if fence is None:
|
||||
return
|
||||
try:
|
||||
await fence.__aexit__(None, None, None)
|
||||
except Exception: # pragma: no cover - release must never mask the outcome
|
||||
self._hermes_logger.debug("Refresh fence release failed", exc_info=True)
|
||||
from tools.mcp_oauth import release_refresh_fence
|
||||
|
||||
fd, self._hermes_fence = self._hermes_fence, None
|
||||
if fd is not None:
|
||||
release_refresh_fence(fd)
|
||||
|
||||
async def _hermes_rotated_candidate(self):
|
||||
"""The on-disk pair, if a peer rotated it past the one we hold.
|
||||
|
||||
Reference in New Issue
Block a user