diff --git a/CLAUDE.md b/CLAUDE.md index 3f54dd1..c877a14 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 1615928..416a97c 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 28ad2c4..de1b419 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,32 @@ 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, 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], status: int | None = None) -> OAuthTokenError: + desc = body.get("error_description", body["error"]) + return OAuthTokenError( + f"OAuth token error: {_sanitize_oauth_error(desc)}", body["error"], status + ) + + 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 +1248,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 +1279,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.status_code) resp.raise_for_status() @@ -1548,6 +1576,49 @@ 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: 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.HTTPError): + 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 +1627,83 @@ 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, + *, + 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). + + ``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. ``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) + 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 ( + seen_access_token is not None + and cached is not None + and cached.access_token != seen_access_token + ): + log("another mcp-stdio process already refreshed the token; using it") + return _RefreshOutcome(cached) + if not acquired: + log( + "another mcp-stdio process is still refreshing this token; " + "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( + server_url, + expected_refresh_token=cached.refresh_token, + expected_access_token=cached.access_token, + ) + return outcome + + +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 +1711,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 @@ -1603,8 +1741,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" @@ -1617,7 +1759,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 +1799,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( @@ -2471,10 +2615,20 @@ 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. 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 ( @@ -2486,13 +2640,24 @@ 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) + # 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, + resource_settings=(not resource_indicator, oauth_resource), + ) + if outcome.data: + return outcome.data + 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). + 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 c0cf9b6..70ee843 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,20 @@ 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[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 (``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. - 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 +755,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 @@ -777,7 +787,7 @@ def _store_lock() -> 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 @@ -792,20 +802,14 @@ def _store_lock() -> Iterator[None]: except OSError: pass locked = False + timed_out = 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) + 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: @@ -818,6 +822,82 @@ 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"): # blocking: never times out + yield + + +# 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 | 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 + 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. Yields False when the bounded wait (default + ``_REFRESH_LOCK_WAIT_SECS``) ran out: the caller must then not exchange. + """ + 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: """Load token data for a server URL. @@ -955,8 +1035,20 @@ 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, + expected_access_token: str | None = None, +) -> bool: + """Delete token data for a server URL; True when an entry was removed. + + 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: store = _read_store(for_write=True) @@ -969,10 +1061,21 @@ 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] + 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] removed = True if removed: @@ -988,3 +1091,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 1a93046..73946a4 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 @@ -7950,3 +7951,313 @@ 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) + # 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.access_token == "at-new" + + 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) + + 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={ + "access_token": "at-new", + "refresh_token": "rt-new", + "expires_in": 3600, + }, + ) + + 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 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" + + 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 diff --git a/tests/test_token_store.py b/tests/test_token_store.py index aec26a7..ae78016 100644 --- a/tests/test_token_store.py +++ b/tests/test_token_store.py @@ -1678,3 +1678,80 @@ 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_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() as acquired: + assert acquired is True + held.set() + release.wait(5) + + t = threading.Thread(target=holder) + t.start() + assert held.wait(5) + 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 + + def broken(fd, wait): + raise OSError("no locking here") + + monkeypatch.setattr(token_store, "_acquire", broken) + with token_store.refresh_lock() as acquired: + assert acquired is True # degraded: proceed unlocked, as before