fix(mcp): refresh expired OAuth tokens automatically (#5573)
* fix(mcp): refresh expired OAuth tokens * fix(mcp): bind refreshed tokens to OAuth issuer * fix(mcp): activate OAuth tools before probe cleanup * fix(webui): preserve failed MCP OAuth status * fix(mcp): preserve OAuth refresh across discovery retries * test(mcp): align OAuth issuer fixture with SDK validation
This commit is contained in:
1 parent
6a8647cfb6
commit
55093dd75b
8 files changed
+1174
-60
No files matched your search
@@ -10,18 +10,27 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import secrets
|
||||
from collections.abc import Awaitable, Callable
|
||||
from contextlib import suppress
|
||||
import time
|
||||
from collections.abc import AsyncGenerator, Awaitable, Callable
|
||||
from contextlib import aclosing, suppress
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, TypedDict, cast
|
||||
|
||||
from filelock import FileLock
|
||||
import httpx
|
||||
from filelock import AsyncFileLock, BaseAsyncFileLock, FileLock
|
||||
from loguru import logger
|
||||
from mcp.client.auth import OAuthClientProvider
|
||||
from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
|
||||
from mcp.shared.auth import (
|
||||
OAuthClientInformationFull,
|
||||
OAuthClientMetadata,
|
||||
OAuthMetadata,
|
||||
OAuthToken,
|
||||
)
|
||||
from pydantic import AnyHttpUrl, AnyUrl
|
||||
|
||||
from nanobot.config.paths import get_data_dir
|
||||
@@ -30,6 +39,7 @@ from nanobot.utils.helpers import _write_text_atomic # pyright: ignore[reportPr
|
||||
MCP_OAUTH_CALLBACK_PATH = "/auth/mcp/callback"
|
||||
_STORE_VERSION = 1
|
||||
_STORE_LOCK_TIMEOUT_S = 15
|
||||
_REFRESH_LOCK_TIMEOUT_S = 60
|
||||
_DEFAULT_REDIRECT_URI = f"http://127.0.0.1{MCP_OAUTH_CALLBACK_PATH}"
|
||||
_CLIENT_URI = AnyHttpUrl("https://github.com/HKUDS/nanobot")
|
||||
_LOGO_URI = AnyHttpUrl(
|
||||
@@ -42,7 +52,11 @@ class _StoredServer(TypedDict, total=False):
|
||||
server_fingerprint: str
|
||||
write_lease: str
|
||||
tokens: dict[str, Any]
|
||||
expires_at: float
|
||||
token_issuer: str
|
||||
client_info: dict[str, Any]
|
||||
oauth_metadata: dict[str, Any]
|
||||
oauth_issuer: str
|
||||
redirect_uri: str
|
||||
|
||||
|
||||
@@ -66,6 +80,24 @@ class MCPOAuthHandlers:
|
||||
reset_credentials: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _OAuthSnapshot:
|
||||
tokens: OAuthToken | None
|
||||
expires_at: float | None
|
||||
token_issuer: str | None
|
||||
client_info: OAuthClientInformationFull | None
|
||||
oauth_metadata: OAuthMetadata | None
|
||||
oauth_issuer: str | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _RefreshLease:
|
||||
lock: BaseAsyncFileLock
|
||||
access_token: str
|
||||
refresh_token: str
|
||||
token_issuer: str
|
||||
|
||||
|
||||
def _store_path() -> Path:
|
||||
return get_data_dir() / "auth" / "mcp.json"
|
||||
|
||||
@@ -74,6 +106,10 @@ def _server_fingerprint(server_url: str) -> str:
|
||||
return hashlib.sha256(server_url.strip().encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _normalize_issuer(value: str) -> str:
|
||||
return value.rstrip("/")
|
||||
|
||||
|
||||
def _empty_store() -> _CredentialStore:
|
||||
return {"version": _STORE_VERSION, "servers": {}, "generations": {}}
|
||||
|
||||
@@ -97,11 +133,29 @@ def _stored_server(value: object) -> _StoredServer | None:
|
||||
token_values = cast(dict[object, object], tokens)
|
||||
if all(isinstance(key, str) for key in token_values):
|
||||
entry["tokens"] = cast(dict[str, Any], token_values)
|
||||
expires_at = raw.get("expires_at")
|
||||
if (
|
||||
isinstance(expires_at, (int, float))
|
||||
and not isinstance(expires_at, bool)
|
||||
and math.isfinite(expires_at)
|
||||
):
|
||||
entry["expires_at"] = float(expires_at)
|
||||
token_issuer = raw.get("token_issuer")
|
||||
if isinstance(token_issuer, str) and token_issuer:
|
||||
entry["token_issuer"] = token_issuer
|
||||
client_info = raw.get("client_info")
|
||||
if isinstance(client_info, dict):
|
||||
client_values = cast(dict[object, object], client_info)
|
||||
if all(isinstance(key, str) for key in client_values):
|
||||
entry["client_info"] = cast(dict[str, Any], client_values)
|
||||
oauth_metadata = raw.get("oauth_metadata")
|
||||
if isinstance(oauth_metadata, dict):
|
||||
metadata_values = cast(dict[object, object], oauth_metadata)
|
||||
if all(isinstance(key, str) for key in metadata_values):
|
||||
entry["oauth_metadata"] = cast(dict[str, Any], metadata_values)
|
||||
oauth_issuer = raw.get("oauth_issuer")
|
||||
if isinstance(oauth_issuer, str) and oauth_issuer:
|
||||
entry["oauth_issuer"] = _normalize_issuer(oauth_issuer)
|
||||
return entry
|
||||
|
||||
|
||||
@@ -257,41 +311,108 @@ class MCPOAuthStorage:
|
||||
_write_store_unlocked(path, payload)
|
||||
return True
|
||||
|
||||
async def get_tokens(self) -> OAuthToken | None:
|
||||
def _snapshot_from_entry(self, entry: _StoredServer | None) -> _OAuthSnapshot:
|
||||
entry = entry or {}
|
||||
tokens: OAuthToken | None = None
|
||||
raw_tokens = entry.get("tokens")
|
||||
if isinstance(raw_tokens, dict):
|
||||
try:
|
||||
tokens = OAuthToken.model_validate(raw_tokens)
|
||||
except (ValueError, TypeError):
|
||||
logger.warning("Ignoring invalid MCP OAuth tokens for '{}'", self.server_name)
|
||||
|
||||
expires_at: float | None = None
|
||||
raw_expiry = entry.get("expires_at")
|
||||
if isinstance(raw_expiry, (int, float)) and not isinstance(raw_expiry, bool):
|
||||
expires_at = float(raw_expiry)
|
||||
|
||||
token_issuer: str | None = None
|
||||
raw_token_issuer = entry.get("token_issuer")
|
||||
if isinstance(raw_token_issuer, str) and raw_token_issuer:
|
||||
token_issuer = raw_token_issuer
|
||||
|
||||
client_info: OAuthClientInformationFull | None = None
|
||||
raw_client = entry.get("client_info")
|
||||
if isinstance(raw_client, dict):
|
||||
try:
|
||||
client_info = OAuthClientInformationFull.model_validate(raw_client)
|
||||
except (ValueError, TypeError):
|
||||
logger.warning(
|
||||
"Ignoring invalid MCP OAuth client info for '{}'",
|
||||
self.server_name,
|
||||
)
|
||||
|
||||
oauth_metadata: OAuthMetadata | None = None
|
||||
raw_metadata = entry.get("oauth_metadata")
|
||||
if isinstance(raw_metadata, dict):
|
||||
try:
|
||||
oauth_metadata = OAuthMetadata.model_validate(raw_metadata)
|
||||
except (ValueError, TypeError):
|
||||
logger.warning(
|
||||
"Ignoring invalid MCP OAuth metadata for '{}'",
|
||||
self.server_name,
|
||||
)
|
||||
|
||||
oauth_issuer: str | None = None
|
||||
raw_oauth_issuer = entry.get("oauth_issuer")
|
||||
if isinstance(raw_oauth_issuer, str) and raw_oauth_issuer:
|
||||
oauth_issuer = _normalize_issuer(raw_oauth_issuer)
|
||||
|
||||
return _OAuthSnapshot(
|
||||
tokens,
|
||||
expires_at,
|
||||
token_issuer,
|
||||
client_info,
|
||||
oauth_metadata,
|
||||
oauth_issuer,
|
||||
)
|
||||
|
||||
async def get_snapshot(self) -> _OAuthSnapshot:
|
||||
entry = await asyncio.to_thread(self._read_entry_sync)
|
||||
raw = entry.get("tokens") if entry is not None else None
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
try:
|
||||
return OAuthToken.model_validate(raw)
|
||||
except (ValueError, TypeError):
|
||||
logger.warning("Ignoring invalid MCP OAuth tokens for '{}'", self.server_name)
|
||||
return None
|
||||
return self._snapshot_from_entry(entry)
|
||||
|
||||
async def get_tokens(self) -> OAuthToken | None:
|
||||
return (await self.get_snapshot()).tokens
|
||||
|
||||
@staticmethod
|
||||
def _replace_tokens(entry: _StoredServer, tokens: OAuthToken | None) -> None:
|
||||
if tokens is None:
|
||||
entry.pop("tokens", None)
|
||||
entry.pop("expires_at", None)
|
||||
entry.pop("token_issuer", None)
|
||||
else:
|
||||
entry["tokens"] = tokens.model_dump(mode="json", exclude_none=True)
|
||||
if tokens.expires_in is None:
|
||||
entry.pop("expires_at", None)
|
||||
else:
|
||||
entry["expires_at"] = time.time() + float(tokens.expires_in)
|
||||
|
||||
async def set_tokens(self, tokens: OAuthToken) -> None:
|
||||
raw = tokens.model_dump(mode="json", exclude_none=True)
|
||||
|
||||
def update(entry: _StoredServer) -> None:
|
||||
entry["tokens"] = raw
|
||||
self._replace_tokens(entry, tokens)
|
||||
issuer = entry.get("oauth_issuer")
|
||||
if isinstance(issuer, str) and issuer:
|
||||
entry["token_issuer"] = _normalize_issuer(issuer)
|
||||
else:
|
||||
entry.pop("token_issuer", None)
|
||||
|
||||
await asyncio.to_thread(self._update_entry_sync, update)
|
||||
|
||||
async def clear_tokens(self) -> None:
|
||||
def update(entry: _StoredServer) -> None:
|
||||
entry.pop("tokens", None)
|
||||
self._replace_tokens(entry, None)
|
||||
|
||||
await asyncio.to_thread(self._update_entry_sync, update, create=False)
|
||||
|
||||
async def clear_tokens_and_client(self) -> None:
|
||||
def update(entry: _StoredServer) -> None:
|
||||
self._replace_tokens(entry, None)
|
||||
entry.pop("client_info", None)
|
||||
|
||||
await asyncio.to_thread(self._update_entry_sync, update, create=False)
|
||||
|
||||
async def get_client_info(self) -> OAuthClientInformationFull | None:
|
||||
entry = await asyncio.to_thread(self._read_entry_sync)
|
||||
raw = entry.get("client_info") if entry is not None else None
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
try:
|
||||
return OAuthClientInformationFull.model_validate(raw)
|
||||
except (ValueError, TypeError):
|
||||
logger.warning("Ignoring invalid MCP OAuth client info for '{}'", self.server_name)
|
||||
return None
|
||||
return (await self.get_snapshot()).client_info
|
||||
|
||||
async def set_client_info(self, client_info: OAuthClientInformationFull) -> None:
|
||||
raw = client_info.model_dump(mode="json", exclude_none=True)
|
||||
@@ -301,6 +422,98 @@ class MCPOAuthStorage:
|
||||
|
||||
await asyncio.to_thread(self._update_entry_sync, update)
|
||||
|
||||
async def set_oauth_metadata(
|
||||
self,
|
||||
metadata: OAuthMetadata,
|
||||
*,
|
||||
issuer: str | None = None,
|
||||
) -> None:
|
||||
raw = metadata.model_dump(mode="json", exclude_none=True)
|
||||
oauth_issuer = _normalize_issuer(issuer or str(metadata.issuer))
|
||||
|
||||
def update(entry: _StoredServer) -> None:
|
||||
entry["oauth_metadata"] = raw
|
||||
entry["oauth_issuer"] = oauth_issuer
|
||||
|
||||
await asyncio.to_thread(self._update_entry_sync, update)
|
||||
|
||||
async def clear_oauth_metadata(self) -> None:
|
||||
def update(entry: _StoredServer) -> None:
|
||||
entry.pop("oauth_metadata", None)
|
||||
entry.pop("oauth_issuer", None)
|
||||
|
||||
await asyncio.to_thread(self._update_entry_sync, update, create=False)
|
||||
|
||||
@staticmethod
|
||||
def _token_binding(entry: _StoredServer) -> tuple[str, str, str] | None:
|
||||
raw = entry.get("tokens")
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
access_token = raw.get("access_token")
|
||||
refresh_token = raw.get("refresh_token")
|
||||
token_issuer = entry.get("token_issuer")
|
||||
if (
|
||||
not isinstance(access_token, str)
|
||||
or not access_token
|
||||
or not isinstance(refresh_token, str)
|
||||
or not refresh_token
|
||||
or not isinstance(token_issuer, str)
|
||||
or not token_issuer
|
||||
):
|
||||
return None
|
||||
return access_token, refresh_token, token_issuer
|
||||
|
||||
def refresh_lock(self) -> BaseAsyncFileLock:
|
||||
path = _store_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
identity = hashlib.sha256(
|
||||
f"{self.server_name}\0{self.server_fingerprint}".encode("utf-8")
|
||||
).hexdigest()
|
||||
return AsyncFileLock(
|
||||
path.with_name(f"mcp-refresh-{identity}.lock"),
|
||||
timeout=_REFRESH_LOCK_TIMEOUT_S,
|
||||
)
|
||||
|
||||
def _finish_refresh_sync(
|
||||
self,
|
||||
lease: _RefreshLease,
|
||||
tokens: OAuthToken | None,
|
||||
*,
|
||||
clear_client: bool,
|
||||
) -> bool:
|
||||
path = _store_path()
|
||||
with _with_store_lock(path):
|
||||
payload = _read_store_unlocked(path)
|
||||
entry, changed = self._bind_entry_unlocked(payload, create=False)
|
||||
if (
|
||||
entry is None
|
||||
or self._token_binding(entry)
|
||||
!= (lease.access_token, lease.refresh_token, lease.token_issuer)
|
||||
):
|
||||
if changed:
|
||||
_write_store_unlocked(path, payload)
|
||||
return False
|
||||
|
||||
self._replace_tokens(entry, tokens)
|
||||
if clear_client:
|
||||
entry.pop("client_info", None)
|
||||
_write_store_unlocked(path, payload)
|
||||
return True
|
||||
|
||||
async def finish_refresh(
|
||||
self,
|
||||
lease: _RefreshLease,
|
||||
tokens: OAuthToken | None,
|
||||
*,
|
||||
clear_client: bool = False,
|
||||
) -> bool:
|
||||
return await asyncio.to_thread(
|
||||
self._finish_refresh_sync,
|
||||
lease,
|
||||
tokens,
|
||||
clear_client=clear_client,
|
||||
)
|
||||
|
||||
async def redirect_uri(self) -> str | None:
|
||||
entry = await asyncio.to_thread(self._read_entry_sync)
|
||||
value = entry.get("redirect_uri") if entry is not None else None
|
||||
@@ -310,7 +523,7 @@ class MCPOAuthStorage:
|
||||
def update(entry: _StoredServer) -> None:
|
||||
changed = entry.get("redirect_uri") != redirect_uri
|
||||
if reset:
|
||||
entry.pop("tokens", None)
|
||||
self._replace_tokens(entry, None)
|
||||
entry.pop("client_info", None)
|
||||
elif changed:
|
||||
# Dynamic registrations bind a client to its redirect URI.
|
||||
@@ -331,6 +544,267 @@ class MCPOAuthStorage:
|
||||
return isinstance(access_token, str) and bool(access_token)
|
||||
|
||||
|
||||
class MCPTokenRefreshError(RuntimeError):
|
||||
"""Raised when a refresh failed without proving that authorization is invalid."""
|
||||
|
||||
|
||||
class _RetryOAuthWithDiscoveredMetadata(BaseException):
|
||||
"""Restart the SDK flow after discovery without logging a false OAuth failure."""
|
||||
|
||||
|
||||
class _RetryOAuthWithStoredCredentials(BaseException):
|
||||
"""Restart the SDK flow with credentials refreshed by another provider."""
|
||||
|
||||
|
||||
def _oauth_error_code(response: httpx.Response) -> str | None:
|
||||
try:
|
||||
payload = cast(object, response.json())
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
error = cast(dict[object, object], payload).get("error")
|
||||
return error if isinstance(error, str) else None
|
||||
|
||||
|
||||
class _RefreshingOAuthClientProvider(OAuthClientProvider):
|
||||
"""MCP SDK OAuth provider with restart-safe, one-shot token refresh.
|
||||
|
||||
This is a compatibility layer for modelcontextprotocol/python-sdk#3328.
|
||||
Its private SDK method contract is pinned by tests and should be removed once
|
||||
the upstream fix is available in nanobot's supported MCP version.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
server_url: str,
|
||||
client_metadata: OAuthClientMetadata,
|
||||
storage: MCPOAuthStorage,
|
||||
redirect_handler: Callable[[str], Awaitable[None]] | None = None,
|
||||
callback_handler: Callable[[], Awaitable[tuple[str, str | None]]] | None = None,
|
||||
timeout: float = 300.0,
|
||||
) -> None:
|
||||
self._nanobot_storage = storage
|
||||
self._refresh_attempted = ContextVar("mcp_oauth_refresh_attempted", default=False)
|
||||
self._refresh_after_discovery = ContextVar(
|
||||
"mcp_oauth_refresh_after_discovery",
|
||||
default=False,
|
||||
)
|
||||
self._refresh_claim = ContextVar[_RefreshLease | None](
|
||||
"mcp_oauth_refresh_claim",
|
||||
default=None,
|
||||
)
|
||||
self._token_issuer: str | None = None
|
||||
super().__init__(
|
||||
server_url,
|
||||
client_metadata,
|
||||
storage,
|
||||
redirect_handler=redirect_handler,
|
||||
callback_handler=callback_handler,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
async def _initialize(self) -> None:
|
||||
"""Restore enough OAuth state to refresh without an interactive flow."""
|
||||
self._apply_snapshot(await self._nanobot_storage.get_snapshot())
|
||||
self._initialized = True
|
||||
|
||||
def _apply_snapshot(self, snapshot: _OAuthSnapshot) -> None:
|
||||
self.context.current_tokens = snapshot.tokens
|
||||
self.context.token_expiry_time = snapshot.expires_at
|
||||
if snapshot.oauth_metadata is None or snapshot.oauth_issuer is None:
|
||||
# Defer the SDK's pre-request refresh until a 401 discovers metadata.
|
||||
# Keep the persisted expiry and issuer binding for retries and restarts.
|
||||
self.context.token_expiry_time = None
|
||||
self._token_issuer = snapshot.token_issuer
|
||||
self.context.client_info = snapshot.client_info
|
||||
self.context.oauth_metadata = snapshot.oauth_metadata
|
||||
self.context.auth_server_url = snapshot.oauth_issuer
|
||||
|
||||
async def _reload_after_lost_claim(self, lease: _RefreshLease) -> bool:
|
||||
snapshot = await self._nanobot_storage.get_snapshot()
|
||||
self._apply_snapshot(snapshot)
|
||||
tokens = snapshot.tokens
|
||||
if tokens is None:
|
||||
return False
|
||||
if (tokens.access_token, tokens.refresh_token) != (
|
||||
lease.access_token,
|
||||
lease.refresh_token,
|
||||
):
|
||||
return True
|
||||
raise MCPTokenRefreshError("MCP OAuth credentials changed while refreshing; retry later")
|
||||
|
||||
async def _release_refresh_claim(self) -> None:
|
||||
lease = self._refresh_claim.get()
|
||||
if lease is None:
|
||||
return
|
||||
self._refresh_claim.set(None)
|
||||
await lease.lock.release()
|
||||
|
||||
async def _handle_refresh_response(self, response: httpx.Response) -> bool:
|
||||
"""Persist a rotated token pair while retaining credentials on transient errors."""
|
||||
lease = self._refresh_claim.get()
|
||||
if lease is None:
|
||||
raise MCPTokenRefreshError("MCP OAuth refresh response has no storage lease")
|
||||
|
||||
if response.status_code != 200:
|
||||
error = _oauth_error_code(response)
|
||||
if error in {"invalid_grant", "invalid_client", "unauthorized_client"}:
|
||||
clear_client = error != "invalid_grant"
|
||||
cleared = await self._nanobot_storage.finish_refresh(
|
||||
lease,
|
||||
None,
|
||||
clear_client=clear_client,
|
||||
)
|
||||
await self._release_refresh_claim()
|
||||
if not cleared:
|
||||
return await self._reload_after_lost_claim(lease)
|
||||
self.context.clear_tokens()
|
||||
self._token_issuer = None
|
||||
if clear_client:
|
||||
self.context.client_info = None
|
||||
return False
|
||||
if response.status_code == 404:
|
||||
await self._release_refresh_claim()
|
||||
await self._nanobot_storage.clear_oauth_metadata()
|
||||
self.context.oauth_metadata = None
|
||||
self._refresh_attempted.set(False)
|
||||
return False
|
||||
await self._release_refresh_claim()
|
||||
raise MCPTokenRefreshError(
|
||||
f"MCP OAuth token refresh failed ({response.status_code}); will retry later"
|
||||
)
|
||||
|
||||
try:
|
||||
token_response = OAuthToken.model_validate_json(await response.aread())
|
||||
except (ValueError, TypeError) as exc:
|
||||
await self._release_refresh_claim()
|
||||
raise MCPTokenRefreshError("MCP OAuth token refresh returned an invalid response") from exc
|
||||
|
||||
previous = self.context.current_tokens
|
||||
updates: dict[str, str] = {}
|
||||
if previous is not None:
|
||||
if token_response.refresh_token is None and previous.refresh_token is not None:
|
||||
updates["refresh_token"] = previous.refresh_token
|
||||
if token_response.scope is None and previous.scope is not None:
|
||||
updates["scope"] = previous.scope
|
||||
if updates:
|
||||
token_response = token_response.model_copy(update=updates)
|
||||
|
||||
committed = await self._nanobot_storage.finish_refresh(lease, token_response)
|
||||
await self._release_refresh_claim()
|
||||
if not committed:
|
||||
return await self._reload_after_lost_claim(lease)
|
||||
self.context.current_tokens = token_response
|
||||
self.context.update_token_expiry(token_response)
|
||||
return True
|
||||
|
||||
async def _refresh_token(self) -> httpx.Request:
|
||||
tokens = self.context.current_tokens
|
||||
if tokens is None or tokens.refresh_token is None:
|
||||
return await super()._refresh_token()
|
||||
lock = self._nanobot_storage.refresh_lock()
|
||||
await lock.acquire()
|
||||
try:
|
||||
snapshot = await self._nanobot_storage.get_snapshot()
|
||||
except BaseException:
|
||||
await lock.release()
|
||||
raise
|
||||
stored_tokens = snapshot.tokens
|
||||
if stored_tokens is None or (
|
||||
stored_tokens.access_token,
|
||||
stored_tokens.refresh_token,
|
||||
snapshot.token_issuer,
|
||||
) != (tokens.access_token, tokens.refresh_token, self._token_issuer):
|
||||
await lock.release()
|
||||
self._apply_snapshot(snapshot)
|
||||
raise _RetryOAuthWithStoredCredentials
|
||||
metadata = self.context.oauth_metadata
|
||||
token_issuer = self._token_issuer
|
||||
oauth_issuer = self.context.auth_server_url
|
||||
if metadata is None or oauth_issuer is None or token_issuer != _normalize_issuer(oauth_issuer):
|
||||
try:
|
||||
await self._nanobot_storage.clear_tokens()
|
||||
finally:
|
||||
await lock.release()
|
||||
self.context.clear_tokens()
|
||||
self._token_issuer = None
|
||||
raise _RetryOAuthWithStoredCredentials
|
||||
assert token_issuer is not None
|
||||
lease = _RefreshLease(
|
||||
lock=lock,
|
||||
access_token=tokens.access_token,
|
||||
refresh_token=tokens.refresh_token,
|
||||
token_issuer=token_issuer,
|
||||
)
|
||||
self._refresh_claim.set(lease)
|
||||
self._refresh_attempted.set(True)
|
||||
try:
|
||||
return await super()._refresh_token()
|
||||
except BaseException:
|
||||
await self._release_refresh_claim()
|
||||
raise
|
||||
|
||||
async def _perform_authorization(self) -> httpx.Request:
|
||||
metadata = self.context.oauth_metadata
|
||||
oauth_issuer: str | None = None
|
||||
if metadata is not None:
|
||||
oauth_issuer = _normalize_issuer(self.context.auth_server_url or str(metadata.issuer))
|
||||
await self._nanobot_storage.set_oauth_metadata(metadata, issuer=oauth_issuer)
|
||||
if self._refresh_after_discovery.get():
|
||||
if metadata is not None and oauth_issuer == self._token_issuer:
|
||||
raise _RetryOAuthWithDiscoveredMetadata
|
||||
await self._nanobot_storage.clear_tokens_and_client()
|
||||
self.context.clear_tokens()
|
||||
self.context.client_info = None
|
||||
self._token_issuer = None
|
||||
raise _RetryOAuthWithStoredCredentials
|
||||
return await super()._perform_authorization()
|
||||
|
||||
async def async_auth_flow(
|
||||
self,
|
||||
request: httpx.Request,
|
||||
) -> AsyncGenerator[httpx.Request, httpx.Response]:
|
||||
"""Let a 401 discover the token endpoint, then restart once to refresh."""
|
||||
try:
|
||||
for attempt in range(3):
|
||||
self._refresh_attempted.set(False)
|
||||
self._refresh_after_discovery.set(False)
|
||||
try:
|
||||
async with aclosing(super().async_auth_flow(request)) as flow:
|
||||
try:
|
||||
outgoing = await anext(flow)
|
||||
except StopAsyncIteration:
|
||||
return
|
||||
while True:
|
||||
response = yield outgoing
|
||||
if (
|
||||
attempt == 0
|
||||
and outgoing is request
|
||||
and response.status_code == 401
|
||||
and not self._refresh_attempted.get()
|
||||
and self.context.can_refresh_token()
|
||||
):
|
||||
self._refresh_after_discovery.set(True)
|
||||
try:
|
||||
outgoing = await flow.asend(response)
|
||||
except StopAsyncIteration:
|
||||
return
|
||||
except _RetryOAuthWithDiscoveredMetadata:
|
||||
# The SDK has now validated discovery metadata. Mark the token
|
||||
# expired so its normal pre-request branch refreshes against the
|
||||
# discovered endpoint instead of guessing {server_origin}/token.
|
||||
self.context.token_expiry_time = time.time() - 1
|
||||
continue
|
||||
except _RetryOAuthWithStoredCredentials:
|
||||
continue
|
||||
finally:
|
||||
self._refresh_after_discovery.set(False)
|
||||
raise AssertionError("MCP OAuth refresh retry did not complete")
|
||||
finally:
|
||||
await self._release_refresh_claim()
|
||||
|
||||
|
||||
async def _missing_callback() -> tuple[str, str | None]:
|
||||
raise MCPAuthorizationRequiredError("MCP server requires browser authorization")
|
||||
|
||||
@@ -372,7 +846,7 @@ async def create_mcp_oauth_auth(
|
||||
logo_uri=_LOGO_URI,
|
||||
software_id="https://github.com/HKUDS/nanobot",
|
||||
)
|
||||
return OAuthClientProvider(
|
||||
return _RefreshingOAuthClientProvider(
|
||||
server_url,
|
||||
metadata,
|
||||
storage,
|
||||
|
||||
@@ -287,7 +287,15 @@ class McpOAuthManager:
|
||||
flow.error = "MCP authorization timed out."
|
||||
raise _OAuthCallbackError(flow.error) from exc
|
||||
|
||||
async def _connect(self, flow: _McpOAuthFlow, handlers: MCPOAuthHandlers) -> bool:
|
||||
@staticmethod
|
||||
async def _close_connections(connections: dict[str, MCPConnection]) -> None:
|
||||
for connection in connections.values():
|
||||
with suppress(Exception):
|
||||
await connection.aclose()
|
||||
|
||||
async def _connect(
|
||||
self, flow: _McpOAuthFlow, handlers: MCPOAuthHandlers
|
||||
) -> dict[str, MCPConnection]:
|
||||
connections: dict[str, MCPConnection] = {}
|
||||
try:
|
||||
connections = await connect_mcp_servers(
|
||||
@@ -295,20 +303,19 @@ class McpOAuthManager:
|
||||
ToolRegistry(),
|
||||
oauth_handlers={flow.name: handlers},
|
||||
)
|
||||
succeeded = flow.name in connections
|
||||
if not succeeded and flow.error is None:
|
||||
if flow.name not in connections:
|
||||
await self._close_connections(connections)
|
||||
connections = {}
|
||||
if not connections and flow.error is None:
|
||||
flow.error = "Could not complete the MCP OAuth connection."
|
||||
return succeeded
|
||||
return connections
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
if flow.error is None:
|
||||
flow.error = "Could not complete the MCP OAuth connection."
|
||||
return False
|
||||
finally:
|
||||
for connection in connections.values():
|
||||
with suppress(Exception):
|
||||
await connection.aclose()
|
||||
await self._close_connections(connections)
|
||||
return {}
|
||||
|
||||
async def _connect_and_reload(
|
||||
self,
|
||||
@@ -316,8 +323,8 @@ class McpOAuthManager:
|
||||
handlers: MCPOAuthHandlers,
|
||||
reload_mcp: McpReload,
|
||||
) -> bool:
|
||||
succeeded = await self._connect(flow, handlers)
|
||||
if not succeeded:
|
||||
connections = await self._connect(flow, handlers)
|
||||
if flow.name not in connections:
|
||||
return False
|
||||
try:
|
||||
flow.reload_result = await reload_mcp()
|
||||
@@ -335,6 +342,8 @@ class McpOAuthManager:
|
||||
"message": "Signed in, but nanobot could not activate the MCP tools.",
|
||||
"requires_restart": True,
|
||||
}
|
||||
finally:
|
||||
await self._close_connections(connections)
|
||||
return True
|
||||
|
||||
def _flow(self, flow_id: str) -> _McpOAuthFlow:
|
||||
@@ -346,7 +355,14 @@ class McpOAuthManager:
|
||||
def _payload(self, flow: _McpOAuthFlow) -> dict[str, Any]:
|
||||
task = flow.task
|
||||
connected = flow.reload_result.get("connected") if flow.reload_result is not None else None
|
||||
if task is not None and task.cancelled():
|
||||
activated = flow.reload_result is not None and (
|
||||
flow.reload_result.get("ok") or (isinstance(connected, list) and flow.name in connected)
|
||||
)
|
||||
if activated:
|
||||
status = "connected"
|
||||
elif flow.reload_result is not None:
|
||||
status = "authorized"
|
||||
elif task is not None and task.cancelled():
|
||||
status = "cancelled"
|
||||
elif task is not None and task.done():
|
||||
try:
|
||||
@@ -355,12 +371,6 @@ class McpOAuthManager:
|
||||
succeeded = False
|
||||
if not succeeded:
|
||||
status = "failed"
|
||||
elif flow.reload_result is None:
|
||||
status = "authorized"
|
||||
elif flow.reload_result.get("ok") or (
|
||||
isinstance(connected, list) and flow.name in connected
|
||||
):
|
||||
status = "connected"
|
||||
else:
|
||||
status = "authorized"
|
||||
elif flow.callback_received:
|
||||
|
||||
@@ -984,7 +984,7 @@ def attach_mcp_runtime_status(
|
||||
payload: dict[str, Any],
|
||||
runtime_status: Mapping[str, str] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""Project safe, connection-attempt state onto configured MCP rows."""
|
||||
"""Project safe, connection-attempt state onto eligible installed MCP rows."""
|
||||
if runtime_status is None:
|
||||
return payload
|
||||
projected = dict(payload)
|
||||
@@ -998,10 +998,15 @@ def attach_mcp_runtime_status(
|
||||
row = dict(cast(dict[str, Any], raw_row))
|
||||
name = row.get("name")
|
||||
status = runtime_status.get(name) if isinstance(name, str) else None
|
||||
oauth_authorization_failed = (
|
||||
status == "failed"
|
||||
and row.get("auth") == "oauth"
|
||||
and row.get("status") == "authorization_required"
|
||||
)
|
||||
if (
|
||||
status in _MCP_RUNTIME_STATUSES
|
||||
and row.get("installed") is True
|
||||
and row.get("configured") is True
|
||||
and (row.get("configured") is True or oauth_authorization_failed)
|
||||
):
|
||||
row["runtime_status"] = status
|
||||
else:
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import inspect
|
||||
import json
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from mcp.shared.auth import OAuthClientInformationFull, OAuthToken
|
||||
from mcp.client.auth import OAuthClientProvider
|
||||
from mcp.shared.auth import OAuthClientInformationFull, OAuthMetadata, OAuthToken
|
||||
|
||||
from nanobot.agent.tools.mcp_oauth import (
|
||||
MCPAuthorizationRequiredError,
|
||||
MCPOAuthHandlers,
|
||||
MCPOAuthStorage,
|
||||
MCPTokenRefreshError,
|
||||
create_mcp_oauth_auth,
|
||||
delete_mcp_oauth_credentials,
|
||||
mcp_oauth_has_credentials,
|
||||
@@ -22,6 +26,32 @@ def _use_data_dir(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr("nanobot.agent.tools.mcp_oauth.get_data_dir", lambda: tmp_path)
|
||||
|
||||
|
||||
def _oauth_metadata() -> OAuthMetadata:
|
||||
return OAuthMetadata.model_validate({
|
||||
"issuer": "https://auth.example.com",
|
||||
"authorization_endpoint": "https://auth.example.com/authorize",
|
||||
"token_endpoint": "https://auth.example.com/oauth/token",
|
||||
"registration_endpoint": "https://auth.example.com/register",
|
||||
"response_types_supported": ["code"],
|
||||
"code_challenge_methods_supported": ["S256"],
|
||||
})
|
||||
|
||||
|
||||
def test_refresh_provider_sdk_private_method_contract() -> None:
|
||||
"""Fail dependency updates loudly while the SDK refresh workaround is needed."""
|
||||
expected_parameters = {
|
||||
"_initialize": ("self",),
|
||||
"_refresh_token": ("self",),
|
||||
"_handle_refresh_response": ("self", "response"),
|
||||
"_perform_authorization": ("self",),
|
||||
"async_auth_flow": ("self", "request"),
|
||||
}
|
||||
|
||||
for method_name, expected in expected_parameters.items():
|
||||
method = getattr(OAuthClientProvider, method_name)
|
||||
assert tuple(inspect.signature(method).parameters) == expected
|
||||
|
||||
|
||||
def test_mcp_server_config_accepts_explicit_oauth() -> None:
|
||||
config = MCPServerConfig.model_validate({
|
||||
"type": "streamableHttp",
|
||||
@@ -91,7 +121,7 @@ async def test_reset_and_delete_credentials_are_scoped_to_one_server(
|
||||
_use_data_dir(tmp_path, monkeypatch)
|
||||
first = MCPOAuthStorage("first", "https://mcp.example.com/mcp")
|
||||
second = MCPOAuthStorage("second", "https://mcp.example.com/mcp")
|
||||
await first.set_tokens(OAuthToken(access_token="first-token"))
|
||||
await first.set_tokens(OAuthToken(access_token="first-token", expires_in=3600))
|
||||
await second.set_tokens(OAuthToken(access_token="second-token"))
|
||||
|
||||
await first.prepare_redirect_uri(
|
||||
@@ -100,6 +130,7 @@ async def test_reset_and_delete_credentials_are_scoped_to_one_server(
|
||||
)
|
||||
|
||||
assert await first.get_tokens() is None
|
||||
assert (await first.get_snapshot()).expires_at is None
|
||||
assert await second.get_tokens() is not None
|
||||
assert delete_mcp_oauth_credentials("first")
|
||||
assert not delete_mcp_oauth_credentials("first")
|
||||
@@ -231,6 +262,485 @@ async def test_background_authorization_request_clears_rejected_token(
|
||||
assert await storage.get_client_info() == client_info
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_expired_token_refreshes_from_persisted_metadata_after_restart(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
_use_data_dir(tmp_path, monkeypatch)
|
||||
server_url = "https://mcp.example.com/mcp"
|
||||
storage = MCPOAuthStorage("linear", server_url)
|
||||
await storage.set_oauth_metadata(_oauth_metadata())
|
||||
await storage.set_tokens(OAuthToken(
|
||||
access_token="expired-access",
|
||||
refresh_token="refresh-token",
|
||||
expires_in=-1,
|
||||
))
|
||||
await storage.set_client_info(OAuthClientInformationFull(
|
||||
redirect_uris=["https://agent.example/auth/mcp/callback"],
|
||||
client_id="registered-client",
|
||||
))
|
||||
auth = await create_mcp_oauth_auth("linear", server_url)
|
||||
requests: list[tuple[str, str]] = []
|
||||
|
||||
async def respond(request: httpx.Request) -> httpx.Response:
|
||||
requests.append((request.method, str(request.url)))
|
||||
if request.url.path == "/oauth/token":
|
||||
form = parse_qs(request.content.decode())
|
||||
assert form["grant_type"] == ["refresh_token"]
|
||||
assert form["refresh_token"] == ["refresh-token"]
|
||||
return httpx.Response(200, json={
|
||||
"access_token": "fresh-access",
|
||||
"refresh_token": "rotated-refresh",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
})
|
||||
assert request.headers["Authorization"] == "Bearer fresh-access"
|
||||
return httpx.Response(200, json={"ok": True})
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(respond), auth=auth) as client:
|
||||
response = await client.get(server_url)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert requests == [
|
||||
("POST", "https://auth.example.com/oauth/token"),
|
||||
("GET", server_url),
|
||||
]
|
||||
snapshot = await MCPOAuthStorage("linear", server_url).get_snapshot()
|
||||
assert snapshot.tokens is not None
|
||||
assert snapshot.tokens.access_token == "fresh-access"
|
||||
assert snapshot.tokens.refresh_token == "rotated-refresh"
|
||||
assert snapshot.token_issuer == "https://auth.example.com"
|
||||
lock = storage.refresh_lock()
|
||||
await asyncio.wait_for(lock.acquire(), timeout=1)
|
||||
await lock.release()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("message_path", ["/mcp", "/messages?session_id=123"])
|
||||
async def test_issuer_bound_token_refreshes_after_401_discovers_endpoint(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
message_path: str,
|
||||
) -> None:
|
||||
_use_data_dir(tmp_path, monkeypatch)
|
||||
server_url = "https://mcp.example.com/mcp"
|
||||
message_url = f"https://mcp.example.com{message_path}"
|
||||
storage = MCPOAuthStorage("linear", server_url)
|
||||
await storage.set_oauth_metadata(_oauth_metadata())
|
||||
await storage.set_tokens(OAuthToken(
|
||||
access_token="stale-access",
|
||||
refresh_token="refresh-token",
|
||||
))
|
||||
await storage.set_client_info(OAuthClientInformationFull(
|
||||
redirect_uris=["https://agent.example/auth/mcp/callback"],
|
||||
client_id="registered-client",
|
||||
))
|
||||
await storage.clear_oauth_metadata()
|
||||
auth = await create_mcp_oauth_auth("linear", server_url)
|
||||
resource_requests = 0
|
||||
|
||||
async def respond(request: httpx.Request) -> httpx.Response:
|
||||
nonlocal resource_requests
|
||||
if str(request.url) == message_url:
|
||||
resource_requests += 1
|
||||
if request.headers.get("Authorization") == "Bearer fresh-access":
|
||||
return httpx.Response(200, json={"ok": True})
|
||||
return httpx.Response(401, headers={
|
||||
"WWW-Authenticate": (
|
||||
'Bearer resource_metadata="https://mcp.example.com/'
|
||||
'.well-known/oauth-protected-resource"'
|
||||
)
|
||||
})
|
||||
if request.url.path == "/.well-known/oauth-protected-resource":
|
||||
return httpx.Response(200, json={
|
||||
"resource": server_url,
|
||||
"authorization_servers": ["https://auth.example.com"],
|
||||
})
|
||||
if request.url.path == "/.well-known/oauth-authorization-server":
|
||||
return httpx.Response(200, json=_oauth_metadata().model_dump(mode="json"))
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(200, json={
|
||||
"access_token": "fresh-access",
|
||||
"refresh_token": "rotated-refresh",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
})
|
||||
return httpx.Response(404)
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(respond), auth=auth) as client:
|
||||
response = await client.post(message_url, json={"method": "tools/list"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert resource_requests == 2
|
||||
reloaded = MCPOAuthStorage("linear", server_url)
|
||||
assert (await reloaded.get_snapshot()).oauth_metadata == _oauth_metadata()
|
||||
stored = await reloaded.get_tokens()
|
||||
assert stored is not None
|
||||
assert stored.refresh_token == "rotated-refresh"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("bound", [False, True], ids=["legacy-unbound", "issuer-changed"])
|
||||
async def test_untrusted_issuer_never_receives_refresh_token(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
bound: bool,
|
||||
) -> None:
|
||||
_use_data_dir(tmp_path, monkeypatch)
|
||||
server_url = "https://mcp.example.com/mcp"
|
||||
storage = MCPOAuthStorage("linear", server_url)
|
||||
if bound:
|
||||
await storage.set_oauth_metadata(_oauth_metadata())
|
||||
await storage.set_tokens(OAuthToken(
|
||||
access_token="stale-access",
|
||||
refresh_token="legacy-refresh-secret",
|
||||
))
|
||||
await storage.set_client_info(OAuthClientInformationFull(
|
||||
redirect_uris=["https://agent.example/auth/mcp/callback"],
|
||||
client_id="registered-client",
|
||||
))
|
||||
if bound:
|
||||
await storage.clear_oauth_metadata()
|
||||
auth = await create_mcp_oauth_auth("linear", server_url)
|
||||
refresh_requests: list[str] = []
|
||||
attacker_payload = _oauth_metadata().model_dump(mode="json")
|
||||
attacker_payload.update({
|
||||
"issuer": "https://attacker.example.com",
|
||||
"authorization_endpoint": "https://attacker.example.com/authorize",
|
||||
"token_endpoint": "https://attacker.example.com/oauth/token",
|
||||
"registration_endpoint": "https://attacker.example.com/register",
|
||||
})
|
||||
attacker_metadata = OAuthMetadata.model_validate(attacker_payload)
|
||||
|
||||
async def respond(request: httpx.Request) -> httpx.Response:
|
||||
if str(request.url) == server_url:
|
||||
return httpx.Response(401, headers={
|
||||
"WWW-Authenticate": (
|
||||
'Bearer resource_metadata="https://mcp.example.com/'
|
||||
'.well-known/oauth-protected-resource"'
|
||||
)
|
||||
})
|
||||
if request.url.path == "/.well-known/oauth-protected-resource":
|
||||
return httpx.Response(200, json={
|
||||
"resource": server_url,
|
||||
"authorization_servers": ["https://attacker.example.com"],
|
||||
})
|
||||
if request.url.path == "/.well-known/oauth-authorization-server":
|
||||
return httpx.Response(200, json=attacker_metadata.model_dump(mode="json"))
|
||||
if request.url.path == "/register":
|
||||
return httpx.Response(201, json={
|
||||
"client_id": "replacement-client",
|
||||
"redirect_uris": ["http://127.0.0.1/auth/mcp/callback"],
|
||||
"token_endpoint_auth_method": "none",
|
||||
})
|
||||
if request.url.path == "/oauth/token":
|
||||
refresh_requests.append(str(request.url))
|
||||
return httpx.Response(200, json={
|
||||
"access_token": "stolen-refresh-result",
|
||||
"token_type": "Bearer",
|
||||
})
|
||||
return httpx.Response(404)
|
||||
|
||||
with pytest.raises(MCPAuthorizationRequiredError):
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.MockTransport(respond),
|
||||
auth=auth,
|
||||
) as client:
|
||||
await client.get(server_url)
|
||||
|
||||
assert refresh_requests == []
|
||||
snapshot = await MCPOAuthStorage("linear", server_url).get_snapshot()
|
||||
assert snapshot.tokens is None
|
||||
assert snapshot.token_issuer is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_transient_refresh_failure_preserves_credentials(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
_use_data_dir(tmp_path, monkeypatch)
|
||||
server_url = "https://mcp.example.com/mcp"
|
||||
storage = MCPOAuthStorage("linear", server_url)
|
||||
original = OAuthToken(
|
||||
access_token="expired-access",
|
||||
refresh_token="refresh-token",
|
||||
expires_in=-1,
|
||||
)
|
||||
await storage.set_oauth_metadata(_oauth_metadata())
|
||||
await storage.set_tokens(original)
|
||||
await storage.set_client_info(OAuthClientInformationFull(
|
||||
redirect_uris=["https://agent.example/auth/mcp/callback"],
|
||||
client_id="registered-client",
|
||||
))
|
||||
auth = await create_mcp_oauth_auth("linear", server_url)
|
||||
|
||||
async def respond(_request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(503, text="temporarily unavailable")
|
||||
|
||||
with pytest.raises(MCPTokenRefreshError, match="will retry later"):
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.MockTransport(respond),
|
||||
auth=auth,
|
||||
) as client:
|
||||
await client.get(server_url)
|
||||
|
||||
stored = await MCPOAuthStorage("linear", server_url).get_tokens()
|
||||
assert stored == original
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("recovery", ["immediate", "retry", "restart"])
|
||||
async def test_stale_token_endpoint_is_rediscovered_once(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
recovery: str,
|
||||
) -> None:
|
||||
_use_data_dir(tmp_path, monkeypatch)
|
||||
server_url = "https://mcp.example.com/mcp"
|
||||
storage = MCPOAuthStorage("linear", server_url)
|
||||
stale_payload = _oauth_metadata().model_dump(mode="json")
|
||||
stale_payload["token_endpoint"] = "https://auth.example.com/old/token"
|
||||
stale_metadata = OAuthMetadata.model_validate(stale_payload)
|
||||
await storage.set_oauth_metadata(stale_metadata)
|
||||
await storage.set_tokens(OAuthToken(
|
||||
access_token="expired-access",
|
||||
refresh_token="refresh-token",
|
||||
expires_in=-1,
|
||||
))
|
||||
await storage.set_client_info(OAuthClientInformationFull(
|
||||
redirect_uris=["https://agent.example/auth/mcp/callback"],
|
||||
client_id="registered-client",
|
||||
))
|
||||
auth = await create_mcp_oauth_auth("linear", server_url)
|
||||
refresh_urls: list[str] = []
|
||||
discovery_unavailable = recovery != "immediate"
|
||||
|
||||
async def respond(request: httpx.Request) -> httpx.Response:
|
||||
nonlocal discovery_unavailable
|
||||
if request.url.path == "/old/token":
|
||||
refresh_urls.append(str(request.url))
|
||||
return httpx.Response(404)
|
||||
if str(request.url) == server_url:
|
||||
if request.headers.get("Authorization") == "Bearer fresh-access":
|
||||
return httpx.Response(200, json={"ok": True})
|
||||
return httpx.Response(401, headers={
|
||||
"WWW-Authenticate": (
|
||||
'Bearer resource_metadata="https://mcp.example.com/'
|
||||
'.well-known/oauth-protected-resource"'
|
||||
)
|
||||
})
|
||||
if request.url.path == "/.well-known/oauth-protected-resource":
|
||||
if discovery_unavailable:
|
||||
discovery_unavailable = False
|
||||
raise httpx.ConnectError("temporary discovery outage", request=request)
|
||||
return httpx.Response(200, json={
|
||||
"resource": server_url,
|
||||
"authorization_servers": ["https://auth.example.com"],
|
||||
})
|
||||
if request.url.path == "/.well-known/oauth-authorization-server":
|
||||
return httpx.Response(200, json=_oauth_metadata().model_dump(mode="json"))
|
||||
if request.url.path == "/oauth/token":
|
||||
refresh_urls.append(str(request.url))
|
||||
return httpx.Response(200, json={
|
||||
"access_token": "fresh-access",
|
||||
"refresh_token": "rotated-refresh",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
})
|
||||
return httpx.Response(404)
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(respond), auth=auth) as client:
|
||||
if recovery != "immediate":
|
||||
with pytest.raises(httpx.ConnectError, match="temporary discovery outage"):
|
||||
await client.get(server_url)
|
||||
snapshot = await storage.get_snapshot()
|
||||
assert snapshot.tokens is not None
|
||||
assert snapshot.tokens.refresh_token == "refresh-token"
|
||||
assert snapshot.token_issuer == "https://auth.example.com"
|
||||
assert snapshot.oauth_metadata is None
|
||||
assert snapshot.expires_at is not None
|
||||
if recovery == "restart":
|
||||
client.auth = await create_mcp_oauth_auth("linear", server_url)
|
||||
response = await client.get(server_url)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert refresh_urls == [
|
||||
"https://auth.example.com/old/token",
|
||||
"https://auth.example.com/oauth/token",
|
||||
]
|
||||
reloaded = await MCPOAuthStorage("linear", server_url).get_snapshot()
|
||||
assert reloaded.oauth_metadata == _oauth_metadata()
|
||||
assert reloaded.tokens is not None
|
||||
assert reloaded.tokens.refresh_token == "rotated-refresh"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("error", "clears_client"),
|
||||
[("invalid_grant", False), ("invalid_client", True)],
|
||||
)
|
||||
async def test_unrecoverable_refresh_error_requires_authorization(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
error: str,
|
||||
clears_client: bool,
|
||||
) -> None:
|
||||
_use_data_dir(tmp_path, monkeypatch)
|
||||
server_url = "https://mcp.example.com/mcp"
|
||||
storage = MCPOAuthStorage("linear", server_url)
|
||||
await storage.set_oauth_metadata(_oauth_metadata())
|
||||
await storage.set_tokens(OAuthToken(
|
||||
access_token="expired-access",
|
||||
refresh_token="rejected-refresh",
|
||||
expires_in=-1,
|
||||
))
|
||||
await storage.set_client_info(OAuthClientInformationFull(
|
||||
redirect_uris=["https://agent.example/auth/mcp/callback"],
|
||||
client_id="registered-client",
|
||||
))
|
||||
auth = await create_mcp_oauth_auth("linear", server_url)
|
||||
|
||||
async def respond(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(400, json={"error": error})
|
||||
if str(request.url) == server_url:
|
||||
return httpx.Response(401, headers={
|
||||
"WWW-Authenticate": (
|
||||
'Bearer resource_metadata="https://mcp.example.com/'
|
||||
'.well-known/oauth-protected-resource"'
|
||||
)
|
||||
})
|
||||
if request.url.path == "/.well-known/oauth-protected-resource":
|
||||
return httpx.Response(200, json={
|
||||
"resource": server_url,
|
||||
"authorization_servers": ["https://auth.example.com"],
|
||||
})
|
||||
if request.url.path == "/.well-known/oauth-authorization-server":
|
||||
return httpx.Response(200, json=_oauth_metadata().model_dump(mode="json"))
|
||||
if request.url.path == "/register":
|
||||
return httpx.Response(201, json={
|
||||
"client_id": "replacement-client",
|
||||
"redirect_uris": ["http://127.0.0.1/auth/mcp/callback"],
|
||||
"token_endpoint_auth_method": "none",
|
||||
})
|
||||
return httpx.Response(404)
|
||||
|
||||
with pytest.raises(MCPAuthorizationRequiredError):
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.MockTransport(respond),
|
||||
auth=auth,
|
||||
) as client:
|
||||
await client.get(server_url)
|
||||
|
||||
reloaded = MCPOAuthStorage("linear", server_url)
|
||||
assert await reloaded.get_tokens() is None
|
||||
client_info = await reloaded.get_client_info()
|
||||
assert client_info is not None
|
||||
assert client_info.client_id == (
|
||||
"replacement-client" if clears_client else "registered-client"
|
||||
)
|
||||
lock = storage.refresh_lock()
|
||||
await asyncio.wait_for(lock.acquire(), timeout=1)
|
||||
await lock.release()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_expired_requests_share_one_refresh(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
_use_data_dir(tmp_path, monkeypatch)
|
||||
server_url = "https://mcp.example.com/mcp"
|
||||
storage = MCPOAuthStorage("linear", server_url)
|
||||
await storage.set_oauth_metadata(_oauth_metadata())
|
||||
await storage.set_tokens(OAuthToken(
|
||||
access_token="expired-access",
|
||||
refresh_token="refresh-token",
|
||||
expires_in=-1,
|
||||
))
|
||||
await storage.set_client_info(OAuthClientInformationFull(
|
||||
redirect_uris=["https://agent.example/auth/mcp/callback"],
|
||||
client_id="registered-client",
|
||||
))
|
||||
auth = await create_mcp_oauth_auth("linear", server_url)
|
||||
refresh_requests = 0
|
||||
|
||||
async def respond(request: httpx.Request) -> httpx.Response:
|
||||
nonlocal refresh_requests
|
||||
if request.url.path == "/oauth/token":
|
||||
refresh_requests += 1
|
||||
await asyncio.sleep(0.01)
|
||||
return httpx.Response(200, json={
|
||||
"access_token": "fresh-access",
|
||||
"refresh_token": "rotated-refresh",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
})
|
||||
assert request.headers["Authorization"] == "Bearer fresh-access"
|
||||
return httpx.Response(200, json={"ok": True})
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(respond), auth=auth) as client:
|
||||
responses = await asyncio.gather(client.get(server_url), client.get(server_url))
|
||||
|
||||
assert [response.status_code for response in responses] == [200, 200]
|
||||
assert refresh_requests == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_separate_providers_share_storage_refresh_lock(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
_use_data_dir(tmp_path, monkeypatch)
|
||||
server_url = "https://mcp.example.com/mcp"
|
||||
storage = MCPOAuthStorage("linear", server_url)
|
||||
await storage.set_oauth_metadata(_oauth_metadata())
|
||||
await storage.set_tokens(OAuthToken(
|
||||
access_token="expired-access",
|
||||
refresh_token="refresh-token",
|
||||
expires_in=-1,
|
||||
))
|
||||
await storage.set_client_info(OAuthClientInformationFull(
|
||||
redirect_uris=["https://agent.example/auth/mcp/callback"],
|
||||
client_id="registered-client",
|
||||
))
|
||||
first_auth = await create_mcp_oauth_auth("linear", server_url)
|
||||
second_auth = await create_mcp_oauth_auth("linear", server_url)
|
||||
refresh_requests = 0
|
||||
|
||||
async def respond(request: httpx.Request) -> httpx.Response:
|
||||
nonlocal refresh_requests
|
||||
if request.url.path == "/oauth/token":
|
||||
refresh_requests += 1
|
||||
await asyncio.sleep(0.05)
|
||||
return httpx.Response(200, json={
|
||||
"access_token": "fresh-access",
|
||||
"refresh_token": "rotated-refresh",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
})
|
||||
assert request.headers["Authorization"] == "Bearer fresh-access"
|
||||
return httpx.Response(200, json={"ok": True})
|
||||
|
||||
transport = httpx.MockTransport(respond)
|
||||
async with (
|
||||
httpx.AsyncClient(transport=transport, auth=first_auth) as first_client,
|
||||
httpx.AsyncClient(transport=transport, auth=second_auth) as second_client,
|
||||
):
|
||||
responses = await asyncio.gather(
|
||||
first_client.get(server_url),
|
||||
second_client.get(server_url),
|
||||
)
|
||||
|
||||
assert [response.status_code for response in responses] == [200, 200]
|
||||
assert refresh_requests == 1
|
||||
stored = await MCPOAuthStorage("linear", server_url).get_tokens()
|
||||
assert stored is not None
|
||||
assert stored.refresh_token == "rotated-refresh"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_official_mcp_sdk_completes_discovery_registration_and_token_exchange(
|
||||
tmp_path,
|
||||
@@ -319,7 +829,9 @@ async def test_official_mcp_sdk_completes_discovery_registration_and_token_excha
|
||||
)
|
||||
assert ("POST", "https://auth.example.com/register") in requests
|
||||
assert ("POST", "https://auth.example.com/token") in requests
|
||||
stored = await MCPOAuthStorage("company-mcp", server_url).get_tokens()
|
||||
assert stored is not None
|
||||
assert stored.access_token == "access-token"
|
||||
assert stored.refresh_token == "refresh-token"
|
||||
snapshot = await MCPOAuthStorage("company-mcp", server_url).get_snapshot()
|
||||
assert snapshot.tokens is not None
|
||||
assert snapshot.tokens.access_token == "access-token"
|
||||
assert snapshot.tokens.refresh_token == "refresh-token"
|
||||
assert snapshot.token_issuer == "https://auth.example.com"
|
||||
assert snapshot.oauth_issuer == "https://auth.example.com"
|
||||
@@ -21,6 +21,18 @@ class _Connection:
|
||||
self.closed = True
|
||||
|
||||
|
||||
class _BlockingConnection:
|
||||
def __init__(self) -> None:
|
||||
self.close_started = asyncio.Event()
|
||||
self.allow_close = asyncio.Event()
|
||||
self.closed = False
|
||||
|
||||
async def aclose(self) -> None:
|
||||
self.close_started.set()
|
||||
await self.allow_close.wait()
|
||||
self.closed = True
|
||||
|
||||
|
||||
def _config() -> MCPServerConfig:
|
||||
return MCPServerConfig(
|
||||
type="streamableHttp",
|
||||
@@ -107,6 +119,62 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_
|
||||
assert connection.closed is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_browser_flow_activates_tools_before_probe_cleanup_completes(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = McpOAuthManager()
|
||||
connection = _BlockingConnection()
|
||||
reload_started = asyncio.Event()
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.mcp_oauth_api.validate_url_target",
|
||||
lambda _url: (True, ""),
|
||||
)
|
||||
|
||||
async def connect(_servers, _registry, *, oauth_handlers):
|
||||
handlers = oauth_handlers["linear"]
|
||||
await handlers.redirect_handler(
|
||||
"https://accounts.example.com/authorize?client_id=test&state=blocked-close"
|
||||
)
|
||||
await handlers.callback_handler()
|
||||
return {"linear": connection}
|
||||
|
||||
async def reload_mcp() -> dict[str, object]:
|
||||
reload_started.set()
|
||||
return {
|
||||
"ok": True,
|
||||
"requires_restart": False,
|
||||
"connected": ["linear"],
|
||||
"failed": [],
|
||||
}
|
||||
|
||||
monkeypatch.setattr("nanobot.webui.mcp_oauth_api.connect_mcp_servers", connect)
|
||||
|
||||
started = await manager.start(
|
||||
"linear",
|
||||
_config(),
|
||||
"https://agent.example.com/auth/mcp/callback",
|
||||
reload_mcp=reload_mcp,
|
||||
)
|
||||
manager.submit_callback(state="blocked-close", code="oauth-code", error=None)
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(reload_started.wait(), timeout=0.5)
|
||||
await asyncio.wait_for(connection.close_started.wait(), timeout=0.5)
|
||||
result = await manager.status(started["flow_id"])
|
||||
assert result["status"] == "connected"
|
||||
assert connection.closed is False
|
||||
finally:
|
||||
connection.allow_close.set()
|
||||
|
||||
for _ in range(10):
|
||||
await asyncio.sleep(0)
|
||||
if connection.closed:
|
||||
break
|
||||
assert connection.closed is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_remote_http_flow_accepts_a_pasted_loopback_callback(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
|
||||
@@ -184,6 +184,17 @@ async def test_oauth_preset_is_one_click_configured_after_token_storage(
|
||||
row = next(item for item in healthy["presets"] if item["name"] == "xmind")
|
||||
assert row["runtime_status"] == "connected"
|
||||
|
||||
await MCPOAuthStorage("xmind", cfg.url).clear_tokens()
|
||||
refresh_failed = mcp_presets_payload(runtime_status={"xmind": "failed"})
|
||||
row = next(item for item in refresh_failed["presets"] if item["name"] == "xmind")
|
||||
assert row["configured"] is False
|
||||
assert row["status"] == "authorization_required"
|
||||
assert row["runtime_status"] == "failed"
|
||||
|
||||
stale_connected = mcp_presets_payload(runtime_status={"xmind": "connected"})
|
||||
row = next(item for item in stale_connected["presets"] if item["name"] == "xmind")
|
||||
assert "runtime_status" not in row
|
||||
|
||||
mcp_presets_action("remove", {"name": ["xmind"]})
|
||||
assert await MCPOAuthStorage("xmind", cfg.url).get_tokens() is None
|
||||
|
||||
|
||||
@@ -545,7 +545,7 @@ function McpAppsCatalogRow({
|
||||
const readyInstalled = preset.enabled ?? configuredInstalled;
|
||||
const runtimeConnected = !toggleable && preset.runtime_status === "connected";
|
||||
const runtimeConnecting = !toggleable && preset.runtime_status === "connecting";
|
||||
const runtimeFailed = !toggleable && preset.runtime_status === "failed";
|
||||
const runtimeFailed = !toggleable && preset.installed && preset.runtime_status === "failed";
|
||||
const statusLabel = toggleable
|
||||
? tx("settings.nanobotFeatures.enabled", "Enabled")
|
||||
: runtimeConnected
|
||||
@@ -601,14 +601,14 @@ function McpAppsCatalogRow({
|
||||
<p
|
||||
className={cn(
|
||||
"mt-0.5 flex min-w-0 items-center gap-1.5 text-[12.5px] leading-5 text-muted-foreground",
|
||||
runtimeFailed && configuredInstalled && "font-medium text-destructive",
|
||||
runtimeFailed && "font-medium text-destructive",
|
||||
)}
|
||||
>
|
||||
{runtimeFailed && configuredInstalled ? (
|
||||
{runtimeFailed ? (
|
||||
<TriangleAlert className="h-3.5 w-3.5 shrink-0" aria-hidden />
|
||||
) : null}
|
||||
<span className="truncate">
|
||||
{runtimeFailed && configuredInstalled ? failureLabel : detail}
|
||||
{runtimeFailed ? failureLabel : detail}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
@@ -647,7 +647,7 @@ function McpAppsCatalogRow({
|
||||
<Trash2 className="h-4 w-4" aria-hidden />
|
||||
</AppsActionButton>
|
||||
</>
|
||||
) : runtimeFailed && configuredInstalled ? (
|
||||
) : runtimeFailed ? (
|
||||
<AppsActionButton
|
||||
ariaLabel={t("settings.mcp.manageTitle", {
|
||||
name: preset.display_name,
|
||||
@@ -857,7 +857,7 @@ function McpAppsCatalogRow({
|
||||
preset={preset}
|
||||
values={values}
|
||||
actionKey={actionKey}
|
||||
statusLabel={runtimeFailed && configuredInstalled ? failureStatusLabel : statusLabel}
|
||||
statusLabel={runtimeFailed ? failureStatusLabel : statusLabel}
|
||||
statusTone={runtimeFailed ? "warning" : configuredInstalled ? "success" : "neutral"}
|
||||
tab={managementTab}
|
||||
icon={<McpPresetLogo preset={preset} showBrandLogos={showBrandLogos} compact />}
|
||||
|
||||
@@ -200,6 +200,40 @@ describe("SettingsView Apps catalog", () => {
|
||||
await act(() => i18n.changeLanguage("en"));
|
||||
});
|
||||
|
||||
it("keeps an OAuth runtime failure visible after credentials are cleared", async () => {
|
||||
const failedPreset = {
|
||||
...xmindMcpPreset,
|
||||
installed: true,
|
||||
configured: false,
|
||||
available: false,
|
||||
status: "authorization_required",
|
||||
runtime_status: "failed",
|
||||
connection_summary: "https://app.xmind.com/api/mcp",
|
||||
};
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url === "/api/settings") return jsonResponse(settingsPayload());
|
||||
if (url === "/api/settings/cli-apps") {
|
||||
return jsonResponse({ apps: [], installed_count: 0 });
|
||||
}
|
||||
if (url === "/api/settings/mcp-presets") {
|
||||
return jsonResponse({ presets: [failedPreset], installed_count: 1 });
|
||||
}
|
||||
return { ok: false, status: 404, text: async () => "Not found" } as Response;
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
renderSettingsView({ initialSection: "apps" });
|
||||
fireEvent.click(await screen.findByRole("button", { name: "MCP" }));
|
||||
|
||||
const heading = await screen.findByRole("heading", { name: "Xmind" });
|
||||
const row = heading.closest("article");
|
||||
expect(row).not.toBeNull();
|
||||
expect(within(row as HTMLElement).getByText("Connection failed.")).toBeInTheDocument();
|
||||
expect(within(row as HTMLElement).getByRole("button", { name: "Manage Xmind" }))
|
||||
.toHaveTextContent("Fix connection");
|
||||
});
|
||||
|
||||
it("refreshes a connecting MCP snapshot until the runtime attempt settles", async () => {
|
||||
const connectingPreset = {
|
||||
...xmindMcpPreset,
|
||||
|
||||
Reference in new issue
Block a user