From fcd60a1432157dde891a6a89efb7b0d91b75b88d Mon Sep 17 00:00:00 2001 From: AIKAWA Shigechika Date: Mon, 5 Oct 2026 19:28:38 +0900 Subject: [PATCH 1/4] fix(oauth): keep the token on a transient refresh failure; serialize refresh across processes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Token-endpoint errors become OAuthTokenError(RuntimeError) carrying the RFC 6749 §5.2 error code (message unchanged). - ensure_token deletes the stored token only when the refresh failure proves the grant dead: anything but a transport error, a 5xx/429, or temporarily_unavailable/server_error. It deletes by comparison (delete_token(expected_refresh_token=...)), so a newer token another process saved survives. - refresh_lock (tokens.json.refresh.lock, separate from the non-reentrant _store_lock that save_token takes) wraps load -> exchange -> save, with a re-read after acquiring: a process that finds a token another one just refreshed uses it, and every exchange spends the latest refresh token. Bounded 30 s wait, then a warning and an unlocked refresh. - refresh_cached_token keeps its "None on failure" contract on top of the new _refresh_cached_token_ex. Fixes #454 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- WORKAROUNDS.md | 2 + src/mcp_stdio/oauth.py | 150 ++++++++++++++++++++++++++++++----- src/mcp_stdio/token_store.py | 123 ++++++++++++++++++++++++---- tests/test_oauth.py | 144 +++++++++++++++++++++++++++++++++ tests/test_token_store.py | 60 ++++++++++++++ 6 files changed, 442 insertions(+), 39 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 3f54dd10..c877a14c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,7 +52,7 @@ The substantive modules under `src/mcp_stdio/`: - Signal handlers (`signal.signal`) are set from the main thread only — both transports now run daemon threads (`run_sse`'s SSE reader; `run()`'s modern-era listen/resource streams and stdin reader; `run()`'s OAuth proactive-refresh and cold-start daemons, on either era), so pytest tests must drive `run()` and `run_sse` from the main thread. - **`cli.py`** — argparse-based CLI. Builds headers, resolves `MCP_BEARER_TOKEN` / `MCP_OAUTH_CLIENT_ID` env vars, runs the OAuth flow before relay if `--oauth` or `--oauth-device` is set, and dispatches to `run()` or `run_sse()` based on `--transport`. - **`oauth.py`** — OAuth 2.1 client: RFC 9728/8414 discovery, RFC 7591 dynamic client registration, RFC 7636 PKCE, RFC 8707 resource indicators, authorization code flow with localhost callback server, RFC 8628 device authorization grant, RFC 9470 step-up authorization, token exchange and refresh. -- **`token_store.py`** — Token persistence in `~/.config/mcp-stdio/tokens.json` (0o600). Stores per-server-URL tokens with client credentials and endpoint URLs for refresh. Migrates legacy `~/.mcp-stdio/` tokens on first read. +- **`token_store.py`** — Token persistence in `~/.config/mcp-stdio/tokens.json` (0o600). Stores per-server-URL tokens with client credentials and endpoint URLs for refresh. Migrates legacy `~/.mcp-stdio/` tokens on first read. Two lock files: `_store_lock` (blocking, NOT re-entrant) around each save/delete, and `refresh_lock` (bounded 30 s wait, then unlocked with a warning) around `oauth._refresh_cached_token_ex`'s load → exchange → save so concurrent relay processes never spend the same rotating refresh token (#454); `delete_token(expected_refresh_token=...)` is compare-and-delete. - **`server.py`** — the `mcp-stdio serve` reverse gateway (dispatched from `cli.py` when `argv[1] == "serve"`). **Dual-era** since #270 Phase 3: one endpoint answers both revisions, and `_request_era()` classifies each POST body conservatively — modern only on positive evidence (`params._meta` carries the `protocolVersion` KEY, or the method is `server/discover`); everything else falls through to the untouched legacy path. - **Legacy path (unchanged, AC2).** One backend stdio child per MCP session (`SessionRegistry`, keyed on `Mcp-Session-Id`) over a stdlib `http.server` Streamable HTTP endpoint: session minted on `initialize`, 400 sessionless, 404 on an unknown id, DELETE to terminate, GET SSE for server-initiated messages. Pinned byte-for-byte by `tests_integration/test_serve_legacy_pin.py`, which every Phase 3 PR had to keep green **with zero diffs**. - **Modern path (2026-07-28).** A request-plane validation ladder (`_validate_modern`; first failure wins, in python-sdk v2's order — the header rungs run BEFORE the unsupported-version rung): required `_meta` → `-32602`; `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` agreement, the last sentinel-decoded via relay's `_decode_mcp_name` → `-32020`; unsupported version → `-32022` with `data.supported`. Notifications are exempt from the ladder entirely (O9). `_dispatch_modern` then serves the request statelessly from a `ModernBackendPool` child, keyed on the **authenticated principal and NOT on a session** (one shared child under no-auth or a static token, one per OAuth user), with the gateway performing the `initialize` + `notifications/initialized` handshake the modern wire omits and caching the result. `server/discover` is synthesised locally and never forwarded (a legacy child would answer `-32601`); every modern result is stamped `resultType: "complete"`, the six cacheable ops additionally get `ttlMs` (`--cache-ttl-ms`, default 60000) / `cacheScope: "private"`, and every result carries the child's `serverInfo` under `_meta`. Client ids are remapped to a minted `mcp-stdio/serve/` id so concurrent stateless clients sharing one child cannot collide. `subscriptions/listen` is SERVED by serve itself, never forwarded: SCOPE is the listChanged trio (`_LISTEN_FILTER_METHODS`, #374) plus `resourceSubscriptions` (#381, detailed below), honor-all on the three booleans, attach-BEFORE-ack, ack as frame 1 with the honored subset at `params.notifications` and the id at `params._meta[subscriptionId]` (both nestings are load-bearing — a top-level echo is silently ignored by a compliant client). Every frame is stamped with the subscription id. `BackendProcess` fans notifications out to attached `_ListenStream`s (filtering on the reader thread, bounded 1024-deep queue per stream, ≤4 streams per pooled child → `-32603`/503 pre-ack). Endings: gateway shutdown → terminal `resultType: "complete"` frame then close (`signal_end(graceful=True)` + a bounded `drain_listeners`); child death or backlog overflow → abrupt close with NO terminal frame; NEVER a server-sent `notifications/cancelled` (the v2 client settles that as LOST). First ending wins. **#381 added the fourth field, `resourceSubscriptions`**: honoring is entirely LOCAL (child's advertised `resources.subscribe` via `_child_supports_resource_subscribe`, then sanitize + dedup + cap at `_LISTEN_MAX_RESOURCE_SUBSCRIPTIONS=256` with truncate-and-honor), so the ack ships BEFORE any `resources/subscribe` is driven — the drive runs on a background daemon thread and can never stall the ack or the pump. `notifications/resources/updated` gets its OWN routing branch (never folded into `_LISTEN_FORWARDED_METHODS`, which would make any non-empty URI list match every URI and leak across streams); matching is exact string equality, no normalization. URIs are refcounted per child in `BackendProcess._resource_refs` under a dedicated `_sub_lock` HELD ACROSS the send (order `_sub_lock` -> `_lock`, never reversed): subscribe on the first reference, unsubscribe on the last, ids from the existing `_mint_modern_id()`. `_ListenStream.torn_down` closes the async-drive-vs-sync-release race. Failure is reply-then-degrade (log once per URI per stream via `_ListenStream.subscribe_failure_logged`, #388 review, keep honored). `_UNDELIVERABLE_NOTIFICATION_FLAGS` still lists `resources.subscribe` as the DEFAULT, lifted per-child by `_synthesize_discover_result`'s `keep=` on the same predicate the ack uses. **O16 is closed by construction, zero production code**: `notifications/message` is never in any listen-forward set, serve's modern face has no other streaming channel to gate, and SEP-2577 deprecated the feature. Pool lifecycle (#376): entries carry a `holds` checkout refcount (taken by `get_or_create`, released in `_dispatch_modern`'s `finally`) which — together with `has_pending` and the PENDING check — forms the single `_reapable_locked` predicate shared by cap-eviction and the `modern-pool-reaper` idle thread (`--modern-idle-ttl`, 0 = off); `holds` is also #374's attach seam. `--modern-only` refuses legacy callers after the auth gate (GET/DELETE 405 + `Allow`, legacy `initialize` → `-32022`). diff --git a/WORKAROUNDS.md b/WORKAROUNDS.md index 1615928f..416a97c1 100644 --- a/WORKAROUNDS.md +++ b/WORKAROUNDS.md @@ -25,6 +25,8 @@ Works around known issues in Claude Code's HTTP transport: - **Each terminal re-runs the full OAuth flow** — credentials are keyed by the ephemeral localhost callback port chosen per process, so every new terminal is a cache miss that triggers a fresh browser round-trip and orphans the previous entry ([#43000](https://github.com/anthropics/claude-code/issues/43000)); mcp-stdio keys its token store by server URL in `~/.config/mcp-stdio/tokens.json`, shared across terminals and sessions. - **Dynamic Client Registration repeated on every authenticate** — a fresh `POST /register` on each authentication orphans the previously issued `client_id` and its refresh token, contrary to the MCP authorization guidance to reuse registered credentials ([#59460](https://github.com/anthropics/claude-code/issues/59460)); mcp-stdio persists the client credentials alongside the tokens and reuses them on subsequent authentications, re-registering only when no client is cached or the stored client secret has passed its RFC 7591 `client_secret_expires_at`. - **Rotated refresh token not persisted** — with authorization servers that issue a new refresh token on every exchange, the rotated token is not written back, so a subsequent refresh replays the already-consumed one and the session drops ([#66210](https://github.com/anthropics/claude-code/issues/66210)); mcp-stdio stores the rotated refresh token on every refresh (keeping the prior one only as an in-flight fallback). +- **Concurrent sessions replay a single-use refresh token** — several sessions sharing one stored token each refresh it on their own, so with single-use rotation the second one replays the token the first just spent and the identity provider rejects it, or revokes the whole token family ([#91641](https://github.com/anthropics/claude-code/issues/91641), [#93537](https://github.com/anthropics/claude-code/issues/93537)); mcp-stdio serializes each refresh across processes with a lock file and re-reads the store after taking it, so a process that finds a token another one just refreshed uses it instead of exchanging again, and every exchange uses the latest refresh token (#454). +- **A transient refresh failure discards the stored grant** — a network blip, a 5xx or `temporarily_unavailable` during refresh is treated like a revoked grant, throwing away a long-lived refresh token and forcing a new sign-in ([punkpeye/mcp-remote#348](https://github.com/punkpeye/mcp-remote/issues/348), [#349](https://github.com/punkpeye/mcp-remote/issues/349), [typescript-sdk#2915](https://github.com/modelcontextprotocol/typescript-sdk/issues/2915)); mcp-stdio deletes the stored token only when the authorization server's answer proves the grant dead (`invalid_grant`, `invalid_client`, other 4xx), and only if the stored refresh token is still the one that failed (#454). - **OIDC `id_token` cannot be used as the Bearer token** — servers that validate an OIDC `id_token` at the edge (e.g. behind Google Cloud IAP) reject the opaque access token that is sent instead ([#70047](https://github.com/anthropics/claude-code/issues/70047)); mcp-stdio can present the `id_token` as the Bearer via `--oauth-use-id-token`. - **Tokens without `expires_in` discarded early** — spec-valid long-lived tokens (e.g. GitHub, Todoist) are assigned an arbitrary client-side lifetime and dropped, after which a request is sent with no `Authorization` header at all ([#26281](https://github.com/anthropics/claude-code/issues/26281)); mcp-stdio treats a token response without `expires_in` as non-expiring and keeps sending it until the server itself returns 401. diff --git a/src/mcp_stdio/oauth.py b/src/mcp_stdio/oauth.py index 28ad2c46..cf64d3d4 100644 --- a/src/mcp_stdio/oauth.py +++ b/src/mcp_stdio/oauth.py @@ -31,7 +31,13 @@ import httpx from .relay import _read_bounded, _parse_auth_params, log -from .token_store import TokenData, delete_token, load_token, save_token +from .token_store import ( + TokenData, + delete_token, + load_token, + refresh_lock, + save_token, +) # --------------------------------------------------------------------------- # Data structures @@ -1208,8 +1214,29 @@ def log_message(self, format: str, *args: Any) -> None: return Handler +class OAuthTokenError(RuntimeError): + """A token-endpoint error response (RFC 6749 §5.2), with its ``error`` code. + + A ``RuntimeError`` subclass with the same message as before, so existing + handlers keep working; ``error`` lets the refresh path tell a dead grant + (``invalid_grant``) from a transient one (``temporarily_unavailable``, + #454). The code is AS-controlled: kept only when it is a short string. + """ + + def __init__(self, message: str, error: Any) -> None: + super().__init__(message) + self.error = error if isinstance(error, str) and len(error) <= 64 else "" + + +def _token_error(body: dict[str, Any]) -> OAuthTokenError: + desc = body.get("error_description", body["error"]) + return OAuthTokenError( + f"OAuth token error: {_sanitize_oauth_error(desc)}", body["error"] + ) + + def _raise_for_body_error(result: dict[str, Any]) -> None: - """Raise RuntimeError if a 200 token response carries an in-body OAuth error. + """Raise OAuthTokenError if a 200 token response carries an in-body OAuth error. Some providers (GitHub legacy) return HTTP 200 with ``error`` / ``error_description`` instead of a token. Applies to both JSON and @@ -1218,8 +1245,7 @@ def _raise_for_body_error(result: dict[str, Any]) -> None: surface as an opaque ``KeyError: 'access_token'`` downstream. """ if "error" in result and "access_token" not in result: - desc = result.get("error_description", result["error"]) - raise RuntimeError(f"OAuth token error: {_sanitize_oauth_error(desc)}") + raise _token_error(result) def _parse_token_response(resp: httpx.Response) -> dict[str, Any]: @@ -1250,8 +1276,7 @@ def _parse_token_response(resp: httpx.Response) -> dict[str, Any]: except Exception: body = None if isinstance(body, dict) and "error" in body: - desc = body.get("error_description", body["error"]) - raise RuntimeError(f"OAuth token error: {_sanitize_oauth_error(desc)}") + raise _token_error(body) resp.raise_for_status() @@ -1548,6 +1573,46 @@ def _token_response_to_data( ) +@dataclass +class _RefreshOutcome: + """What ``_refresh_cached_token_ex`` produced (#454). + + ``data`` is the usable token, or None on failure. ``dead`` says the + failure proves the stored grant unusable (delete it), as opposed to a + transient one (keep it for the next attempt). ``refresh_token`` is the + one that failed, for ``delete_token``'s compare-and-delete. + """ + + data: TokenData | None + dead: bool = False + refresh_token: str | None = None + + +# Token-endpoint ``error`` codes that say "try again later", not "this grant +# is dead" (RFC 6749 §5.2 defines no such codes for the token endpoint, but +# ASes use the §4.1.2.1 ones there). +_TRANSIENT_TOKEN_ERRORS = frozenset({"temporarily_unavailable", "server_error"}) + + +def _refresh_error_is_dead(e: Exception) -> bool: + """Whether a refresh failure proves the stored grant unusable (#454). + + Only the plainly transient cases keep the token: a transport error + (no answer at all), an HTTP 5xx or 429, or a transient ``error`` code. + Everything else — ``invalid_grant``, ``invalid_client``, any other 4xx, + an unparseable success — is treated as dead, as every failure was + before. + """ + if isinstance(e, OAuthTokenError): + return e.error not in _TRANSIENT_TOKEN_ERRORS + if isinstance(e, httpx.HTTPStatusError): + status = e.response.status_code + return not (status >= 500 or status == 429) + if isinstance(e, httpx.TransportError): + return False + return True + + def refresh_cached_token(server_url: str, client: httpx.Client) -> TokenData | None: """Refresh the cached token for a server using its stored refresh_token. @@ -1556,16 +1621,45 @@ def refresh_cached_token(server_url: str, client: httpx.Client) -> TokenData | N client_secret per RFC 7591 §3.2.1) or the refresh request fails. Does not delete stale tokens on failure — callers decide the retry - policy. + policy (``ensure_token`` uses ``_refresh_cached_token_ex`` for that). """ - cached = load_token(server_url) + return _refresh_cached_token_ex(server_url, client).data + + +def _refresh_cached_token_ex(server_url: str, client: httpx.Client) -> _RefreshOutcome: + """``refresh_cached_token`` plus why it failed, under ``refresh_lock`` (#454). + + The store is read once before taking the cross-process lock and again + after: if another relay process refreshed in between, its token is + used as-is instead of exchanging again, and in any case the exchange + uses the LATEST stored refresh token. Two processes therefore never + spend the same rotating refresh token. + """ + snapshot = load_token(server_url) + with refresh_lock(): + cached = load_token(server_url) + if ( + snapshot is not None + and cached is not None + and cached.access_token != snapshot.access_token + ): + log("another mcp-stdio process already refreshed the token; using it") + return _RefreshOutcome(cached) + return _refresh_locked(server_url, client, cached) + + +def _refresh_locked( + server_url: str, client: httpx.Client, cached: TokenData | None +) -> _RefreshOutcome: + """The exchange itself; the caller holds ``refresh_lock``.""" if not ( cached and cached.refresh_token and cached.token_endpoint and cached.client_id ): - return None + return _RefreshOutcome(None, dead=True) + failed = _RefreshOutcome(None, dead=True, refresh_token=cached.refresh_token) if _is_client_secret_expired(cached): log("OAuth client_secret expired (RFC 7591 §3.2.1) — cannot refresh") - return None + return failed log("access token expired, attempting refresh") # Defence-in-depth: the cached token_endpoint was validated at # persist time, but re-validate before re-POSTing credentials to it. The @@ -1573,7 +1667,7 @@ def refresh_cached_token(server_url: str, client: httpx.Client) -> TokenData | N # the discovery-path validation so a tampered/legacy store cannot redirect # the refresh to a cleartext or userinfo-bearing URL. See #13. if not _validate_endpoint_url(cached.token_endpoint, label="cached token_endpoint"): - return None + return failed auth_method = cached.token_endpoint_auth_method no_resource_indicator = cached.no_resource_indicator oauth_resource = cached.oauth_resource @@ -1617,7 +1711,9 @@ def _refresh(scope: str | None) -> dict[str, Any]: # would otherwise leak AS-controlled bytes into the log. Bound it # defensively so no exception type can write an unbounded/raw log line. log(f"token refresh failed: {_sanitize_oauth_error(e)}") - return None + return _RefreshOutcome( + None, dead=_refresh_error_is_dead(e), refresh_token=cached.refresh_token + ) metadata = OAuthMetadata( authorization_endpoint=cached.authorization_endpoint, token_endpoint=cached.token_endpoint, @@ -1655,10 +1751,10 @@ def _refresh(scope: str | None) -> dict[str, Any]: # the stale token and re-auth, but the RuntimeError reached cli.py and # exited 1). Degrade to None like every other refresh failure. log(f"token refresh failed: {_sanitize_oauth_error(e)}") - return None + return failed save_token(server_url, data) log("token refreshed successfully") - return data + return _RefreshOutcome(data) def _resolve_cimd_client_id( @@ -2486,13 +2582,25 @@ def ensure_token( # Try refresh (skip if client_secret has expired per RFC 7591 §3.2.1) if cached.refresh_token and cached.token_endpoint and cached.client_id: - refreshed = refresh_cached_token(server_url, client) - if refreshed: - return refreshed - # Refresh failed or was skipped — clear stale token so the full - # flow below isn't blocked by cached failure state - # (cf. anthropics/claude-code#37747). - delete_token(server_url) + outcome = _refresh_cached_token_ex(server_url, client) + if outcome.data: + return outcome.data + if outcome.dead: + # The grant is dead — clear the stale token so the full flow + # below isn't blocked by cached failure state + # (cf. anthropics/claude-code#37747). Compare-and-delete + # (#454): if another process stored a newer token meanwhile, + # it survives. + delete_token( + server_url, + expected_refresh_token=outcome.refresh_token + or cached.refresh_token, + ) + else: + # A transient failure (no answer, 5xx/429, temporarily_unavailable) + # says nothing about the grant: keep the token for the next + # attempt instead of throwing away weeks of refresh token (#454). + log("keeping the stored OAuth token; its refresh failed transiently") if not interactive: # Non-interactive probe (--oauth-eager warm check): no cached/refreshable diff --git a/src/mcp_stdio/token_store.py b/src/mcp_stdio/token_store.py index c0cf9b69..aa248809 100644 --- a/src/mcp_stdio/token_store.py +++ b/src/mcp_stdio/token_store.py @@ -18,6 +18,7 @@ import stat import sys import threading +import time from collections.abc import Iterator from dataclasses import asdict, dataclass from pathlib import Path @@ -724,11 +725,16 @@ def _write_store(data: dict[str, Any]) -> None: @contextlib.contextmanager -def _store_lock() -> Iterator[None]: - """Best-effort advisory exclusive lock around a read-modify-write. +def _file_lock(name: str, wait: float | None = None) -> Iterator[None]: + """Best-effort advisory exclusive lock on ``_STORE_DIR / name``. + + ``wait`` None blocks until the lock is free (``_store_lock``); a number + bounds the wait in seconds, after which the lock is skipped with a + warning (``refresh_lock``, #454). Everything below applies to both. - Serialises ``save_token`` / ``delete_token`` so updates to distinct server - keys merge rather than clobbering each other (last-writer-wins). Uses + For ``_store_lock`` it serialises ``save_token`` / ``delete_token`` so + updates to distinct server keys merge rather than clobbering each other + (last-writer-wins). Uses ``fcntl.flock`` on POSIX and ``msvcrt`` on Windows; if no primitive is available or acquisition fails, it proceeds without the lock (the operation must never be blocked by lock trouble). @@ -745,7 +751,7 @@ def _store_lock() -> Iterator[None]: _ensure_store_dir() # Derive the lock path from the current _STORE_DIR (not a module constant) # so test monkeypatching of _STORE_DIR redirects the lock file too. - lock_path = _STORE_DIR / "tokens.json.lock" + lock_path = _STORE_DIR / name try: # _O_NONBLOCK: without it, an O_WRONLY open of a writer-less # FIFO planted at the lock path BLOCKS forever, hanging every @@ -794,15 +800,13 @@ def _store_lock() -> Iterator[None]: locked = False try: try: - if sys.platform == "win32": - import msvcrt - - msvcrt.locking(fd, msvcrt.LK_LOCK, 1) - else: - import fcntl - - fcntl.flock(fd, fcntl.LOCK_EX) - locked = True + locked = _acquire(fd, wait) + if not locked: + print( + f"warning: {lock_path.name} still held after {wait:g}s; " + f"proceeding without it", + file=sys.stderr, + ) except (OSError, ImportError, ValueError): pass # best-effort: fall back to an unsynchronised write yield @@ -818,6 +822,78 @@ def _store_lock() -> Iterator[None]: os.close(fd) +def _acquire(fd: int, wait: float | None) -> bool: + """Take the exclusive lock on ``fd``; False when ``wait`` ran out. + + Raises OSError/ImportError/ValueError when no lock primitive works, + which the caller treats as "proceed unlocked". + """ + if sys.platform == "win32": + import msvcrt + + if wait is None: + msvcrt.locking(fd, msvcrt.LK_LOCK, 1) + return True + lock_once = lambda: msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) # noqa: E731 + else: + import fcntl + + if wait is None: + fcntl.flock(fd, fcntl.LOCK_EX) + return True + lock_once = lambda: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) # noqa: E731 + deadline = time.monotonic() + wait + while True: + try: + lock_once() + return True + except OSError as e: + if e.errno not in ( + errno.EAGAIN, + errno.EACCES, + errno.EWOULDBLOCK, + errno.EDEADLK, + ): + raise + if time.monotonic() >= deadline: + return False + time.sleep(0.05) + + +@contextlib.contextmanager +def _store_lock() -> Iterator[None]: + """Serialise ``save_token`` / ``delete_token``'s read-modify-write. + + A blocking ``_file_lock`` on ``tokens.json.lock`` (see there for the + platform primitives and the degrade-to-unlocked rules). NOT re-entrant: + each call opens its own fd, so code holding it must not call + ``save_token`` / ``delete_token``. + """ + with _file_lock("tokens.json.lock"): + yield + + +# Upper bound on waiting for another process's refresh (#454). Its holder +# makes one token-endpoint round trip, so this only runs out when that +# process is stuck; then refreshing unlocked beats stalling this one. +_REFRESH_LOCK_WAIT_SECS = 30.0 + + +@contextlib.contextmanager +def refresh_lock(wait: float = _REFRESH_LOCK_WAIT_SECS) -> Iterator[None]: + """Cross-process lock around one refresh's load -> exchange -> save (#454). + + A separate file from ``_store_lock`` (which ``save_token`` takes inside + it), so the holder can still save. With a rotating refresh token, two + relay processes exchanging the same token make the AS answer the second + with ``invalid_grant`` — or revoke the whole family; holding this and + re-reading the store after acquiring it means each process exchanges + the latest token. Bounded wait, then unlocked with a warning. + """ + with _file_lock("tokens.json.refresh.lock", wait=wait): + yield + + def load_token(server_url: str) -> TokenData | None: """Load token data for a server URL. @@ -955,8 +1031,13 @@ def save_token(server_url: str, data: TokenData) -> None: ) -def delete_token(server_url: str) -> None: - """Delete token data for a server URL.""" +def delete_token(server_url: str, *, expected_refresh_token: str | None = None) -> bool: + """Delete token data for a server URL; True when an entry was removed. + + With ``expected_refresh_token``, delete only while the stored entry still + carries that refresh token (#454): a refresh that just failed must not + remove a newer token another process saved in the meantime. + """ with _store_lock(): try: store = _read_store(for_write=True) @@ -969,10 +1050,16 @@ def delete_token(server_url: str) -> None: f"not deleting to avoid overwriting other servers' tokens", file=sys.stderr, ) - return + return False removed = False for key in {_normalize_key(server_url), server_url}: if key in store: + entry = store[key] + if expected_refresh_token is not None and ( + not isinstance(entry, dict) + or entry.get("refresh_token") != expected_refresh_token + ): + continue del store[key] removed = True if removed: @@ -988,3 +1075,5 @@ def delete_token(server_url: str) -> None: f"warning: could not write token store ({e}); token not deleted", file=sys.stderr, ) + return False + return removed diff --git a/tests/test_oauth.py b/tests/test_oauth.py index 1a930461..4b8c92de 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -7950,3 +7950,147 @@ def test_gui_browser_available(monkeypatch, platform, env, expected): monkeypatch.setenv(k, v) monkeypatch.setattr(oauth_mod.sys, "platform", platform) assert oauth_mod._gui_browser_available() is expected + + +# --- #454: refresh failure classification and cross-process serialization --- + +_DUR_URL = "https://api.example.com/mcp" +_DUR_TOKEN = "https://auth.example.com/token" + + +class TestRefreshDurability: + @pytest.fixture(autouse=True) + def _store(self, tmp_path, monkeypatch): + monkeypatch.setattr("mcp_stdio.token_store._STORE_DIR", tmp_path) + monkeypatch.setattr("mcp_stdio.token_store._STORE_FILE", tmp_path / "t.json") + + def _save_expired(self, refresh_token="rt-old", access_token="at-old"): + from mcp_stdio.token_store import save_token + + save_token( + _DUR_URL, + TokenData( + access_token=access_token, + refresh_token=refresh_token, + expires_at=time.time() - 10, + client_id="cid", + token_endpoint=_DUR_TOKEN, + authorization_endpoint="https://auth.example.com/authorize", + ), + ) + + def _ensure(self): + return ensure_token(_DUR_URL, httpx.Client(), interactive=False) + + @pytest.mark.parametrize( + "kind, kwargs", + [ + ("json-400", {"status_code": 400, "json": {"error": "invalid_grant"}}), + ("body-200", {"status_code": 200, "json": {"error": "invalid_grant"}}), + ( + "form-400", + { + "status_code": 400, + "text": "error=invalid_grant&error_description=gone", + "headers": {"content-type": "application/x-www-form-urlencoded"}, + }, + ), + ], + ) + def test_token_error_carries_its_code(self, httpx_mock, kind, kwargs): + from mcp_stdio.oauth import OAuthTokenError + + httpx_mock.add_response(url=_DUR_TOKEN, **kwargs) + with pytest.raises(OAuthTokenError, match="OAuth token error") as exc: + refresh_access_token(_DUR_TOKEN, "cid", None, "rt", httpx.Client()) + assert exc.value.error == "invalid_grant" + assert isinstance(exc.value, RuntimeError) + + @pytest.mark.parametrize( + "failure", + [ + {"exception": httpx.ConnectError("down")}, + {"status_code": 503, "text": ""}, + {"status_code": 429, "text": ""}, + {"status_code": 400, "json": {"error": "temporarily_unavailable"}}, + ], + ) + def test_transient_failure_keeps_the_token(self, httpx_mock, failure): + from mcp_stdio.token_store import load_token + + self._save_expired() + if "exception" in failure: + httpx_mock.add_exception(failure["exception"], url=_DUR_TOKEN) + else: + httpx_mock.add_response(url=_DUR_TOKEN, **failure) + assert self._ensure() is None + kept = load_token(_DUR_URL) + assert kept is not None and kept.refresh_token == "rt-old" + + @pytest.mark.parametrize("code", ["invalid_grant", "invalid_client"]) + def test_dead_grant_deletes_the_token(self, httpx_mock, code): + from mcp_stdio.token_store import load_token + + self._save_expired() + httpx_mock.add_response(url=_DUR_TOKEN, status_code=400, json={"error": code}) + assert self._ensure() is None + assert load_token(_DUR_URL) is None + + def test_dead_grant_spares_a_token_saved_meanwhile(self, httpx_mock, monkeypatch): + """Compare-and-delete: another process stored a newer token between our + failed exchange and our delete (the degraded, unlocked case).""" + from mcp_stdio import oauth as oauth_mod + from mcp_stdio.token_store import load_token + + self._save_expired() + httpx_mock.add_response( + url=_DUR_TOKEN, status_code=400, json={"error": "invalid_grant"} + ) + real_locked = oauth_mod._refresh_locked + + def racing(server_url, client, cached): + outcome = real_locked(server_url, client, cached) + self._save_expired(refresh_token="rt-new", access_token="at-new") + return outcome + + monkeypatch.setattr(oauth_mod, "_refresh_locked", racing) + assert self._ensure() is None + survivor = load_token(_DUR_URL) + assert survivor is not None and survivor.refresh_token == "rt-new" + + def test_concurrent_refreshes_spend_the_refresh_token_once(self, httpx_mock): + """Two refreshers (two processes; threads with their own lock fds + behave the same): the second waits, re-reads, and uses the first's + new token instead of replaying the rotated refresh token.""" + from mcp_stdio.oauth import refresh_cached_token + + self._save_expired() + + def slow_token(request): + time.sleep(0.3) + return httpx.Response( + 200, + json={ + "access_token": "at-new", + "refresh_token": "rt-new", + "expires_in": 3600, + }, + ) + + httpx_mock.add_callback(slow_token, url=_DUR_TOKEN) + results: list[object] = [] + threads = [ + threading.Thread( + target=lambda: results.append( + refresh_cached_token(_DUR_URL, httpx.Client()) + ) + ) + for _ in range(2) + ] + for th in threads: + th.start() + time.sleep(0.05) # both snapshot the old token before the first saves + for th in threads: + th.join(5) + assert len(httpx_mock.get_requests()) == 1 + assert [r.access_token for r in results] == ["at-new", "at-new"] diff --git a/tests/test_token_store.py b/tests/test_token_store.py index aec26a76..901b0044 100644 --- a/tests/test_token_store.py +++ b/tests/test_token_store.py @@ -6,6 +6,7 @@ import stat import sys import threading +import time import pytest @@ -1678,3 +1679,62 @@ def test_no_migration_if_no_legacy(self, tmp_path, monkeypatch): monkeypatch.setattr("mcp_stdio.token_store._LEGACY_STORE_FILE", legacy_file) assert load_token("https://example.com/mcp") is None + + +# --- #454: compare-and-delete and the bounded refresh lock --- + + +class TestRefreshDurabilityStore: + @pytest.fixture(autouse=True) + def _store(self, tmp_path, monkeypatch): + monkeypatch.setattr("mcp_stdio.token_store._STORE_DIR", tmp_path) + monkeypatch.setattr("mcp_stdio.token_store._STORE_FILE", tmp_path / "t.json") + + def test_delete_with_expected_refresh_token(self): + from mcp_stdio.token_store import ( + TokenData, + delete_token, + load_token, + save_token, + ) + + url = "https://x.example/mcp" + save_token(url, TokenData(access_token="a", refresh_token="rt-new")) + assert delete_token(url, expected_refresh_token="rt-old") is False + assert load_token(url) is not None + assert delete_token(url, expected_refresh_token="rt-new") is True + assert load_token(url) is None + + def test_refresh_lock_gives_up_after_its_wait(self, capsys): + from mcp_stdio.token_store import refresh_lock + + held = threading.Event() + release = threading.Event() + + def holder(): + with refresh_lock(): + held.set() + release.wait(5) + + t = threading.Thread(target=holder) + t.start() + assert held.wait(5) + started = time.monotonic() + with refresh_lock(wait=0.2): + waited = time.monotonic() - started + release.set() + t.join(5) + assert 0.15 <= waited < 2 + assert "still held" in capsys.readouterr().err + + def test_refresh_lock_degrades_when_locking_is_unavailable(self, monkeypatch): + from mcp_stdio import token_store + + def broken(fd, wait): + raise OSError("no locking here") + + monkeypatch.setattr(token_store, "_acquire", broken) + ran = [] + with token_store.refresh_lock(): + ran.append(True) + assert ran == [True] From e5d6e36fefe4465a6e0005be2c8b5e984f738b6f Mon Sep 17 00:00:00 2001 From: AIKAWA Shigechika Date: Mon, 5 Oct 2026 19:43:20 +0900 Subject: [PATCH 2/4] fix(oauth): status-aware classification, no unlocked exchange, delete under the lock (#455 review) - OAuthTokenError keeps the HTTP status; a 5xx/429 is transient whatever its body says. Any other httpx failure before a status was judged (decoding, oversized body) is transient too. - The scope-less retry runs only after a dead-looking answer, so a 503 can no longer be turned into Entra's AADSTS90009 and a deleted token. - refresh_lock yields False when its bounded wait runs out; the caller then never exchanges (the holder may just be slow): it returns a token stored meanwhile, else a transient failure. - ensure_token passes the token it holds as seen_access_token and asks for delete_if_dead: the dead grant is deleted while the lock is held, compared against both the failed refresh and access tokens (a non-rotating AS keeps the refresh token). - The resource-flag reconcile is applied to a fresh read under the lock instead of writing back a possibly stale copy. - Tests synchronize with events instead of sleeps. Co-Authored-By: Claude Opus 5.5 --- src/mcp_stdio/oauth.py | 119 +++++++++++++++-------- src/mcp_stdio/token_store.py | 68 ++++++++------ tests/test_oauth.py | 176 ++++++++++++++++++++++++++++++----- tests/test_token_store.py | 45 ++++++--- 4 files changed, 306 insertions(+), 102 deletions(-) diff --git a/src/mcp_stdio/oauth.py b/src/mcp_stdio/oauth.py index cf64d3d4..dcaeda0c 100644 --- a/src/mcp_stdio/oauth.py +++ b/src/mcp_stdio/oauth.py @@ -1223,15 +1223,18 @@ class OAuthTokenError(RuntimeError): #454). The code is AS-controlled: kept only when it is a short string. """ - def __init__(self, message: str, error: Any) -> None: + def __init__(self, message: str, error: Any, status: int | None = None) -> None: super().__init__(message) self.error = error if isinstance(error, str) and len(error) <= 64 else "" + # The HTTP status it arrived with (None for an in-body error on a 200), + # so a 5xx/429 stays transient whatever its body says. + self.status = status -def _token_error(body: dict[str, Any]) -> OAuthTokenError: +def _token_error(body: dict[str, Any], status: int | None = None) -> OAuthTokenError: desc = body.get("error_description", body["error"]) return OAuthTokenError( - f"OAuth token error: {_sanitize_oauth_error(desc)}", body["error"] + f"OAuth token error: {_sanitize_oauth_error(desc)}", body["error"], status ) @@ -1276,7 +1279,7 @@ def _parse_token_response(resp: httpx.Response) -> dict[str, Any]: except Exception: body = None if isinstance(body, dict) and "error" in body: - raise _token_error(body) + raise _token_error(body, resp.status_code) resp.raise_for_status() @@ -1597,18 +1600,21 @@ class _RefreshOutcome: def _refresh_error_is_dead(e: Exception) -> bool: """Whether a refresh failure proves the stored grant unusable (#454). - Only the plainly transient cases keep the token: a transport error - (no answer at all), an HTTP 5xx or 429, or a transient ``error`` code. - Everything else — ``invalid_grant``, ``invalid_client``, any other 4xx, - an unparseable success — is treated as dead, as every failure was - before. + Only the plainly transient cases keep the token: an HTTP 5xx or 429 + (whatever its body says), a transient ``error`` code, or any other httpx + failure before a status was judged (no answer, a body over + --max-message-size, an undecodable body). Everything else — + ``invalid_grant``, ``invalid_client``, any other 4xx, a 200 without an + access token — is treated as dead, as every failure was before. """ if isinstance(e, OAuthTokenError): + if e.status is not None and (e.status >= 500 or e.status == 429): + return False return e.error not in _TRANSIENT_TOKEN_ERRORS if isinstance(e, httpx.HTTPStatusError): status = e.response.status_code return not (status >= 500 or status == 429) - if isinstance(e, httpx.TransportError): + if isinstance(e, httpx.HTTPError): return False return True @@ -1626,26 +1632,54 @@ def refresh_cached_token(server_url: str, client: httpx.Client) -> TokenData | N return _refresh_cached_token_ex(server_url, client).data -def _refresh_cached_token_ex(server_url: str, client: httpx.Client) -> _RefreshOutcome: +def _refresh_cached_token_ex( + server_url: str, + client: httpx.Client, + *, + seen_access_token: str | None = None, + delete_if_dead: bool = False, +) -> _RefreshOutcome: """``refresh_cached_token`` plus why it failed, under ``refresh_lock`` (#454). - The store is read once before taking the cross-process lock and again - after: if another relay process refreshed in between, its token is - used as-is instead of exchanging again, and in any case the exchange - uses the LATEST stored refresh token. Two processes therefore never - spend the same rotating refresh token. + ``seen_access_token`` is the (expired) token the caller holds; without + one, the store is read before taking the lock. After taking it the + store is read again: if the token there differs, another relay process + already refreshed and its token is returned without an exchange; + otherwise the exchange spends the LATEST stored refresh token. Two + processes therefore never spend the same rotating refresh token. + + If the bounded wait for the lock runs out, nothing is exchanged (the + holder may just be slow): a token stored meanwhile is returned, else a + transient failure. ``delete_if_dead`` deletes a dead grant while the + lock is still held, compared against the failed refresh AND access + tokens, so no newer token can be removed. """ - snapshot = load_token(server_url) - with refresh_lock(): + if seen_access_token is None: + snapshot = load_token(server_url) + seen_access_token = snapshot.access_token if snapshot else None + with refresh_lock() as acquired: cached = load_token(server_url) if ( - snapshot is not None + seen_access_token is not None and cached is not None - and cached.access_token != snapshot.access_token + and cached.access_token != seen_access_token ): log("another mcp-stdio process already refreshed the token; using it") return _RefreshOutcome(cached) - return _refresh_locked(server_url, client, cached) + if not acquired: + log( + "another mcp-stdio process is still refreshing this token; " + "not refreshing concurrently" + ) + return _RefreshOutcome(None) + outcome = _refresh_locked(server_url, client, cached) + if outcome.dead and delete_if_dead and cached is not None: + delete_token( + server_url, + expected_refresh_token=cached.refresh_token, + expected_access_token=cached.access_token, + ) + return outcome def _refresh_locked( @@ -1697,8 +1731,12 @@ def _refresh(scope: str | None) -> dict[str, Any]: # cause (``invalid_scope``, or a scope it cannot accept back # verbatim), retry once exactly as before #451 — without it — so # sending the scope can never turn a working refresh into a - # failing one. A transport error is not retried here. - if not cached.scope: + # failing one. A transport error, or a transient answer + # (5xx/429, ``temporarily_unavailable``), is not retried: the + # scope did not cause it, and a scope-less retry could turn it + # into a "dead" answer (Entra's AADSTS90009) that deletes the + # token (#454). + if not cached.scope or not _refresh_error_is_dead(e): raise log( f"token refresh with scope failed ({_sanitize_oauth_error(e)}); retrying without scope" @@ -2569,8 +2607,17 @@ def ensure_token( # fail a request this path previously always served. Degrade to the # in-memory reconciled token (refresh below re-reads the store, so it # would still use the old settings until the next successful save). + # Under refresh_lock, applied to a fresh read (#454): writing back + # this possibly stale copy could overwrite a refresh token another + # process just rotated. try: - save_token(server_url, cached) + with refresh_lock() as acquired: + latest = load_token(server_url) if acquired else None + if latest is not None and latest.access_token: + latest.no_resource_indicator = desired_no_ri + latest.oauth_resource = oauth_resource + save_token(server_url, latest) + cached = latest except OSError as e: log(f"warning: could not persist reconciled resource settings: {e}") if ( @@ -2582,21 +2629,19 @@ def ensure_token( # Try refresh (skip if client_secret has expired per RFC 7591 §3.2.1) if cached.refresh_token and cached.token_endpoint and cached.client_id: - outcome = _refresh_cached_token_ex(server_url, client) + # A dead grant is deleted inside the refresh lock — clearing the + # stale token so the full flow below isn't blocked by cached + # failure state (cf. anthropics/claude-code#37747) — and only + # while the store still holds the token that failed (#454). + outcome = _refresh_cached_token_ex( + server_url, + client, + seen_access_token=cached.access_token, + delete_if_dead=True, + ) if outcome.data: return outcome.data - if outcome.dead: - # The grant is dead — clear the stale token so the full flow - # below isn't blocked by cached failure state - # (cf. anthropics/claude-code#37747). Compare-and-delete - # (#454): if another process stored a newer token meanwhile, - # it survives. - delete_token( - server_url, - expected_refresh_token=outcome.refresh_token - or cached.refresh_token, - ) - else: + if not outcome.dead: # A transient failure (no answer, 5xx/429, temporarily_unavailable) # says nothing about the grant: keep the token for the next # attempt instead of throwing away weeks of refresh token (#454). diff --git a/src/mcp_stdio/token_store.py b/src/mcp_stdio/token_store.py index aa248809..70ee843e 100644 --- a/src/mcp_stdio/token_store.py +++ b/src/mcp_stdio/token_store.py @@ -725,12 +725,16 @@ def _write_store(data: dict[str, Any]) -> None: @contextlib.contextmanager -def _file_lock(name: str, wait: float | None = None) -> Iterator[None]: +def _file_lock(name: str, wait: float | None = None) -> Iterator[bool]: """Best-effort advisory exclusive lock on ``_STORE_DIR / name``. ``wait`` None blocks until the lock is free (``_store_lock``); a number - bounds the wait in seconds, after which the lock is skipped with a - warning (``refresh_lock``, #454). Everything below applies to both. + bounds the wait in seconds (``refresh_lock``, #454). Yields False only + when that bounded wait ran out while another holder kept the lock, so + the caller can decide not to proceed; it yields True when the lock is + held AND on the degrade-to-unlocked paths below (no primitive, a planted + special file), which keep their old "never block on lock trouble" + behavior. Everything below applies to both. For ``_store_lock`` it serialises ``save_token`` / ``delete_token`` so updates to distinct server keys merge rather than clobbering each other @@ -783,7 +787,7 @@ def _file_lock(name: str, wait: float | None = None) -> Iterator[None]: f"saves may last-writer-wins", file=sys.stderr, ) - yield + yield True return # the 0o600 mode above applies only on CREATION. Re-tighten a # pre-existing lock file via the fd (fchmod, anchored to this inode like @@ -798,18 +802,14 @@ def _file_lock(name: str, wait: float | None = None) -> Iterator[None]: except OSError: pass locked = False + timed_out = False try: try: locked = _acquire(fd, wait) - if not locked: - print( - f"warning: {lock_path.name} still held after {wait:g}s; " - f"proceeding without it", - file=sys.stderr, - ) + timed_out = not locked except (OSError, ImportError, ValueError): pass # best-effort: fall back to an unsynchronised write - yield + yield not timed_out finally: if locked and sys.platform == "win32": try: @@ -869,18 +869,19 @@ def _store_lock() -> Iterator[None]: each call opens its own fd, so code holding it must not call ``save_token`` / ``delete_token``. """ - with _file_lock("tokens.json.lock"): + with _file_lock("tokens.json.lock"): # blocking: never times out yield -# Upper bound on waiting for another process's refresh (#454). Its holder -# makes one token-endpoint round trip, so this only runs out when that -# process is stuck; then refreshing unlocked beats stalling this one. +# Upper bound on waiting for another process's refresh (#454). Running out +# does NOT mean refreshing unlocked — the holder may just be slow, and two +# exchanges of one rotating refresh token is the race this lock prevents — +# the caller re-reads the store and otherwise reports a transient failure. _REFRESH_LOCK_WAIT_SECS = 30.0 @contextlib.contextmanager -def refresh_lock(wait: float = _REFRESH_LOCK_WAIT_SECS) -> Iterator[None]: +def refresh_lock(wait: float | None = None) -> Iterator[bool]: """Cross-process lock around one refresh's load -> exchange -> save (#454). A separate file from ``_store_lock`` (which ``save_token`` takes inside @@ -888,10 +889,13 @@ def refresh_lock(wait: float = _REFRESH_LOCK_WAIT_SECS) -> Iterator[None]: relay processes exchanging the same token make the AS answer the second with ``invalid_grant`` — or revoke the whole family; holding this and re-reading the store after acquiring it means each process exchanges - the latest token. Bounded wait, then unlocked with a warning. + the latest token. Yields False when the bounded wait (default + ``_REFRESH_LOCK_WAIT_SECS``) ran out: the caller must then not exchange. """ - with _file_lock("tokens.json.refresh.lock", wait=wait): - yield + if wait is None: + wait = _REFRESH_LOCK_WAIT_SECS + with _file_lock("tokens.json.refresh.lock", wait=wait) as acquired: + yield acquired def load_token(server_url: str) -> TokenData | None: @@ -1031,12 +1035,19 @@ def save_token(server_url: str, data: TokenData) -> None: ) -def delete_token(server_url: str, *, expected_refresh_token: str | None = None) -> bool: +def delete_token( + server_url: str, + *, + expected_refresh_token: str | None = None, + expected_access_token: str | None = None, +) -> bool: """Delete token data for a server URL; True when an entry was removed. - With ``expected_refresh_token``, delete only while the stored entry still - carries that refresh token (#454): a refresh that just failed must not - remove a newer token another process saved in the meantime. + With ``expected_refresh_token`` / ``expected_access_token``, delete only + while the stored entry still carries those values (#454): a refresh that + just failed must not remove a newer token another process saved in the + meantime — the access token catches an AS that does not rotate the + refresh token. """ with _store_lock(): try: @@ -1055,9 +1066,14 @@ def delete_token(server_url: str, *, expected_refresh_token: str | None = None) for key in {_normalize_key(server_url), server_url}: if key in store: entry = store[key] - if expected_refresh_token is not None and ( - not isinstance(entry, dict) - or entry.get("refresh_token") != expected_refresh_token + expected = { + "refresh_token": expected_refresh_token, + "access_token": expected_access_token, + } + if any( + want is not None + and (not isinstance(entry, dict) or entry.get(field) != want) + for field, want in expected.items() ): continue del store[key] diff --git a/tests/test_oauth.py b/tests/test_oauth.py index 4b8c92de..89fad4d8 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -8050,24 +8050,42 @@ def test_dead_grant_spares_a_token_saved_meanwhile(self, httpx_mock, monkeypatch def racing(server_url, client, cached): outcome = real_locked(server_url, client, cached) - self._save_expired(refresh_token="rt-new", access_token="at-new") + # an unlocked (degraded) writer slips in before the delete; a + # non-rotating AS keeps the refresh token, so only the access + # token differs + self._save_expired(refresh_token="rt-old", access_token="at-new") return outcome monkeypatch.setattr(oauth_mod, "_refresh_locked", racing) assert self._ensure() is None survivor = load_token(_DUR_URL) - assert survivor is not None and survivor.refresh_token == "rt-new" + assert survivor is not None and survivor.access_token == "at-new" - def test_concurrent_refreshes_spend_the_refresh_token_once(self, httpx_mock): - """Two refreshers (two processes; threads with their own lock fds - behave the same): the second waits, re-reads, and uses the first's - new token instead of replaying the rotated refresh token.""" - from mcp_stdio.oauth import refresh_cached_token + def test_concurrent_refreshes_spend_the_refresh_token_once( + self, httpx_mock, monkeypatch + ): + """Two refreshers that both saw the old token (two processes; threads + with their own lock fds behave the same): the second blocks on the + lock while the first exchanges, then re-reads and uses the new token + instead of replaying the rotated refresh token.""" + from mcp_stdio import token_store + from mcp_stdio.oauth import _refresh_cached_token_ex self._save_expired() + in_exchange = threading.Event() + b_waiting = threading.Event() + real_acquire = token_store._acquire + + def acquire(fd, wait): + if threading.current_thread().name == "B": + b_waiting.set() + return real_acquire(fd, wait) - def slow_token(request): - time.sleep(0.3) + monkeypatch.setattr(token_store, "_acquire", acquire) + + def token_endpoint(request): + in_exchange.set() + assert b_waiting.wait(5) # B is now queued behind A's lock return httpx.Response( 200, json={ @@ -8077,20 +8095,128 @@ def slow_token(request): }, ) - httpx_mock.add_callback(slow_token, url=_DUR_TOKEN) - results: list[object] = [] - threads = [ - threading.Thread( - target=lambda: results.append( - refresh_cached_token(_DUR_URL, httpx.Client()) - ) - ) - for _ in range(2) - ] - for th in threads: - th.start() - time.sleep(0.05) # both snapshot the old token before the first saves - for th in threads: - th.join(5) + httpx_mock.add_callback(token_endpoint, url=_DUR_TOKEN) + results: dict[str, object] = {} + + def run(name): + results[name] = _refresh_cached_token_ex( + _DUR_URL, httpx.Client(), seen_access_token="at-old" + ).data + + a = threading.Thread(target=run, args=("A",), name="A") + a.start() + assert in_exchange.wait(5) + b = threading.Thread(target=run, args=("B",), name="B") + b.start() + a.join(5) + b.join(5) + assert len(httpx_mock.get_requests()) == 1 + assert results["A"].access_token == results["B"].access_token == "at-new" + + def test_lock_timeout_does_not_exchange(self, httpx_mock, monkeypatch): + """A slow holder is not a stuck one: running out of patience must not + start a second exchange of the same refresh token.""" + from mcp_stdio import token_store + from mcp_stdio.oauth import _refresh_cached_token_ex + + self._save_expired() + monkeypatch.setattr(token_store, "_REFRESH_LOCK_WAIT_SECS", 0.1) + held, release = threading.Event(), threading.Event() + + def holder(): + with token_store.refresh_lock(): + held.set() + release.wait(5) + + t = threading.Thread(target=holder) + t.start() + assert held.wait(5) + try: + outcome = _refresh_cached_token_ex(_DUR_URL, httpx.Client()) + finally: + release.set() + t.join(5) + assert outcome.data is None and outcome.dead is False + assert httpx_mock.get_requests() == [] + + @pytest.mark.parametrize( + "status, body", + [ + (503, {"error": "invalid_grant"}), # a 5xx stays transient + (429, {"error": "rate_limit_exceeded"}), + (500, {"error": "unknown_error"}), + ], + ) + def test_status_wins_over_the_error_body(self, httpx_mock, status, body): + from mcp_stdio.token_store import load_token + + self._save_expired() + httpx_mock.add_response(url=_DUR_TOKEN, status_code=status, json=body) + assert self._ensure() is None + assert load_token(_DUR_URL) is not None + + def test_decoding_error_is_transient(self, httpx_mock): + from mcp_stdio.token_store import load_token + + self._save_expired() + httpx_mock.add_exception(httpx.DecodingError("bad gzip"), url=_DUR_TOKEN) + assert self._ensure() is None + assert load_token(_DUR_URL) is not None + + def test_scope_retry_skipped_after_a_transient_answer(self, httpx_mock): + """A 503 is not the scope's fault: no scope-less retry, whose own + (e.g. Entra AADSTS90009) answer would read as a dead grant.""" + from mcp_stdio.token_store import load_token, save_token + + save_token( + _DUR_URL, + TokenData( + access_token="at-old", + refresh_token="rt-old", + expires_at=time.time() - 10, + scope="api://app/.default", + client_id="cid", + token_endpoint=_DUR_TOKEN, + authorization_endpoint="https://auth.example.com/authorize", + ), + ) + httpx_mock.add_response(url=_DUR_TOKEN, status_code=503, text="") + assert self._ensure() is None assert len(httpx_mock.get_requests()) == 1 - assert [r.access_token for r in results] == ["at-new", "at-new"] + assert load_token(_DUR_URL) is not None + + def test_reconcile_applies_to_the_latest_stored_token(self, monkeypatch): + """A changed --oauth-resource is persisted onto a fresh read under the + refresh lock, never by writing back a stale copy.""" + from mcp_stdio import oauth as oauth_mod + from mcp_stdio.token_store import load_token, save_token + + save_token( + _DUR_URL, + TokenData( + access_token="at-1", refresh_token="rt-1", expires_at=time.time() + 3600 + ), + ) + real_load = oauth_mod.load_token + calls = {"n": 0} + + def load(url): + calls["n"] += 1 + if calls["n"] == 2: # another process rotated between our reads + save_token( + _DUR_URL, + TokenData( + access_token="at-2", + refresh_token="rt-2", + expires_at=time.time() + 3600, + ), + ) + return real_load(url) + + monkeypatch.setattr(oauth_mod, "load_token", load) + data = ensure_token( + _DUR_URL, httpx.Client(), oauth_resource="api://x", interactive=False + ) + stored = load_token(_DUR_URL) + assert stored.refresh_token == "rt-2" and stored.oauth_resource == "api://x" + assert data.access_token == "at-2" diff --git a/tests/test_token_store.py b/tests/test_token_store.py index 901b0044..ae780161 100644 --- a/tests/test_token_store.py +++ b/tests/test_token_store.py @@ -6,7 +6,6 @@ import stat import sys import threading -import time import pytest @@ -1705,27 +1704,47 @@ def test_delete_with_expected_refresh_token(self): assert delete_token(url, expected_refresh_token="rt-new") is True assert load_token(url) is None - def test_refresh_lock_gives_up_after_its_wait(self, capsys): + def test_refresh_lock_reports_a_timed_out_wait(self): from mcp_stdio.token_store import refresh_lock held = threading.Event() release = threading.Event() def holder(): - with refresh_lock(): + with refresh_lock() as acquired: + assert acquired is True held.set() release.wait(5) t = threading.Thread(target=holder) t.start() assert held.wait(5) - started = time.monotonic() - with refresh_lock(wait=0.2): - waited = time.monotonic() - started - release.set() - t.join(5) - assert 0.15 <= waited < 2 - assert "still held" in capsys.readouterr().err + try: + with refresh_lock(wait=0.1) as acquired: + assert acquired is False # the caller must not exchange + finally: + release.set() + t.join(5) + + def test_delete_compares_the_access_token_too(self): + """A non-rotating AS keeps the refresh token, so only the access token + tells a token another process refreshed from the one that failed.""" + from mcp_stdio.token_store import ( + TokenData, + delete_token, + load_token, + save_token, + ) + + url = "https://x.example/mcp" + save_token(url, TokenData(access_token="at-new", refresh_token="rt")) + assert ( + delete_token( + url, expected_refresh_token="rt", expected_access_token="at-old" + ) + is False + ) + assert load_token(url) is not None def test_refresh_lock_degrades_when_locking_is_unavailable(self, monkeypatch): from mcp_stdio import token_store @@ -1734,7 +1753,5 @@ def broken(fd, wait): raise OSError("no locking here") monkeypatch.setattr(token_store, "_acquire", broken) - ran = [] - with token_store.refresh_lock(): - ran.append(True) - assert ran == [True] + with token_store.refresh_lock() as acquired: + assert acquired is True # degraded: proceed unlocked, as before From a7c4d2c14cbdc141f25557cf496806b0f1c06813 Mon Sep 17 00:00:00 2001 From: AIKAWA Shigechika Date: Mon, 5 Oct 2026 19:55:32 +0900 Subject: [PATCH 3/4] fix(oauth): apply current resource flags to the locked exchange; no lock with nothing to refresh (#455 review) Co-Authored-By: Claude Opus 5.5 --- src/mcp_stdio/oauth.py | 15 +++++++++++++-- tests/test_oauth.py | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/src/mcp_stdio/oauth.py b/src/mcp_stdio/oauth.py index dcaeda0c..7a60820e 100644 --- a/src/mcp_stdio/oauth.py +++ b/src/mcp_stdio/oauth.py @@ -1638,6 +1638,7 @@ def _refresh_cached_token_ex( *, seen_access_token: str | None = None, delete_if_dead: bool = False, + resource_settings: tuple[bool, str | None] | None = None, ) -> _RefreshOutcome: """``refresh_cached_token`` plus why it failed, under ``refresh_lock`` (#454). @@ -1652,11 +1653,18 @@ def _refresh_cached_token_ex( holder may just be slow): a token stored meanwhile is returned, else a transient failure. ``delete_if_dead`` deletes a dead grant while the lock is still held, compared against the failed refresh AND access - tokens, so no newer token can be removed. + tokens, so no newer token can be removed. ``resource_settings`` + (``no_resource_indicator``, ``oauth_resource``) is the caller's current + intent, applied to the freshly read token before the exchange, so a + reconcile that could not be persisted still governs this request. """ if seen_access_token is None: snapshot = load_token(server_url) - seen_access_token = snapshot.access_token if snapshot else None + if snapshot is None: + # Nothing to refresh: skip the lock (and the store-directory + # bootstrap it implies) entirely, as before #454. + return _RefreshOutcome(None, dead=True) + seen_access_token = snapshot.access_token with refresh_lock() as acquired: cached = load_token(server_url) if ( @@ -1672,6 +1680,8 @@ def _refresh_cached_token_ex( "not refreshing concurrently" ) return _RefreshOutcome(None) + if cached is not None and resource_settings is not None: + cached.no_resource_indicator, cached.oauth_resource = resource_settings outcome = _refresh_locked(server_url, client, cached) if outcome.dead and delete_if_dead and cached is not None: delete_token( @@ -2638,6 +2648,7 @@ def ensure_token( client, seen_access_token=cached.access_token, delete_if_dead=True, + resource_settings=(not resource_indicator, oauth_resource), ) if outcome.data: return outcome.data diff --git a/tests/test_oauth.py b/tests/test_oauth.py index 89fad4d8..73946a49 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -1,6 +1,7 @@ """Tests for mcp_stdio.oauth module.""" import base64 +import contextlib import hashlib import inspect import json @@ -8220,3 +8221,43 @@ def load(url): stored = load_token(_DUR_URL) assert stored.refresh_token == "rt-2" and stored.oauth_resource == "api://x" assert data.access_token == "at-2" + + def test_refresh_uses_current_resource_flags_even_if_unpersisted( + self, httpx_mock, monkeypatch + ): + """The reconcile's save can be skipped (lock wait ran out); the + exchange must still follow --no-resource-indicator (#455 review).""" + from mcp_stdio import token_store + + self._save_expired() + real_lock = token_store.refresh_lock + calls = {"n": 0} + + @contextlib.contextmanager + def first_times_out(wait=None): + calls["n"] += 1 + if calls["n"] == 1: # the reconcile's attempt + yield False + return + with real_lock(wait) as acquired: + yield acquired + + monkeypatch.setattr("mcp_stdio.oauth.refresh_lock", first_times_out) + httpx_mock.add_response( + url=_DUR_TOKEN, json={"access_token": "at-new", "expires_in": 3600} + ) + data = ensure_token( + _DUR_URL, httpx.Client(), resource_indicator=False, interactive=False + ) + assert data.access_token == "at-new" + sent = parse_qs(httpx_mock.get_requests()[0].content.decode()) + assert "resource" not in sent + + def test_refresh_without_a_cached_token_skips_the_lock(self, monkeypatch): + from mcp_stdio import oauth as oauth_mod + + def no_lock(*a, **k): + raise AssertionError("refresh_lock taken with nothing to refresh") + + monkeypatch.setattr(oauth_mod, "refresh_lock", no_lock) + assert oauth_mod.refresh_cached_token(_DUR_URL, httpx.Client()) is None From 9735b74e1a060a1eef387ae65f16f19f39b81af6 Mon Sep 17 00:00:00 2001 From: AIKAWA Shigechika Date: Mon, 5 Oct 2026 20:07:46 +0900 Subject: [PATCH 4/4] docs(oauth): reconcile comment matches resource_settings (#455 review) Co-Authored-By: Claude Opus 5.5 --- src/mcp_stdio/oauth.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mcp_stdio/oauth.py b/src/mcp_stdio/oauth.py index 7a60820e..de1b4190 100644 --- a/src/mcp_stdio/oauth.py +++ b/src/mcp_stdio/oauth.py @@ -2615,8 +2615,9 @@ def ensure_token( # Best-effort persist: the reconcile is a convenience, and the cached # access_token is already valid, so a store-write failure must NOT # fail a request this path previously always served. Degrade to the - # in-memory reconciled token (refresh below re-reads the store, so it - # would still use the old settings until the next successful save). + # in-memory reconciled token; the refresh below is handed the same + # settings (``resource_settings``), so it uses them even when this + # save was skipped. # Under refresh_lock, applied to a fresh read (#454): writing back # this possibly stale copy could overwrite a refresh token another # process just rotated.