Skip to content

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.

fix(marketplace): make OAuth token persistence failure-safe and honest

Ruben Lütkee247dc30949d
diff --git a/jarvis/marketplace/refresh_scheduler.py b/jarvis/marketplace/refresh_scheduler.py
index 8545199f8a..4c410ec3da 100644
--- a/jarvis/marketplace/refresh_scheduler.py
+++ b/jarvis/marketplace/refresh_scheduler.py
@@ -152,9 +152,19 @@ async def refresh_due_tokens(
# "Reconnect" prompt. A connected plugin must never silently
# disappear; the only user-visible delete path is an explicit
# DELETE. (Previously this called store.delete(pid).)
- store.save(pid, dataclasses.replace(tokens, needs_reauth=True))
- outcomes[pid] = REVOKED
- log.info("plugin %s refresh needs reauth — marked needs_reauth: %s", pid, exc)
+ try:
+ store.save(pid, dataclasses.replace(tokens, needs_reauth=True))
+ outcomes[pid] = REVOKED
+ log.info(
+ "plugin %s refresh needs reauth — marked needs_reauth: %s", pid, exc
+ )
+ except Exception as save_exc: # noqa: BLE001 — isolate one plugin's store failure
+ outcomes[pid] = FAILED
+ log.warning(
+ "plugin %s needs_reauth save failed, will retry next cycle: %s",
+ pid,
+ save_exc,
+ )
else:
outcomes[pid] = FAILED
log.warning("plugin %s refresh failed (transient, will retry): %s", pid, exc)
@@ -167,11 +177,18 @@ async def refresh_due_tokens(
# A healthy refresh clears any stale needs_reauth flag and stamps the
# refresh time so the keep-alive sweep can skip it until the next window.
merged_extra = {**new_tokens.extra, "last_refreshed": datetime.now(UTC).isoformat()}
- store.save(
- pid,
- dataclasses.replace(new_tokens, extra=merged_extra, needs_reauth=False),
- )
- outcomes[pid] = REFRESHED
+ try:
+ store.save(
+ pid,
+ dataclasses.replace(new_tokens, extra=merged_extra, needs_reauth=False),
+ )
+ outcomes[pid] = REFRESHED
+ except Exception as exc: # noqa: BLE001 — isolate one plugin's store failure
+ outcomes[pid] = FAILED
+ log.warning(
+ "plugin %s refreshed token save failed, will retry next cycle: %s", pid, exc
+ )
+ continue
if on_refreshed is not None:
try:
diff --git a/jarvis/marketplace/token_store.py b/jarvis/marketplace/token_store.py
index 3a3c56246b..186e3b16b9 100644
--- a/jarvis/marketplace/token_store.py
+++ b/jarvis/marketplace/token_store.py
@@ -103,8 +103,14 @@ class KeyringBackend:
def delete(self, key: str) -> None:
from jarvis.core.config import delete_secret
- if not delete_secret(key):
- raise RuntimeError(f"keyring delete failed for {key!r}")
+ # Deliberately does not raise on a failed delete (unlike `set`): both
+ # `ChunkedBackend._clear_overflow` and `ChunkedBackend.set`'s
+ # rollback/leftover-cleanup call this as best-effort housekeeping and
+ # rely on it never raising, so a cleanup failure here can't mask a
+ # more important error or turn a successful token save into a
+ # reported failure. The return value is intentionally not checked;
+ # see jarvis/core/config.py:delete_secret for the honest result.
+ delete_secret(key)
_CHUNK_SENTINEL = "\x00JCHUNKS\x00" # primary-key header for a chunked value: sentinel + <count>
diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.py
index 81c176e63d..75500b794c 100644
--- a/jarvis/ui/web/marketplace_routes.py
+++ b/jarvis/ui/web/marketplace_routes.py
@@ -471,15 +471,26 @@ async def connect_start(plugin_id: str, background: BackgroundTasks) -> dict[str
return
async with slot.completion_lock:
try:
- slot.result = await handler.await_completion(session)
+ result = await handler.await_completion(session)
except Exception as exc: # noqa: BLE001
log.warning("plugin %s connect/await failed: %s", plugin_id, exc)
slot.result = FlowResult(tokens=None, error=str(exc))
- else:
- if slot.result.tokens is not None:
- TokenStore().save(plugin_id, slot.result.tokens)
- _refresh_plugin_in_live_registry(plugin_id)
- log.info("plugin %s connected via DCR", plugin_id)
+ return
+ if result.tokens is not None:
+ # Persist BEFORE publishing the result: connect_poll reads
+ # `slot.result` to decide "connected" vs "pending", so setting
+ # it before the save actually lands let a poll (or a crash
+ # right after) report success for a token that was never
+ # written to the store.
+ try:
+ TokenStore().save(plugin_id, result.tokens)
+ except Exception as exc: # noqa: BLE001
+ log.warning("plugin %s token save failed: %s", plugin_id, exc)
+ slot.result = FlowResult(tokens=None, error=f"token save failed: {exc}")
+ return
+ _refresh_plugin_in_live_registry(plugin_id)
+ log.info("plugin %s connected via DCR", plugin_id)
+ slot.result = result
asyncio.create_task(_drive(), name=f"oauth-drive:{plugin_id}:{session.flow_id}")
diff --git a/tests/unit/marketplace/test_connect_token_save_failure.py b/tests/unit/marketplace/test_connect_token_save_failure.py
new file mode 100644
index 0000000000..5d366fa75e
--- /dev/null
+++ b/tests/unit/marketplace/test_connect_token_save_failure.py
@@ -0,0 +1,120 @@
+"""connect_start's background _drive() must not report "connected" before the
+token actually landed in the TokenStore.
+
+Previously `slot.result` (what `connect_poll` reads) was set to the
+successful FlowResult BEFORE `TokenStore().save()` ran, so a save failure
+(or a crash right after `await_completion`) still let the poll endpoint
+report a successful connect for a token that was never persisted.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+from fastapi import BackgroundTasks
+
+from jarvis.marketplace.auth.base import AuthSession, FlowResult
+from jarvis.marketplace.token_store import Tokens
+from jarvis.ui.web import marketplace_routes as mr
+
+
+class _Catalog:
+ def __init__(self, specs):
+ self.plugins = specs
+
+ def by_id(self, plugin_id: str):
+ return next((s for s in self.plugins if s.id == plugin_id), None)
+
+
+def _pkce_spec(client_id: str):
+ for spec in mr.load_catalog().plugins:
+ if spec.auth is not None and getattr(spec.auth, "mode", "") == "oauth_pkce_loopback":
+ return spec.model_copy(
+ update={"auth": spec.auth.model_copy(update={"client_id": client_id})}
+ )
+ pytest.skip("no oauth_pkce_loopback plugin in catalog")
+
+
+class _StubPkceHandler:
+ """Stands in for the real PkceLoopbackHandler: returns a session
+ immediately and a completed FlowResult carrying tokens, without ever
+ touching a socket or a real OAuth provider."""
+
+ def __init__(self, config) -> None:
+ self.config = config
+
+ async def start(self, plugin_spec) -> AuthSession:
+ return AuthSession(
+ flow_id=f"test-flow-{plugin_spec.id}",
+ plugin_id=plugin_spec.id,
+ kind="browser_redirect",
+ )
+
+ async def await_completion(self, session: AuthSession) -> FlowResult:
+ return FlowResult(tokens=Tokens(access="tok-123"), error=None)
+
+
+def _capture_background_tasks(monkeypatch):
+ """connect_start fires `_drive()` via `asyncio.create_task` and returns
+ immediately — capture the task so the test can await it before polling."""
+ real_create_task = asyncio.create_task
+ captured: list[asyncio.Task] = []
+
+ def _capturing(coro, **kwargs):
+ task = real_create_task(coro, **kwargs)
+ captured.append(task)
+ return task
+
+ monkeypatch.setattr(mr.asyncio, "create_task", _capturing)
+ return captured
+
+
+async def _start_and_drain(monkeypatch, capture_background_tasks) -> tuple[str, str]:
+ spec = _pkce_spec("real-client-id.apps.example")
+ monkeypatch.setattr(mr, "load_catalog", lambda: _Catalog([spec]))
+ monkeypatch.setattr(
+ "jarvis.marketplace.connect_helpers.resolve_pkce_client",
+ lambda pid, cid, csec: ("real-client-id.apps.example", None),
+ )
+ monkeypatch.setattr(mr, "PkceLoopbackHandler", _StubPkceHandler)
+
+ session = await mr.connect_start(spec.id, BackgroundTasks())
+ for task in capture_background_tasks:
+ await task
+ return session["plugin_id"], session["flow_id"]
+
+
+async def test_connect_poll_reports_error_when_token_save_fails(
+ monkeypatch, _capture_background_tasks
+) -> None:
+ def _raising_save(self, plugin_id, tokens) -> None:
+ raise RuntimeError("simulated keyring save failure")
+
+ monkeypatch.setattr(mr.TokenStore, "save", _raising_save)
+
+ plugin_id, flow_id = await _start_and_drain(monkeypatch, _capture_background_tasks)
+
+ result = await mr.connect_poll(plugin_id, flow_id)
+ assert result["state"] == "error"
+
+
+async def test_connect_poll_reports_connected_when_save_succeeds(
+ monkeypatch, _capture_background_tasks
+) -> None:
+ saved: dict[str, Tokens] = {}
+
+ def _recording_save(self, plugin_id, tokens) -> None:
+ saved[plugin_id] = tokens
+
+ monkeypatch.setattr(mr.TokenStore, "save", _recording_save)
+ monkeypatch.setattr(mr, "_refresh_plugin_in_live_registry", lambda plugin_id: None)
+
+ plugin_id, flow_id = await _start_and_drain(monkeypatch, _capture_background_tasks)
+
+ result = await mr.connect_poll(plugin_id, flow_id)
+ assert result["state"] == "connected"
+ assert saved # the token was actually persisted before the state flipped
diff --git a/tests/unit/marketplace/test_refresh_scheduler.py b/tests/unit/marketplace/test_refresh_scheduler.py
index b8ae4f87ca..31f4de569f 100644
--- a/tests/unit/marketplace/test_refresh_scheduler.py
+++ b/tests/unit/marketplace/test_refresh_scheduler.py
@@ -361,6 +361,43 @@ async def test_on_refreshed_exception_does_not_break_the_loop(caplog) -> None:
assert store.load("notion").access == "a1" # token save is unaffected
+class _SaveFailsForPlugin:
+ """Wraps a real TokenStore; ``save`` raises for one chosen plugin id --
+ used to prove a store failure for one plugin stays isolated from the
+ rest of the cycle."""
+
+ def __init__(self, inner: TokenStore, fail_for: str) -> None:
+ self._inner = inner
+ self._fail_for = fail_for
+
+ def load(self, plugin_id: str):
+ return self._inner.load(plugin_id)
+
+ def save(self, plugin_id: str, tokens: Tokens) -> None:
+ if plugin_id == self._fail_for:
+ raise RuntimeError("simulated store.save failure")
+ self._inner.save(plugin_id, tokens)
+
+
+async def test_one_plugins_save_failure_does_not_block_the_next() -> None:
+ inner = _store()
+ inner.save("gmail", _tokens(60))
+ inner.save("notion", _tokens(60))
+ store = _SaveFailsForPlugin(inner, fail_for="gmail")
+ handlers = {
+ "gmail": _FakeHandler("gmail", new_tokens=Tokens(access="a1", refresh="r1")),
+ "notion": _FakeHandler("notion", new_tokens=Tokens(access="a2", refresh="r2")),
+ }
+
+ outcomes = await refresh_due_tokens(
+ ["gmail", "notion"], store, lambda pid: handlers[pid]
+ )
+
+ assert outcomes == {"gmail": FAILED, "notion": REFRESHED}
+ assert inner.load("notion").access == "a2"
+
+
@pytest.mark.asyncio
async def test_scheduler_keep_alive_refreshes_long_lived_token() -> None:
# The scheduler must apply keep-alive so a long-lived / no-expiry token still
diff --git a/tests/unit/marketplace/test_token_store.py b/tests/unit/marketplace/test_token_store.py
index ba946072be..b07edcb2a6 100644
--- a/tests/unit/marketplace/test_token_store.py
+++ b/tests/unit/marketplace/test_token_store.py
@@ -82,6 +82,64 @@ def test_chunked_backend_resave_smaller_clears_stale_chunks():
assert list(primitive.store) == ["plugin_gmail_tokens"]
+class _FailNthSetBackend:
+ """Mimics a keyring backend whose ``set`` raises on a chosen call number
+ (1-indexed across the object's whole lifetime) — used to simulate a
+ write failing partway through a chunked ``ChunkedBackend.set``."""
+
+ def __init__(self) -> None:
+ self.fail_on_call: int | None = None
+ self.calls = 0
+ self.store: dict[str, str] = {}
+
+ def get(self, key: str) -> str | None:
+ return self.store.get(key)
+
+ def set(self, key: str, value: str) -> None:
+ self.calls += 1
+ if self.calls == self.fail_on_call:
+ raise RuntimeError("simulated backend write failure")
+ self.store[key] = value
+
+ def delete(self, key: str) -> None:
+ self.store.pop(key, None)
+
+
+def test_chunked_backend_set_failure_leaves_old_value_intact():
+ # Delete-then-write used to drop the OLD chunks before writing the new
+ # ones, so a failure partway through left a header pointing at deleted
+ # data. Write-then-swap must instead leave the last-good value readable.
+ primitive = _FailNthSetBackend()
+ backend = ChunkedBackend(primitive, chunk_size=20)
+ old_value = "a" * 55 # 3 chunks: 20 / 20 / 15
+ backend.set("plugin_gmail_tokens", old_value)
+ assert backend.get("plugin_gmail_tokens") == old_value
+
+ # Fail on the 2nd chunk write of the NEXT set() call (chunk index 1 of 3).
+ primitive.fail_on_call = primitive.calls + 2
+ with pytest.raises(RuntimeError):
+ backend.set("plugin_gmail_tokens", "b" * 55)
+
+ assert backend.get("plugin_gmail_tokens") == old_value
+
+
+def test_chunked_backend_set_success_leaves_no_orphan_chunks_when_shrinking():
+ # New value needs FEWER chunks than the old one -- the old header's
+ # higher-index leftovers must be cleaned up, not just the count that
+ # overlaps with the new value.
+ primitive = _SizeLimitedFakeBackend(limit=1000)
+ backend = ChunkedBackend(primitive, chunk_size=20)
+ backend.set("plugin_gmail_tokens", "a" * 100) # 5 chunks
+ backend.set("plugin_gmail_tokens", "b" * 30) # 2 chunks
+
+ assert backend.get("plugin_gmail_tokens") == "b" * 30
+ assert set(primitive.store) == {
+ "plugin_gmail_tokens",
+ "plugin_gmail_tokens__0",
+ "plugin_gmail_tokens__1",
+ }
+
+
def test_chunked_backend_raises_when_a_single_chunk_still_too_big():
# Defensive: if even one chunk can't be stored, fail loudly rather than
# silently persisting a partial blob that can never be reassembled.