Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(marketplace): keep MCP connections authenticated through token rotation (#434)
Ruben Lütke14673f592163
diff --git a/jarvis/brain/ollama_library.py b/jarvis/brain/ollama_library.pyindex 8705e0c488..7bb13976a0 100644--- a/jarvis/brain/ollama_library.py+++ b/jarvis/brain/ollama_library.py@@ -224,14 +224,23 @@ def parse_search_html(page: str) -> list[dict[str, Any]]:description = textbreak- spans = [_text(m.group(1)) for m in re.finditer(r"<span\b[^>]*>([^<]*)</span>", block)]+ # The current catalog puts an SVG before title-cased badge labels.+ # Ignore icon markup while retaining the actual visible label, and+ # keep accepting the older text-only lowercase badges.+ labels = re.sub(r"<svg\b[^>]*>.*?</svg>", "", block, flags=re.DOTALL | re.IGNORECASE)+ spans = [_text(m.group(1)) for m in re.finditer(r"<span\b[^>]*>([^<]*)</span>", labels)]spans = [s for s in spans if s]- capabilities = [badge for badge in _CAPABILITY_BADGES if badge in spans]+ badge_labels = {s.lower() for s in spans}+ capabilities = [badge for badge in _CAPABILITY_BADGES if badge in badge_labels]sizes = [s for s in spans if re.fullmatch(r"\d+(?:\.\d+)?[bm]", s)]pulls_match = re.search(r">\s*([\d.,]+[KMB]?)\s*</span>\s*<span[^>]*>(?: |\s)*Pulls", block)+ if pulls_match is None:+ pulls_match = re.search(+ r'''\btitle=["']([\d.,]+[KMB]?)\s+downloads["']''', block, re.IGNORECASE+ )updated = next((s for s in spans if s.endswith(" ago") or s == "yesterday"), "")entries.append(@@ -239,7 +248,7 @@ def parse_search_html(page: str) -> list[dict[str, Any]]:"name": name,"description": description,"capabilities": capabilities,- "cloud": "cloud" in spans,+ "cloud": "cloud" in badge_labels,"sizes": sizes,"pulls": pulls_match.group(1) if pulls_match else "","updated": updated,diff --git a/jarvis/marketplace/http_auth.py b/jarvis/marketplace/http_auth.pynew file mode 100644index 0000000000..d706d94b10--- /dev/null+++ b/jarvis/marketplace/http_auth.py@@ -0,0 +1,126 @@+"""Keep remote MCP requests on the current Marketplace credential generation."""++from __future__ import annotations++import asyncio+import logging+from collections.abc import AsyncGenerator+from datetime import UTC, datetime++import httpx++from jarvis.marketplace.refresh_scheduler import (+ HandlerBuilder,+ RefreshAttempt,+ refresh_plugin_token,+)+from jarvis.marketplace.token_store import Tokens, TokenStore++log = logging.getLogger(__name__)+++class PluginHttpAuth(httpx.Auth):+ """Refresh before expiry and retry only an explicit HTTP authentication refusal.++ The SDK owns the HTTP session, but the Marketplace owns its credentials.+ Reading the store per request also picks up rotations by another app instance.+ Tool errors, transport failures and timeouts are never replayed here.+ """++ def __init__(+ self,+ plugin_id: str,+ url: str,+ store: TokenStore,+ build_handler: HandlerBuilder,+ ) -> None:+ self._plugin_id = plugin_id+ self._url = httpx.URL(url)+ self._store = store+ self._build_handler = build_handler++ def _tokens(self) -> Tokens:+ tokens = self._store.load(self._plugin_id)+ if tokens is None or tokens.needs_reauth:+ raise RuntimeError("Plugin disconnected or authorization expired; reconnect in Plugins")+ return tokens++ async def _refresh(self, *, observed: str | None = None) -> RefreshAttempt:+ async def refresh_bounded() -> RefreshAttempt:+ return await asyncio.wait_for(+ refresh_plugin_token(+ self._plugin_id,+ self._store,+ self._build_handler,+ force=observed is not None,+ observed_access_token=observed,+ ),+ timeout=65,+ )++ task = asyncio.create_task(+ refresh_bounded(),+ name=f"plugin-http-refresh:{self._plugin_id}",+ )+ cancelled: asyncio.CancelledError | None = None+ # Closing an MCP stream must not discard an already-rotated grant.+ # Even repeated cancellation waits for this bounded save to finish.+ while not task.done():+ try:+ await asyncio.shield(task)+ except asyncio.CancelledError as exc:+ # Re-raise after the bounded credential save finishes below.+ cancelled = exc+ except Exception as exc: # noqa: BLE001 - re-raised via task.result below+ log.debug(+ "plugin %s HTTP refresh ended with %s",+ self._plugin_id,+ type(exc).__name__,+ )+ break+ try:+ result = task.result()+ except TimeoutError:+ log.warning("plugin %s HTTP refresh did not drain", self._plugin_id)+ if cancelled is not None:+ raise cancelled from None+ raise+ if cancelled is not None:+ raise cancelled+ return result++ async def async_auth_flow(+ self, request: httpx.Request+ ) -> AsyncGenerator[httpx.Request, httpx.Response]:+ if (request.url.scheme, request.url.host, request.url.port) != (+ self._url.scheme,+ self._url.host,+ self._url.port,+ ):+ raise RuntimeError("Plugin credential destination does not match its MCP server")++ # An async auth-flow override must buffer explicitly; HTTPX only honors+ # requires_request_body in its default sync-to-async implementation.+ await request.aread()+ tokens = self._tokens()+ if tokens.is_near_expiry():+ await self._refresh()+ tokens = self._tokens()+ if tokens.expires_at is not None and tokens.expires_at <= datetime.now(UTC):+ raise RuntimeError(+ "Plugin token refresh temporarily unavailable; try again shortly"+ )++ request.headers["Authorization"] = f"Bearer {tokens.access}"+ response = yield request+ if response.status_code != 401:+ return++ attempt = await self._refresh(observed=tokens.access)+ if not attempt.usable:+ return+ tokens = self._tokens()+ request.headers["Authorization"] = f"Bearer {tokens.access}"+ # Release the refused response before retrying a streaming request.+ await response.aclose()+ yield requestdiff --git a/jarvis/marketplace/plugin_registry.py b/jarvis/marketplace/plugin_registry.pyindex 22ffd818ab..8fb1614f99 100644--- a/jarvis/marketplace/plugin_registry.py+++ b/jarvis/marketplace/plugin_registry.py@@ -209,6 +209,22 @@ class PluginToolRegistry:self._bootstrapped = Truelog.info("plugin-registry: %d plugin tools exposed", len(self._tools))+ async def refresh_credentials(self, plugin_id: str) -> None:+ """Apply token rotation without interrupting a request-aware HTTP session."""+ async with self._lock:+ if self._stopping:+ return+ client = self._clients.get(plugin_id)+ tokens = self._store.load(plugin_id)+ if (+ getattr(client, "uses_dynamic_http_auth", False)+ and client.is_healthy+ and tokens is not None+ and not tokens.needs_reauth+ ):+ return+ await self.refresh_plugin(plugin_id)+async def refresh_plugin(self, plugin_id: str) -> None:"""Re-evaluate a single plugin after connect/disconnect."""async with self._lock:@@ -291,6 +307,18 @@ class PluginToolRegistry:) -> tuple[Any, list[dict[str, Any]]]:"""Open one bounded client and clean up any failed attempt."""client = self._client_factory(server_spec, env_overrides=env_overrides)+ set_http_auth = getattr(client, "set_http_auth", None)+ if server_spec.transport == "http" and callable(set_http_auth):+ authorization = next(+ (v for k, v in (server_spec.headers or {}).items() if k.lower() == "authorization"),+ "",+ )+ if authorization.lower().startswith("bearer "):+ from jarvis.marketplace.http_auth import PluginHttpAuth++ set_http_auth(PluginHttpAuth(+ server_spec.name, server_spec.url, self._store, self._build_refresh_handler+ ))from jarvis.marketplace.bundled_rest_client import BundledRestMcpClientif isinstance(client, BundledRestMcpClient):@@ -341,6 +369,11 @@ class PluginToolRegistry:raise pending_canceldef _connect_error_message(self, exc: Exception) -> str:+ if isinstance(exc, BaseExceptionGroup):+ # AnyIO wraps HTTP refusals in TaskGroup errors. Its group summary+ # contains no status code, so treating it as the error hides the 401+ # and repeatedly reconnects with the same stale credential.+ return "; ".join(self._connect_error_message(child) for child in exc.exceptions)if isinstance(exc, asyncio.TimeoutError):return (f"connect timed out after {self._connect_timeout_s:.0f}s "@@ -402,7 +435,7 @@ class PluginToolRegistry:)self._last_errors[plugin.id] = messageif attempt.outcome == SKIPPED:- self._maybe_mark_needs_reauth(plugin.id, message)+ self._maybe_mark_needs_reauth(plugin.id, message, expected_tokens=tokens)else:self._schedule_retry(plugin.id)return@@ -485,10 +518,15 @@ class PluginToolRegistry:"plugin-registry: %s re-auth mark skipped; token changed during connect retry",plugin_id,)+ self._schedule_retry(plugin_id)return- from jarvis.marketplace.refresh_scheduler import flag_for_reauth+ from jarvis.marketplace.refresh_scheduler import _save_if_current, flag_for_reauth- self._store.save(plugin_id, flag_for_reauth(tokens, reason))+ if not _save_if_current(+ self._store, plugin_id, tokens, flag_for_reauth(tokens, reason)+ ):+ self._schedule_retry(plugin_id)+ returnlog.warning("plugin-registry: %s connect needs re-auth (%s) — marked: %s",plugin_id,diff --git a/jarvis/mcp/client.py b/jarvis/mcp/client.pyindex 2884c85519..2b428913d2 100644--- a/jarvis/mcp/client.py+++ b/jarvis/mcp/client.py@@ -116,6 +116,15 @@ class MCPClient:self._tools_cache: list[dict[str, Any]] = []self._circuit_breaker_failures = 0self._disabled_until_ns: int = 0+ self._http_auth: Any | None = None++ def set_http_auth(self, auth: Any) -> None:+ """Install caller-owned request authentication before opening transport."""+ self._http_auth = auth++ @property+ def uses_dynamic_http_auth(self) -> bool:+ return self._http_auth is not None# ---- Lifecycle ----------------------------------------------------@@ -196,7 +205,11 @@ class MCPClient:# (read, write, get_session_id) — unlike the 2-tuple stdio/sse# transports. The session-id callback is unused here.read, write, _ = await stack.enter_async_context(- streamablehttp_client(self.spec.url, headers=headers or None)+ streamablehttp_client(+ self.spec.url,+ headers=headers or None,+ **({"auth": self._http_auth} if self._http_auth is not None else {}),+ ))else:raise NotImplementedError(diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex dce4988243..36c5cd7a0b 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -2540,7 +2540,7 @@ class WebServer:if registry is None or self._refresh_scheduler_stopping:returntask = asyncio.create_task(- registry.refresh_plugin(plugin_id),+ registry.refresh_credentials(plugin_id),name=f"plugin-refresh:{plugin_id}",)self._refresh_registry_tasks.add(task)diff --git a/tests/fakes/fake_plugin_http.py b/tests/fakes/fake_plugin_http.pynew file mode 100644index 0000000000..8840a643ab--- /dev/null+++ b/tests/fakes/fake_plugin_http.py@@ -0,0 +1,67 @@+"""An OAuth provider and MCP transport with observable credential rotation."""++from __future__ import annotations++import asyncio+import json+from datetime import UTC, datetime, timedelta++import httpx++from jarvis.marketplace.token_store import Tokens+++class RotatingPluginHandler:+ def __init__(self) -> None:+ self.calls: list[str | None] = []+ self.entered = asyncio.Event()+ self.release: asyncio.Event | None = None+ self.error: Exception | None = None++ async def refresh(self, current: Tokens) -> Tokens:+ self.calls.append(current.refresh)+ self.entered.set()+ if self.release is not None:+ await self.release.wait()+ if self.error is not None:+ raise self.error+ return Tokens(+ access="fresh-access",+ refresh="fresh-refresh",+ expires_at=datetime.now(UTC) + timedelta(hours=1),+ )+++class PluginMcpTransport:+ """Exercise the real MCP SDK over HTTPX without sockets or provider calls."""++ def __init__(self) -> None:+ self.accepted = "old-access"+ self.requests: list[tuple[str, str]] = []+ self.tool_calls = 0++ def __call__(self, request: httpx.Request) -> httpx.Response:+ header = request.headers.get("Authorization", "")+ if request.method != "POST":+ return httpx.Response(405)+ body = json.loads(request.content)+ method = body.get("method", "")+ self.requests.append((method, header))+ if header != f"Bearer {self.accepted}":+ return httpx.Response(401)+ if method.startswith("notifications/"):+ return httpx.Response(202)+ if method == "initialize":+ result = {+ "protocolVersion": "2025-03-26",+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "test-plugin", "version": "1"},+ }+ elif method == "tools/list":+ result = {"tools": [{"name": "list_items", "inputSchema": {"type": "object"}}]}+ elif method == "tools/call":+ self.tool_calls += 1+ result = {"content": [{"type": "text", "text": "items"}], "isError": False}+ else:+ raise AssertionError(f"Unexpected MCP method: {method}")+ return httpx.Response(200, json={"jsonrpc": "2.0", "id": body["id"], "result": result})diff --git a/tests/integration/test_ollama_library_live.py b/tests/integration/test_ollama_library_live.pyindex 6b56b33fe9..607ee8a1b9 100644--- a/tests/integration/test_ollama_library_live.py+++ b/tests/integration/test_ollama_library_live.py@@ -57,13 +57,18 @@ def test_the_live_tags_page_still_parses() -> None:def test_the_live_newest_sort_is_honoured() -> None:- """``?o=newest`` must change the ORDER: the first rows are days or weeks- old, never the years-old names that top the popular listing."""+ """``?o=newest`` must change the ordered results from the popular listing.++ Search cards no longer publish ages, so sorting cannot be inferred from+ timestamps. Compare the two real listings instead of inventing an age.+ """models = parse_search_html(_fetch("https://ollama.com/search?o=newest"))assert len(models) >= 5, "The live newest listing parsed almost empty."- head = [m["updated"] for m in models[:5]]- assert all(u and "year" not in u for u in head), head- assert any(("day" in u or "week" in u or u == "yesterday") for u in head), head+ popular = parse_search_html(_fetch("https://ollama.com/search"))+ assert len(popular) >= 5, "The live popular listing parsed almost empty."+ newest_names = [model["name"] for model in models]+ popular_names = [model["name"] for model in popular]+ assert newest_names != popular_names, "The newest sort returned the default ordering."def test_the_live_capability_filter_is_honoured() -> None:diff --git a/tests/unit/brain/test_ollama_library.py b/tests/unit/brain/test_ollama_library.pyindex cc98413606..f8b1dde232 100644--- a/tests/unit/brain/test_ollama_library.py+++ b/tests/unit/brain/test_ollama_library.py@@ -77,6 +77,27 @@ def test_search_parser_answers_empty_on_garbage() -> None:assert library.parse_search_html("<html><body>maintenance</body></html>") == []+def test_search_parser_reads_icon_badges_and_download_counts() -> None:+ page = """+ <li><a href="/library/example">+ <h2><span>example</span></h2>+ <p>A model whose description mentions tools without claiming that badge.</p>+ <span><svg><title>Tools</title><path d="M0 0"/></svg>Vision</span>+ <span><svg><path d="M0 0"/></svg>Embedding</span>+ <span><svg><path d="M0 0"/></svg>Cloud</span>+ <span><span>270m</span><span>440m</span></span>+ <span title="5,358 downloads"><svg></svg><span>5,358</span></span>+ </a></li>+ """+ model, = library.parse_search_html(page)+ assert model["capabilities"] == ["vision", "embedding"]+ assert model["cloud"] is True+ assert model["sizes"] == ["270m", "440m"]+ assert model["pulls"] == "5,358"+ # The redesigned page omits timestamps; unknown must remain unknown.+ assert model["updated"] == ""++# ── tags parser ──────────────────────────────────────────────────────────diff --git a/tests/unit/marketplace/test_connect_recovery.py b/tests/unit/marketplace/test_connect_recovery.pynew file mode 100644index 0000000000..ccfc147f11--- /dev/null+++ b/tests/unit/marketplace/test_connect_recovery.py@@ -0,0 +1,90 @@+"""Reconnect errors must neither hide authentication nor overwrite a newer grant."""++from __future__ import annotations++import httpx+import pytest++from jarvis.marketplace.catalog import PluginCatalog+from jarvis.marketplace.catalog_data import load_catalog+from jarvis.marketplace.plugin_registry import PluginToolRegistry+from jarvis.marketplace.token_store import InMemoryBackend, Tokens, TokenStore+from tests.fakes.fake_plugin_http import RotatingPluginHandler++[email protected]("status", [401, 503])+async def test_nested_sdk_http_errors_select_refresh_or_retry(status):+ plugin = load_catalog().by_id("notion")+ store = TokenStore(InMemoryBackend())+ store.save(plugin.id, Tokens(access="old-access", refresh="old-refresh"))+ handler = RotatingPluginHandler()++ class Client:+ def __init__(self, spec, **kwargs):+ self.spec = spec++ async def start(self):+ if self.spec.headers["Authorization"] == "Bearer old-access":+ response = httpx.Response(status, request=httpx.Request("POST", self.spec.url))+ error = httpx.HTTPStatusError(+ f"HTTP {status}", request=response.request, response=response+ )+ raise ExceptionGroup("TaskGroup", [ExceptionGroup("transport", [error])])++ async def stop(self):+ pass++ async def list_tools(self):+ return [{"name": "list_items", "inputSchema": {}}]++ registry = PluginToolRegistry(+ catalog=PluginCatalog(version=1, schema_version="1", plugins=[plugin]),+ token_store=store,+ client_factory=Client,+ refresh_handler_builder=lambda _: handler,+ )+ try:+ await registry.bootstrap()+ assert handler.calls == (["old-refresh"] if status == 401 else [])+ assert registry.live_tool_count(plugin.id) == (1 if status == 401 else 0)+ assert not store.load(plugin.id).needs_reauth+ if status == 503:+ assert plugin.id in registry._retry_tasks+ finally:+ await registry.stop()+++async def test_reauth_mark_is_atomic_with_concurrent_credential_rotation():+ replacement = Tokens(access="new-login", refresh="new-refresh")++ class RacingStore(TokenStore):+ def compare_and_save(self, plugin_id, expected, updated):+ # Another instance commits between the caller's load and its write.+ self.save(plugin_id, replacement)+ return super().compare_and_save(plugin_id, expected, updated)++ store = RacingStore(InMemoryBackend())+ original = Tokens(access="old-access", refresh="old-refresh")+ store.save("notion", original)+ registry = PluginToolRegistry(token_store=store)+ try:+ registry._maybe_mark_needs_reauth("notion", "HTTP 401", expected_tokens=original)+ assert store.load("notion") == replacement+ finally:+ await registry.stop()+++async def test_stale_auth_refusal_does_not_flag_a_reconnected_static_token():+ original = Tokens(access="old-access")+ replacement = Tokens(access="new-access")+ store = TokenStore(InMemoryBackend())+ store.save("notion", replacement)+ registry = PluginToolRegistry(token_store=store)+ try:+ registry._maybe_mark_needs_reauth("notion", "HTTP 401", expected_tokens=original)+ assert store.load("notion") == replacement+ finally:+ await registry.stop()diff --git a/tests/unit/marketplace/test_http_auth.py b/tests/unit/marketplace/test_http_auth.pynew file mode 100644index 0000000000..bfb15270eb--- /dev/null+++ b/tests/unit/marketplace/test_http_auth.py@@ -0,0 +1,311 @@+"""Remote plugin sessions must survive token rotation without browser consent."""++from __future__ import annotations++import asyncio+from datetime import UTC, datetime, timedelta++import httpx+import pytest++from jarvis.marketplace.catalog_data import load_catalog+from jarvis.marketplace.http_auth import PluginHttpAuth+from jarvis.marketplace.token_store import InMemoryBackend, Tokens, TokenStore+from tests.fakes.fake_plugin_http import PluginMcpTransport, RotatingPluginHandler++URL = "https://plugin.example/mcp"+++def _setup(seconds: int = 3600):+ store = TokenStore(InMemoryBackend())+ store.save(+ "notion",+ Tokens(+ access="old-access",+ refresh="old-refresh",+ expires_at=datetime.now(UTC) + timedelta(seconds=seconds),+ ),+ )+ handler = RotatingPluginHandler()+ auth = PluginHttpAuth("notion", URL, store, lambda _: handler)+ return store, handler, auth+++async def test_each_request_reads_rotations_from_other_instances():+ store, handler, auth = _setup()+ seen = []++ def respond(request):+ seen.append(request.headers["Authorization"])+ return httpx.Response(200)++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ await client.post(URL)+ store.save("notion", Tokens(access="another-instance", refresh="rotated"))+ await client.post(URL)+ assert seen == ["Bearer old-access", "Bearer another-instance"]+ assert handler.calls == []+++async def test_expired_access_is_refreshed_before_the_first_request():+ store, handler, auth = _setup(-1)+ seen = []++ def respond(request):+ seen.append(request.headers["Authorization"])+ return httpx.Response(200)++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ await client.post(URL)+ assert seen == ["Bearer fresh-access"]+ assert handler.calls == ["old-refresh"]+ assert store.load("notion").refresh == "fresh-refresh"+++async def test_401_refreshes_once_and_preserves_request_body():+ _, handler, auth = _setup()+ seen = []++ def respond(request):+ seen.append((request.headers["Authorization"], request.content))+ return httpx.Response(401 if len(seen) == 1 else 200)++ async def body():+ yield b"same-"+ yield b"operation"++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ response = await client.post(URL, content=body())+ assert response.status_code == 200+ assert seen == [+ ("Bearer old-access", b"same-operation"),+ ("Bearer fresh-access", b"same-operation"),+ ]+ assert handler.calls == ["old-refresh"]+++async def test_concurrent_401s_consume_a_rotating_refresh_token_only_once():+ _, handler, auth = _setup()+ both_arrived = asyncio.Event()+ old_requests = 0++ async def respond(request):+ nonlocal old_requests+ if request.headers["Authorization"] == "Bearer old-access":+ old_requests += 1+ if old_requests == 2:+ both_arrived.set()+ await both_arrived.wait()+ return httpx.Response(401)+ return httpx.Response(200)++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ responses = await asyncio.wait_for(+ asyncio.gather(client.post(URL), client.post(URL)), timeout=2+ )+ assert [r.status_code for r in responses] == [200, 200]+ assert handler.calls == ["old-refresh"]++[email protected]("status", [403, 404, 429, 500, 503])+async def test_non_authentication_failures_are_never_replayed(status):+ store, handler, auth = _setup()+ calls = []++ def respond(request):+ calls.append(request)+ return httpx.Response(status)++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ response = await client.post(URL)+ assert response.status_code == status+ assert len(calls) == 1+ assert not store.load("notion").needs_reauth+ assert handler.calls == []+++async def test_repeated_401_is_bounded():+ _, handler, auth = _setup()+ calls = []++ def respond(request):+ calls.append(request)+ return httpx.Response(401)++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ response = await client.post(URL)+ assert response.status_code == 401+ assert len(calls) == 2+ assert handler.calls == ["old-refresh"]+++ "error,reauth", [(RuntimeError("revoked"), True), (httpx.ConnectError("offline"), False)]+)+async def test_refresh_failure_preserves_the_grant_and_does_not_replay(error, reauth):+ store, handler, auth = _setup()+ handler.error = error+ calls = []++ def respond(request):+ calls.append(request)+ return httpx.Response(401)++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ response = await client.post(URL)+ assert response.status_code == 401+ assert len(calls) == 1+ assert store.load("notion").needs_reauth == reauth+ assert store.load("notion").refresh == "old-refresh"+++async def test_cancelled_request_finishes_saving_rotated_credentials():+ store, handler, auth = _setup(-1)+ handler.release = asyncio.Event()+ calls = []++ def respond(request):+ calls.append(request)+ return httpx.Response(200)++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ request = asyncio.create_task(client.post(URL))+ await handler.entered.wait()+ request.cancel()+ await asyncio.sleep(0)+ request.cancel()+ await asyncio.sleep(0)+ handler.release.set()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(request, timeout=2)+ assert store.load("notion").refresh == "fresh-refresh"+ assert calls == []++[email protected]("disconnect", [True, False])+async def test_removed_or_revoked_connection_cannot_send_a_cached_token(disconnect):+ store, _, auth = _setup()+ if disconnect:+ store.delete("notion")+ else:+ store.save("notion", Tokens(access="revoked", needs_reauth=True))++ def respond(request):+ raise AssertionError("Disconnected plugin must not send a request")++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ with pytest.raises(RuntimeError, match="reconnect in Plugins"):+ await client.post(URL)+++async def test_credentials_are_not_sent_to_a_different_origin():+ _, _, auth = _setup()++ def respond(request):+ raise AssertionError("Credentials must not leave their MCP origin")++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ with pytest.raises(RuntimeError, match="destination"):+ await client.post("https://other.example/mcp")+++ "plugin_id",+ [+ plugin.id+ for plugin in load_catalog().plugins+ if (plugin.mcp_server or {}).get("transport") == "http"+ ],+)+async def test_registry_and_real_sdk_survive_rotation_mid_session(monkeypatch, plugin_id):+ """Run real SDK initialization, tools/list and tools/call through the registry."""+ import mcp.client.streamable_http as sdk++ from jarvis.marketplace.plugin_registry import PluginToolRegistry++ store, handler, _ = _setup()+ original_tokens = store.load("notion")+ store.delete("notion")+ store.save(plugin_id, original_tokens)+ remote = PluginMcpTransport()+ original = sdk.streamablehttp_client++ def open_transport(url, **kwargs):+ def http_client_factory(headers=None, timeout=None, auth=None):+ return httpx.AsyncClient(+ headers=headers,+ timeout=timeout,+ auth=auth,+ transport=httpx.MockTransport(remote),+ )++ return original(url, httpx_client_factory=http_client_factory, **kwargs)++ monkeypatch.setattr(sdk, "streamablehttp_client", open_transport)+ registry = PluginToolRegistry(+ catalog=load_catalog(),+ token_store=store,+ refresh_handler_builder=lambda _: handler,+ )+ try:+ await registry.bootstrap()+ assert registry.live_tool_count(plugin_id) == 1+ client = registry._clients[plugin_id]+ remote.accepted = "fresh-access"+ result = await client.call_tool("list_items", {})+ assert result.content[0].text == "items"+ assert remote.tool_calls == 1+ assert handler.calls == ["old-refresh"]+ assert registry._clients[plugin_id] is client+ assert not store.load(plugin_id).needs_reauth+ # Rotation by a different process is also visible without recreating SDK state.+ store.save(plugin_id, Tokens(access="external-access", refresh="external-refresh"))+ remote.accepted = "external-access"+ await registry.refresh_credentials(plugin_id)+ assert registry._clients[plugin_id] is client+ await client.call_tool("list_items", {})+ assert remote.tool_calls == 2+ assert handler.calls == ["old-refresh"]+ finally:+ await registry.stop()+++async def test_network_timeout_does_not_replay_a_potentially_completed_operation():+ _, handler, auth = _setup()+ calls = []++ def respond(request):+ calls.append(request)+ raise httpx.ReadTimeout("response lost after request was accepted")++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ with pytest.raises(httpx.ReadTimeout):+ await client.post(URL)+ assert len(calls) == 1+ assert handler.calls == []+++async def test_expired_token_and_provider_outage_remain_retryable():+ store, handler, auth = _setup(-1)+ handler.error = httpx.ConnectError("offline")++ def respond(request):+ raise AssertionError("An expired credential must not reach the MCP server")++ async with httpx.AsyncClient(auth=auth, transport=httpx.MockTransport(respond)) as client:+ with pytest.raises(RuntimeError, match="temporarily unavailable"):+ await client.post(URL)+ assert not store.load("notion").needs_reauthdiff --git a/tests/unit/marketplace/test_refresh_lifecycle.py b/tests/unit/marketplace/test_refresh_lifecycle.pyindex 97b8f0a4f1..d2e3e589f5 100644--- a/tests/unit/marketplace/test_refresh_lifecycle.py+++ b/tests/unit/marketplace/test_refresh_lifecycle.py@@ -94,7 +94,7 @@ async def test_stop_cancels_queued_live_session_refresh(class _BlockingRegistry:calls = 0- async def refresh_plugin(self, _plugin_id: str) -> None:+ async def refresh_credentials(self, _plugin_id: str) -> None:self.calls += 1entered.set()try: