mcp_oauth_provider.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. """Shared ``OAuthClientProvider`` customizations for Hermes MCP OAuth.
  2. Two code paths build an SDK provider — ``tools.mcp_oauth.build_oauth_auth`` (legacy public
  3. API) and ``tools.mcp_oauth_manager.MCPOAuthManager`` — and both need the same real-world
  4. fixes and config → constructor-kwargs plumbing. This module holds that core once; the origin
  5. modules keep their own subclass (logger name, disk-watch hooks) on top of it.
  6. """
  7. from __future__ import annotations
  8. import logging
  9. import re
  10. from typing import TYPE_CHECKING, Any
  11. from urllib.parse import urlsplit
  12. if TYPE_CHECKING:
  13. from tools.mcp_oauth import HermesTokenStorage
  14. logger = logging.getLogger(__name__)
  15. # Authorization servers that advertise ``authorization_response_iss_parameter_supported`` and then
  16. # omit ``iss`` from the redirect (#111135). Exact issuer match, nothing else is relaxed.
  17. _ISS_OMITTING_ISSUERS = frozenset({"https://api.figma.com"})
  18. # Authorization-server metadata documents the SDK tries in its 401 branch (RFC 8414 / OIDC discovery).
  19. _ASM_DISCOVERY_PATHS = ("/.well-known/oauth-authorization-server", "/.well-known/openid-configuration")
  20. _DISCOVERY_CONTEXT_LEAD = "Could not read authorization-server metadata"
  21. def _default_auth_request_user_agent() -> str:
  22. """``Hermes-Agent/<version>`` for SDK-built OAuth requests that would otherwise carry no User-Agent at
  23. all; versioned so an operator debugging a WAF block can tell which client they are looking at."""
  24. from hermes_cli.version_info import get_version_info
  25. return f"Hermes-Agent/{get_version_info().base_version}"
  26. DEFAULT_AUTH_REQUEST_USER_AGENT = _default_auth_request_user_agent()
  27. def stamp_default_user_agent(request):
  28. """Give an SDK-built OAuth request (discovery, registration, token) a User-Agent if it has none.
  29. The SDK builds those as bare ``httpx.Request`` objects and sends them through ``client.send()``,
  30. which never merges the client's default headers, so they leave with NO ``User-Agent`` at all.
  31. WAF-fronted authorization servers (www.tradingview.com, coda.io) answer 403 to header-less
  32. requests while curl and a plain ``client.get()`` get 200 — the metadata document is then "not
  33. found", the SDK falls back to guessing ``/register`` and ``/authorize`` on the MCP host, and the
  34. user sees ``Registration failed: 404`` (#113771). Only an absent header is filled, so a
  35. configured ``oauth.user_agent`` (token requests) still wins."""
  36. if "user-agent" not in request.headers:
  37. request.headers["User-Agent"] = DEFAULT_AUTH_REQUEST_USER_AGENT
  38. return request
  39. def _asm_discovery_failure(response) -> str | None:
  40. """``"<status> from <url>"`` when *response* is a failed authorization-server metadata fetch."""
  41. req = getattr(response, "request", None)
  42. status = getattr(response, "status_code", None)
  43. if req is None or status is None or 200 <= status < 300:
  44. return None
  45. url = str(req.url)
  46. return f"{status} from {url}" if any(p in url for p in _ASM_DISCOVERY_PATHS) else None
  47. def _with_discovery_context(exc: Exception, failures: list[str]):
  48. """Re-shape a registration error raised after every metadata fetch failed: lead with the discovery
  49. failure, since the 404 on the guessed ``/register`` URL is only its consequence (#113771)."""
  50. return type(exc)(f"{_DISCOVERY_CONTEXT_LEAD} ({'; '.join(failures)}); dynamic client registration "
  51. f"then fell back to a guessed endpoint on the MCP host and failed: {exc}")
  52. class _RefreshCompletedByPeer(Exception):
  53. """Restart the SDK auth flow: a peer rotated the grant we were about to present."""
  54. class HermesProviderMixin:
  55. """Token-endpoint fixes layered over the SDK's ``OAuthClientProvider`` (must precede it in
  56. the MRO; subclasses set ``_hermes_logger`` to keep their own logger name).
  57. - Supabase-style dynamic registration returns a ``client_secret`` but omits
  58. ``token_endpoint_auth_method``; the SDK then treats the client as public and the token
  59. endpoint rejects the exchange (looping the browser page) — coerce ``client_secret_post``.
  60. - ``token_user_agent`` (``oauth.user_agent``) is stamped onto token-endpoint requests only
  61. (some authorization servers/WAFs reject httpx's default); unset falls back to the shared
  62. ``Hermes-Agent/<version>`` default, since a header-less token POST is 403'd by WAF-fronted
  63. authorization servers (#115329).
  64. - Any 2xx token/refresh response is accepted; token bodies never leak into errors/logs."""
  65. _hermes_logger: logging.Logger = logger
  66. def __init__(self, *args: Any, token_user_agent: str | None = None, oauth_flow: str = "browser", **kwargs: Any):
  67. super().__init__(*args, **kwargs)
  68. self._hermes_oauth_flow = oauth_flow
  69. # oauth.user_agent — stamped onto token-endpoint requests only; some authorization servers/WAFs
  70. # reject httpx's default (#75576).
  71. self._hermes_token_user_agent = token_user_agent
  72. async def _perform_authorization(self):
  73. info = self.context.client_info
  74. grants = getattr(info, "grant_types", None) or []
  75. if (getattr(self, "_hermes_oauth_flow", "browser") == "device"
  76. or ("urn:ietf:params:oauth:grant-type:device_code" in grants and "authorization_code" not in grants)):
  77. from tools.mcp_oauth import OAuthNonInteractiveError
  78. raise OAuthNonInteractiveError(
  79. "MCP device authorization requires `hermes mcp login <server> --flow device`; "
  80. "background reconnects cannot start a device login")
  81. self._tolerate_missing_iss_for_known_server()
  82. self._request_google_offline_access()
  83. return await super()._perform_authorization()
  84. def _tolerate_missing_iss_for_known_server(self) -> None:
  85. """Figma advertises ``authorization_response_iss_parameter_supported`` and then omits ``iss``
  86. from the redirect, so the SDK's RFC 9207 check rejects every valid code (#111135). For that
  87. one issuer only, fill a missing ``iss`` with the discovered issuer and warn; a present-but-
  88. different ``iss`` still fails the SDK check, and every other server keeps the strict rule."""
  89. issuer = _metadata_issuer(self.context)
  90. if issuer not in _ISS_OMITTING_ISSUERS:
  91. return
  92. inner = self.context.callback_handler
  93. async def _fill_iss():
  94. result = await inner()
  95. if getattr(result, "iss", None) is None and getattr(result, "code", None):
  96. self._hermes_logger.warning(
  97. "MCP OAuth: %s omitted the iss parameter it advertises; accepting the redirect for that issuer only", issuer)
  98. result = result.model_copy(update={"iss": str(self.context.oauth_metadata.issuer)})
  99. return result
  100. self.context.callback_handler = _fill_iss
  101. def _request_google_offline_access(self) -> None:
  102. """Wrap the redirect handler so Google's authorization URL asks for a refresh token (#117510).
  103. ``access_type=offline`` is what makes Google issue one at all, and ``prompt=consent`` is what
  104. makes it re-issue one on repeat logins (the first consent already spent the grant); MCP
  105. discovery advertises neither. The SDK builds the URL itself, so the two parameters are
  106. appended here — never overwriting values already present in the query. Wraps once: every
  107. authorization runs through here, and the wrapper reads the issuer at call time."""
  108. inner = self.context.redirect_handler
  109. if inner is None or getattr(inner, "_hermes_offline_access", False):
  110. return
  111. from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
  112. async def _with_offline_access(authorization_url: str) -> None:
  113. params = google_offline_access_params(self.context)
  114. if not params:
  115. await inner(authorization_url)
  116. return
  117. parts = urlsplit(authorization_url)
  118. query = dict(parse_qsl(parts.query, keep_blank_values=True))
  119. query.update(params)
  120. query.setdefault("prompt", "consent")
  121. await inner(urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(query), parts.fragment)))
  122. _with_offline_access._hermes_offline_access = True # type: ignore[attr-defined]
  123. self.context.redirect_handler = _with_offline_access
  124. async def _hermes_accept_origin_issued_metadata(self, response):
  125. """Accept an authorization server's metadata document whose ``issuer`` differs from the advertised
  126. identifier only in a shape the SDK's exact-string check (RFC 8414 §3.3) refuses: a path-scoped
  127. server naming its origin (see ``metadata_issued_by_origin``, Strava #116233), or a root issuer
  128. spelled with the trailing slash on one side only (Otter.ai advertises ``https://otter.ai/`` and its
  129. document names ``https://otter.ai``, #132233), which the SDK's own ``issuers_match`` treats as
  130. one server but applies only on the legacy no-PRM path.
  131. The SDK validates inside its Step 2 loop right after reading the response, so the document is
  132. installed on the context here and the SDK is handed an empty 204: ``handle_auth_metadata_response``
  133. reads that as "stop trying", leaving the installed document in place. ``auth_server_url`` is left
  134. untouched, so the SEP-2352 credential binding still uses the advertised identifier (stable across
  135. runs), while the RFC 9207 ``iss`` check and Hermes' refresh-token binding use the document's issuer.
  136. Every other response goes back to the SDK unchanged, including its issuer check."""
  137. # This compatibility shim is only for authorization-server metadata
  138. # responses. Never consume arbitrary 200 responses here: MCP resource
  139. # responses may be long-lived SSE streams (for example GET /v2/mcp),
  140. # and response.aread() would wait for that stream to end while holding
  141. # the OAuth state semaphore.
  142. req = getattr(response, "request", None)
  143. request_path = urlsplit(str(req.url)).path if req is not None else ""
  144. if not any(request_path == base or request_path.startswith(f"{base}/")
  145. for base in _ASM_DISCOVERY_PATHS):
  146. return response
  147. from mcp.shared.auth import OAuthMetadata
  148. from pydantic import ValidationError
  149. try:
  150. metadata = OAuthMetadata.model_validate_json(await response.aread())
  151. except ValidationError:
  152. return response
  153. from mcp.client.auth.utils import issuers_match
  154. advertised, issuer = self.context.auth_server_url, str(metadata.issuer)
  155. if metadata_issued_by_origin(metadata, advertised, response):
  156. relation = "is the origin of"
  157. elif advertised and issuer != advertised and issuers_match(issuer, advertised):
  158. relation = "differs only by the root trailing slash from"
  159. else:
  160. return response
  161. self._hermes_logger.info("MCP OAuth: accepting authorization-server metadata from %s whose issuer %s %s "
  162. "the advertised server %s", response.url, issuer, relation, advertised)
  163. self.context.oauth_metadata = metadata
  164. return type(response)(204, request=response.request)
  165. def _prepare_token_request(self, request):
  166. """Stamp a token/refresh request's User-Agent: the configured ``oauth.user_agent`` when set,
  167. else the shared ``Hermes-Agent/<version>`` default. These requests are built by hand — the
  168. SDK's ``_exchange_token_authorization_code``/``_refresh_token`` and ``tools.mcp_oauth_device``
  169. — and travel through ``client.send()``, which never merges the client's default headers, so
  170. without a stamp the POST leaves with NO ``User-Agent`` at all and a WAF-fronted authorization
  171. server answers 403 (#115329)."""
  172. ua = getattr(self, "_hermes_token_user_agent", None) # tests build via __new__
  173. if ua:
  174. request.headers["User-Agent"] = ua
  175. return stamp_default_user_agent(request)
  176. def _coerce_client_secret_post(self) -> None:
  177. """Same rule as ``HermesTokenStorage._coerce_secret_auth_method``, applied to the
  178. in-memory client info BEFORE the SDK builds a token-endpoint request from it."""
  179. info = self.context.client_info
  180. if not info:
  181. return
  182. from mcp.shared.auth import OAuthClientInformationFull
  183. from tools.mcp_oauth import HermesTokenStorage
  184. data = info.model_dump(mode="json", exclude_none=True)
  185. if HermesTokenStorage._coerce_secret_auth_method(data):
  186. self.context.client_info = OAuthClientInformationFull.model_validate(data)
  187. async def _exchange_token_authorization_code(self, *args: Any, **kwargs: Any):
  188. self._coerce_client_secret_post()
  189. return self._prepare_token_request(await super()._exchange_token_authorization_code(*args, **kwargs))
  190. # Locked descriptor while this provider owns the refresh fence; cleared by
  191. # _hermes_release_refresh_fence. Never shared across instances.
  192. _hermes_fence: int | None = None
  193. async def async_auth_flow(self, request):
  194. """Guarantee fence release even if the auth generator is abandoned.
  195. The SDK drives the refresh as a generator: ``_refresh_token`` yields a
  196. request and ``_handle_refresh_response`` consumes the response. If the
  197. caller cancels in between (timeout, task cancellation, transport
  198. teardown), GeneratorExit/CancelledError is raised at the yield and
  199. ``_handle_refresh_response`` never runs. Without this wrapper the fence
  200. file would stay locked for the life of the process and every later
  201. refresh would fail closed -- trading a race for a deadlock.
  202. When a peer already rotated the grant while we waited for the fence,
  203. ``_refresh_token`` adopts it and raises ``_RefreshCompletedByPeer``;
  204. the SDK flow is then restarted so it re-evaluates validity and sends
  205. the original request with the winner's access token, never POSTing
  206. the burned refresh token.
  207. """
  208. while True:
  209. inner = super().async_auth_flow(request)
  210. discovery_failures: list[str] = []
  211. try:
  212. sent, thrown = None, None
  213. while True:
  214. try:
  215. if thrown is not None:
  216. exc, thrown = thrown, None
  217. out = await inner.athrow(exc)
  218. else:
  219. out = await inner.asend(sent)
  220. except StopAsyncIteration:
  221. return
  222. except _RefreshCompletedByPeer:
  223. break
  224. except Exception as exc:
  225. from mcp.client.auth.oauth2 import OAuthRegistrationError
  226. if (isinstance(exc, OAuthRegistrationError) and discovery_failures
  227. and self.context.oauth_metadata is None):
  228. raise _with_discovery_context(exc, discovery_failures) from exc
  229. raise
  230. if out is not request:
  231. stamp_default_user_agent(out)
  232. # Full bidirectional delegation: the SDK drives this flow with
  233. # asend(response), so `async for` would swallow the response and
  234. # feed the inner generator None. Async generators have no
  235. # `yield from`, hence the manual pump.
  236. try:
  237. sent = yield out
  238. except GeneratorExit:
  239. await inner.aclose()
  240. raise
  241. except BaseException as exc:
  242. sent, thrown = None, exc
  243. else:
  244. failure = _asm_discovery_failure(sent)
  245. if failure:
  246. discovery_failures.append(failure)
  247. elif getattr(sent, "status_code", None) == 200:
  248. sent = await self._hermes_accept_origin_issued_metadata(sent)
  249. finally:
  250. await self._hermes_release_refresh_fence()
  251. async def _refresh_token(self):
  252. """Take the refresh fence, then build the request from the token we own.
  253. The fence is acquired BEFORE the final read of the refresh token and is
  254. released only after _handle_refresh_response has persisted the
  255. replacement, so one refresh generation is consumed by exactly one
  256. process. See tools.mcp_oauth.acquire_refresh_fence for the interleaving this
  257. closes.
  258. Holding a lock across ``yield`` in the SDK's generator-based auth flow
  259. is safe here because the SDK already serializes the whole flow under
  260. ``self.context.lock``: the generator is always driven to completion (or
  261. aborted) by one task, and async_auth_flow cannot interleave two
  262. refreshes inside one process.
  263. """
  264. self._coerce_client_secret_post()
  265. await self._hermes_acquire_refresh_fence()
  266. try:
  267. # Re-read under the fence: a peer may have rotated while we waited
  268. # for it, in which case the token we were about to POST is dead.
  269. # If disk already holds a different refresh token, the peer that held
  270. # the fence before us won this generation; its value is the only one
  271. # the provider will still accept, so install it even when its access
  272. # token has already expired (the POST we build needs the new grant).
  273. candidate = await self._hermes_rotated_candidate()
  274. if candidate is not None:
  275. if not self._hermes_install_disk_pair(candidate):
  276. # Issuer binding stripped the peer's refresh token: nothing
  277. # left to POST. Restart the flow so the SDK lands in 401 ->
  278. # full authorization instead of raising over a dead grant.
  279. raise _RefreshCompletedByPeer
  280. if self._hermes_live_ttl() and self.context.is_token_valid():
  281. # The peer's access token is live: presenting our copy of the
  282. # refresh token would only burn a generation on a single-use
  283. # provider. Skip the POST and let the flow restart.
  284. raise _RefreshCompletedByPeer
  285. return self._prepare_token_request(await super()._refresh_token())
  286. except BaseException:
  287. # Never hold the fence when no POST will follow.
  288. await self._hermes_release_refresh_fence()
  289. raise
  290. def _hermes_live_ttl(self) -> bool:
  291. """True when the installed token is not known to be past due.
  292. Storage clamps a past-due token to ``expires_in == 0`` on read (see
  293. HermesTokenStorage.get_tokens); the SDK's is_token_valid() compares
  294. ``time.time() <= expiry`` and still reports True for that boundary,
  295. which would make us adopt a token the server rejects immediately.
  296. ``expires_in`` is optional in RFC 6749: None means no expiry was
  297. issued, which the SDK treats as valid, so it counts as live here too.
  298. """
  299. if self.context.current_tokens is None:
  300. return False
  301. exp = getattr(self.context.current_tokens, "expires_in", None)
  302. return exp is None or int(exp) > 0
  303. async def _hermes_acquire_refresh_fence(self) -> None:
  304. """Enter the fence, or let RefreshFenceTimeout abort this attempt.
  305. Fails closed on purpose: a refresh we are not certain we own must not
  306. be POSTed. A stale fence from an aborted attempt is replaced rather
  307. than stacked, so a crashed generator cannot leak ownership.
  308. """
  309. from tools.mcp_oauth import acquire_refresh_fence
  310. await self._hermes_release_refresh_fence()
  311. storage = self.context.storage
  312. tokens_path = getattr(storage, "_tokens_path", None)
  313. if tokens_path is None: # pragma: no cover - non-Hermes storage
  314. return
  315. self._hermes_fence = await acquire_refresh_fence(tokens_path())
  316. async def _hermes_release_refresh_fence(self) -> None:
  317. """Release the fence if held. Idempotent and never raises."""
  318. from tools.mcp_oauth import release_refresh_fence
  319. fd, self._hermes_fence = self._hermes_fence, None
  320. if fd is not None:
  321. release_refresh_fence(fd)
  322. async def _hermes_rotated_candidate(self):
  323. """The on-disk pair, if a peer rotated it past the one we hold.
  324. A candidate must carry a refresh token different from ours (same
  325. token: disk has nothing newer) and a non-empty access token. A disk
  326. entry with no refresh token is never adopted: its access token may
  327. still be inside its TTL, but taking it trades an explicit reauth now
  328. for a silent one at expiry with no way to refresh in between.
  329. ``get_tokens`` already returns None for absent or corrupt files.
  330. """
  331. stored = await self.context.storage.get_tokens()
  332. if stored is None:
  333. return None
  334. current = self.context.current_tokens
  335. stored_refresh = getattr(stored, "refresh_token", None)
  336. if not stored_refresh or not getattr(stored, "access_token", None):
  337. return None
  338. if stored_refresh == getattr(current, "refresh_token", None):
  339. return None
  340. return stored
  341. def _hermes_install_disk_pair(self, tokens) -> bool:
  342. """Publish a disk pair to the context and re-run issuer binding on it.
  343. Returns False when the enforcer strips the refresh token (the pair was
  344. minted by a different issuer): there is nothing left to refresh with,
  345. and each caller decides what that means for its own flow.
  346. """
  347. self.context.current_tokens = tokens
  348. self.context.update_token_expiry(tokens)
  349. enforce_refresh_token_issuer(self.context)
  350. return bool(getattr(self.context.current_tokens, "refresh_token", None))
  351. async def _initialize(self) -> None:
  352. """Load stored state, restore persisted server metadata when the SDK has none (so the issuer
  353. check and any refresh see the discovered ``issuer``/``token_endpoint`` instead of SDK guesses),
  354. then enforce refresh-token issuer binding."""
  355. await super()._initialize()
  356. storage = self.context.storage
  357. from tools.mcp_oauth import HermesTokenStorage
  358. if isinstance(storage, HermesTokenStorage) and self.context.oauth_metadata is None:
  359. meta = storage.load_oauth_metadata()
  360. if meta is not None:
  361. self.context.oauth_metadata = meta
  362. enforce_refresh_token_issuer(self.context)
  363. async def _store_tokens(self, token_response) -> None:
  364. self.context.current_tokens = token_response
  365. self.context.update_token_expiry(token_response)
  366. bind_issuer_from_context(self.context)
  367. await self.context.storage.set_tokens(token_response)
  368. async def _handle_token_response(self, response):
  369. """Accept any 2xx token response; a 2xx body (it carries the tokens) never reaches an error.
  370. A non-2xx body carries no tokens and is the only clue to WHY the exchange failed — a WAF's
  371. HTML "Request blocked" page vs the issuer's ``invalid_grant`` JSON (#115329) — so a short,
  372. tag-stripped, redacted excerpt rides along with the status."""
  373. from mcp.client.auth.oauth2 import OAuthTokenError
  374. if not (200 <= response.status_code < 300):
  375. from tools.mcp_tool_common import _sanitize_error
  376. excerpt = " ".join(re.sub(r"<[^>]+>", " ", response.text).split())[:200]
  377. raise OAuthTokenError(f"Token exchange failed ({response.status_code}): {_sanitize_error(excerpt)}".rstrip(": "))
  378. from httpx import HTTPError
  379. from mcp.client.auth.utils import handle_token_response_scopes
  380. try:
  381. token_response = await handle_token_response_scopes(response)
  382. except (HTTPError, OAuthTokenError):
  383. raise OAuthTokenError("Invalid token response") from None
  384. await self._store_tokens(token_response)
  385. async def _handle_refresh_response(self, response) -> bool:
  386. """Accept any 2xx refresh response; never log the body.
  387. Always releases the refresh fence: this is the single exit point of the
  388. fenced section, whatever the outcome.
  389. """
  390. try:
  391. return await self._hermes_handle_refresh_response(response)
  392. finally:
  393. await self._hermes_release_refresh_fence()
  394. async def _hermes_handle_refresh_response(self, response) -> bool:
  395. if not (200 <= response.status_code < 300):
  396. self._hermes_logger.warning("Token refresh failed: %s", response.status_code)
  397. # A writer outside the fence (interactive `hermes mcp login`, or a
  398. # pre-fence Hermes sharing this HERMES_HOME) may have rotated the
  399. # grant and persisted the replacement. Providers issuing single-use
  400. # refresh tokens reject our stale copy with a 400. Re-read disk
  401. # before destroying the session.
  402. if await self._hermes_reload_tokens_after_refresh_failure():
  403. self._hermes_logger.info(
  404. "Recovered a peer-rotated refresh token instead of clearing the session"
  405. )
  406. return True
  407. self.context.clear_tokens()
  408. return False
  409. from httpx import HTTPError
  410. from mcp.shared.auth import OAuthToken
  411. from pydantic import ValidationError
  412. try:
  413. token_response = OAuthToken.model_validate_json(await response.aread())
  414. except (HTTPError, ValidationError):
  415. self._hermes_logger.warning("Invalid refresh response: %s", response.status_code)
  416. self.context.clear_tokens()
  417. return False
  418. # RFC 6749 §6: a refresh response may omit refresh_token (AS does not rotate) and scope
  419. # (unchanged). The SDK's own _handle_refresh_response carries both forward; this override
  420. # must too, or every non-rotating refresh erases the stored refresh_token and the server
  421. # dies at the NEXT expiry with a forced browser re-auth (#62333).
  422. prior = self.context.current_tokens
  423. if prior is not None:
  424. if token_response.refresh_token is None:
  425. token_response.refresh_token = prior.refresh_token
  426. if token_response.scope is None:
  427. token_response.scope = prior.scope
  428. await self._store_tokens(token_response)
  429. return True
  430. async def _hermes_reload_tokens_after_refresh_failure(self) -> bool:
  431. """Re-read tokens from disk after a rejected refresh.
  432. Returns True only when disk holds a pair that is BOTH different from
  433. the one we just failed with AND still live. That is the signature of
  434. a writer outside the fence (an interactive ``hermes mcp login`` or a
  435. pre-fence Hermes) having rotated the grant between our read and our
  436. POST -- a recoverable race, not a dead credential.
  437. Returns False for the genuinely-expired case (nobody wrote a newer
  438. pair), so the caller still clears state and surfaces the reauth
  439. prompt.
  440. """
  441. candidate = await self._hermes_rotated_candidate()
  442. if candidate is None:
  443. return False
  444. # Publish, then restore on rejection. is_token_valid() reads the
  445. # context rather than taking a token argument, so the candidate has
  446. # to be installed to be tested; a losing probe must leave the context
  447. # exactly as it found it.
  448. previous_tokens = self.context.current_tokens
  449. if (
  450. self._hermes_install_disk_pair(candidate)
  451. and self._hermes_live_ttl()
  452. and self.context.is_token_valid()
  453. ):
  454. return True
  455. self.context.current_tokens = previous_tokens
  456. self.context.update_token_expiry(previous_tokens)
  457. return False
  458. def _metadata_issuer(context: Any) -> str | None:
  459. """Discovered authorization-server issuer from the SDK auth context, without trailing slash."""
  460. meta = getattr(context, "oauth_metadata", None)
  461. issuer = getattr(meta, "issuer", None) if meta is not None else None
  462. return (str(issuer).rstrip("/") or None) if issuer else None
  463. def metadata_issued_by_origin(metadata: Any, auth_server_url: str | None, response: Any) -> bool:
  464. """Whether *metadata* may stand in for the exact-issuer match of RFC 8414 §3.3 because it is the
  465. document of the path-scoped authorization server *auth_server_url* and names that server's origin.
  466. The issuer check stops a party controlling a path or a sibling host from making the client accept
  467. endpoints of a different authorization server (RFC 8414 §3.3, RFC 9728 §3.3). This narrow shape keeps
  468. that boundary: *response* must be the document fetched directly (no redirect) from the RFC 8414 §3.1
  469. well-known URL DERIVED from the advertised identifier, ``<origin>/.well-known/oauth-authorization-server
  470. <path>`` — a location only the origin's operator controls — and its ``issuer`` must be exactly that
  471. origin, i.e. the advertised server is ``issuer + path``. ``response.url`` is the URL the body was
  472. actually read from (the final request after any followed redirect), so a redirected document never
  473. matches. Whoever can publish that document already
  474. controls the origin's well-known tree, so accepting it grants a path-controlling attacker nothing.
  475. Strava's MCP connector publishes exactly this pair (#116233). Anything else (another origin, a
  476. different path, the root or OIDC fallback documents, a redirect target) still goes through the
  477. exact-string check."""
  478. from urllib.parse import urlsplit
  479. if not auth_server_url:
  480. return False
  481. parts = urlsplit(auth_server_url)
  482. path = parts.path.rstrip("/")
  483. if (not path or ".." in path.split("/") or parts.username is not None or parts.query or parts.fragment
  484. or response.status_code != 200):
  485. return False
  486. origin = f"{parts.scheme}://{parts.netloc}"
  487. derived = f"{origin}/.well-known/oauth-authorization-server{path}"
  488. return str(response.url) == derived and str(metadata.issuer).rstrip("/") == origin
  489. def google_offline_access_params(context: Any) -> dict[str, str]:
  490. """Parameters that ask the authorization server for a refresh token Google-style: Google issues
  491. one only when the authorization request carries ``access_type=offline`` — its idiom where OIDC
  492. servers use the ``offline_access`` scope that MCP discovery would advertise — so without the
  493. parameter the grant ends with the short-lived access token and every later reconnect (a gateway
  494. process, cron) fails back to an interactive login it cannot perform (#117510). Empty for every
  495. other issuer, whose requests keep the SDK-built parameters untouched."""
  496. from urllib.parse import urlsplit
  497. issuer = _metadata_issuer(context)
  498. if issuer is None or urlsplit(issuer).netloc != "accounts.google.com":
  499. return {}
  500. return {"access_type": "offline"}
  501. def bind_issuer_from_context(context: Any) -> None:
  502. """Record the discovered issuer so the next ``storage.set_tokens`` (exchange or refresh) carries
  503. it. No-op when metadata is not discovered yet or storage is not Hermes'."""
  504. from tools.mcp_oauth import HermesTokenStorage
  505. storage = getattr(context, "storage", None)
  506. issuer = _metadata_issuer(context)
  507. if isinstance(storage, HermesTokenStorage) and issuer:
  508. storage.bind_issuer(issuer)
  509. def enforce_refresh_token_issuer(context: Any) -> None:
  510. """Refuse to reuse a refresh token minted by a different issuer.
  511. The authorization server discovered for an MCP server can change (DNS takeover, protected-resource
  512. metadata edit, server migration); sending the stored refresh token to the new issuer hands it a
  513. long-lived credential. On mismatch the refresh token is stripped (memory + disk) while an unexpired
  514. access token stays usable; full re-authorization happens at expiry. Token files predating the field
  515. adopt the current issuer once rather than forcing a re-login. Runs after ``_initialize`` restored
  516. tokens + metadata, before the SDK's ``can_refresh_token()`` decision."""
  517. from tools.mcp_oauth import HermesTokenStorage
  518. storage = getattr(context, "storage", None)
  519. tokens = getattr(context, "current_tokens", None)
  520. if not isinstance(storage, HermesTokenStorage) or tokens is None or not getattr(tokens, "refresh_token", None):
  521. return
  522. current = _metadata_issuer(context)
  523. if current is None: # not discovered yet; the SDK's 401-branch discovery + _store_tokens stamp it later
  524. return
  525. stored = (storage.loaded_issuer or "").rstrip("/") or None
  526. if stored is None:
  527. storage.stamp_issuer(current)
  528. return
  529. if stored != current:
  530. logger.warning("MCP OAuth: authorization server issuer changed (%s -> %s); dropping the stored "
  531. "refresh token rather than sending it to a different issuer", stored, current)
  532. storage.strip_refresh_token()
  533. tokens.refresh_token = None
  534. def prepare_oauth_config(server_name: str, server_url: str, oauth_config: dict | None) -> tuple[dict, HermesTokenStorage]:
  535. """Copy the ``oauth:`` block, apply provider defaults, open its token storage. The copy
  536. matters: later steps record ``_resolved_port`` / ``_cimd_url`` in the dict, which must
  537. never leak back into the caller's config."""
  538. from tools import mcp_oauth as mo
  539. cfg = dict(oauth_config or {})
  540. mo.apply_oauth_provider_defaults(cfg, server_name=server_name, server_url=server_url)
  541. return cfg, mo.HermesTokenStorage(server_name)
  542. def build_provider_kwargs(cfg: dict, storage: HermesTokenStorage, *, ssh_proxy_hint: bool) -> dict[str, Any]:
  543. """Resolve the callback port and return the shared provider constructor kwargs. Order
  544. matters: metadata needs the resolved port, pre-registration needs the metadata.
  545. ``ssh_proxy_hint`` lets the redirect handler tailor its remote-session hint to a configured
  546. proxy ``redirect_uri``. Helpers are looked up on ``tools.mcp_oauth`` so tests can patch them."""
  547. from tools import mcp_oauth as mo
  548. port = mo._configure_callback_port(cfg, storage)
  549. client_metadata = mo._build_client_metadata(cfg)
  550. mo._maybe_preregister_client(storage, cfg, client_metadata)
  551. redirect_uri = (cfg.get("redirect_uri") or None) if ssh_proxy_hint else None
  552. return {
  553. "client_metadata": client_metadata,
  554. "storage": storage,
  555. "redirect_handler": mo._make_redirect_handler(port, redirect_uri=redirect_uri, redirect_host=cfg.get("redirect_host")),
  556. # mcp 2.0 dropped OAuthClientProvider's own `timeout`; the configured
  557. # `oauth.timeout` bounds the callback waiter's poll loop instead.
  558. "callback_handler": mo._make_callback_waiter(port, cfg.get("_cimd_url"), timeout=float(cfg.get("timeout", 300))),
  559. "token_user_agent": mo.token_request_user_agent(cfg),
  560. "oauth_flow": cfg.get("flow", "browser"),
  561. **mo.cimd_provider_kwargs(cfg)}