Skip to content

The agent that grows with you

fix(honcho): adopt on-disk oauth grant after a 401 instead of re-exchanging

Erosika2250f1d1f336
diff --git a/plugins/memory/honcho/oauth.py b/plugins/memory/honcho/oauth.py
index b78227a340e..7c612bc8e2c 100644
--- a/plugins/memory/honcho/oauth.py
+++ b/plugins/memory/honcho/oauth.py
@@ -256,6 +256,15 @@ def _rotate_and_persist(
rotated = _exchange_with_retry(cred, now=now)
except Exception as exc:
if isinstance(exc, OAuthRefreshError) and exc.permanent:
+ # The file lock is best-effort: a sibling may have rotated first, making our
+ # refresh token a replay. If disk moved on, adopt that grant instead of killing it.
+ disk = _load_cred(path, host)
+ if disk is not None and disk.refresh_token != cred.refresh_token:
+ _dead_grants.pop(key, None)
+ _expiry_cache[key] = (disk.expires_at, disk.access_token)
+ logger.info("Honcho OAuth %s for host %s lost a rotation race; "
+ "adopted the newer on-disk grant", op_label, host)
+ return disk
_mark_grant_dead(key, cred)
logger.error("Honcho OAuth grant for host %s is no longer valid (%s); "
"run 'hermes honcho setup' to re-authenticate", host, exc)
@@ -323,9 +332,14 @@ def ensure_fresh_token(
logger.info("Honcho OAuth token refreshed for host %s", host)
return (rotated.access_token, True) if rotated is not None else (current.access_token, False)
-def force_refresh_token(path: Path, host: str) -> str | None:
+def force_refresh_token(
+ path: Path, host: str, *, failed_access_token: str | None = None
+) -> str | None:
"""Rotate ``host``'s token now, ignoring local expiry (recovers a 401 on a
- token the local clock still thinks is valid)."""
+ token the local clock still thinks is valid). ``failed_access_token`` is the
+ bearer the server rejected: when disk already holds a different one, a sibling
+ rotated the single-use refresh token first, so adopt its grant instead of
+ re-exchanging (a replay can revoke the whole grant)."""
now = time.time()
key = (str(path), host)
with _refresh_lock, _config_refresh_lock(path):
@@ -336,6 +350,11 @@ def force_refresh_token(path: Path, host: str) -> str | None:
# Dead grant, or an exchange just failed transiently: callers fail open.
if _grant_is_dead(key, cred) or _in_failure_cooldown(key):
return None
+ # Disk moving off the rejected bearer is the authoritative signal: the expiry cache is
+ # empty in sibling processes and already equals disk after this process's first waiter.
+ if failed_access_token and cred.access_token != failed_access_token and not cred.is_expired(now=now):
+ _expiry_cache[key] = (cred.expires_at, cred.access_token)
+ return cred.access_token
cached = _expiry_cache.get(key)
# Another thread or process already rotated: adopt the newer on-disk token.
if cached is not None and cred.access_token != cached[1] and not cred.is_expired(now=now):
diff --git a/plugins/memory/honcho/session_auth.py b/plugins/memory/honcho/session_auth.py
index 1439b80cfd0..4050c50e537 100644
--- a/plugins/memory/honcho/session_auth.py
+++ b/plugins/memory/honcho/session_auth.py
@@ -104,7 +104,12 @@ class SessionAuthMixin:
host = getattr(self._config, "host", "") or ""
if not host:
return False
- token = oauth.force_refresh_token(self._bound_config_path(), host)
+ # Tell the refresher which bearer 401'd so a sibling's rotation is adopted, not replayed.
+ try:
+ failed = getattr(getattr(self.honcho, "_http", None), "api_key", None)
+ except Exception:
+ failed = None
+ token = oauth.force_refresh_token(self._bound_config_path(), host, failed_access_token=failed)
if not token:
return False
if not oauth.apply_token_to_client(self.honcho, token):
diff --git a/tests/honcho_plugin/test_auth_recovery.py b/tests/honcho_plugin/test_auth_recovery.py
index dc57d912c4b..5f50187c444 100644
--- a/tests/honcho_plugin/test_auth_recovery.py
+++ b/tests/honcho_plugin/test_auth_recovery.py
@@ -195,6 +195,101 @@ class TestForceRefreshToken:
)
assert oauth.force_refresh_token(path, "hermes") == "hch-at-2"
+ def test_serial_force_refresh_adopts_first_waiters_rotation(self, tmp_path, monkeypatch):
+ """Waiter 2 force-refreshes with the token that 401'd while disk (and
+ the expiry cache) already hold waiter 1's rotation: it must adopt
+ without a second exchange — a replayed refresh token can revoke the
+ grant."""
+ path = tmp_path / "honcho.json"
+ far = time.time() + 7200
+ _write(path, {"hosts": {"hermes": _host_block(expires_at=far)}})
+ calls = []
+
+ def exchange_once(url, data, timeout):
+ calls.append(data["refresh_token"])
+ body = _rotated_body()
+ body["expires_in"] = 7200
+ return 200, body
+
+ monkeypatch.setattr(oauth, "_http_post_form_status", exchange_once)
+ # Waiter 1: rotates for real (cache and disk now both hold new1).
+ assert (
+ oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
+ == "hch-at-new1"
+ )
+ assert calls == ["hch-rt-old"]
+ # Waiter 2: was queued on the lock with the same failing token; disk
+ # has moved — must adopt, not exchange.
+ monkeypatch.setattr(
+ oauth, "_http_post_form_status",
+ lambda *a, **k: pytest.fail("second waiter must adopt, not exchange"),
+ )
+ assert (
+ oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
+ == "hch-at-new1"
+ )
+
+ def test_cross_process_401_adopts_disk_with_empty_cache(self, tmp_path, monkeypatch):
+ """A sibling process rotated on disk; this process's expiry cache is
+ empty. The failing token disagreeing with disk must be enough to
+ adopt with zero HTTP."""
+ path = tmp_path / "honcho.json"
+ far = time.time() + 7200
+ rotated = _host_block(refresh="hch-rt-2", expires_at=far)
+ rotated["apiKey"] = "hch-at-2"
+ _write(path, {"hosts": {"hermes": rotated}})
+ oauth._expiry_cache.clear()
+ monkeypatch.setattr(
+ oauth, "_http_post_form_status",
+ lambda *a, **k: pytest.fail("must adopt the sibling's on-disk grant, not exchange"),
+ )
+ assert (
+ oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
+ == "hch-at-2"
+ )
+ assert oauth._expiry_cache[(str(path), "hermes")][1] == "hch-at-2"
+
+ def test_invalid_grant_adopts_disk_rotated_during_exchange(self, tmp_path, monkeypatch):
+ """The exchange loses the race (endpoint says invalid_grant because a
+ sibling used the refresh token first) and the sibling persists before
+ we give up: adopt its grant, do not mark the grant dead."""
+ path = tmp_path / "honcho.json"
+ far = time.time() + 7200
+ _write(path, {"hosts": {"hermes": _host_block(expires_at=far)}})
+ monkeypatch.setattr(oauth, "_REFRESH_RETRY_DELAY_SECONDS", 0)
+
+ def lost_race(url, data, timeout):
+ # Sibling process persisted its rotation while our POST was in flight.
+ sibling = _host_block(refresh="hch-rt-sibling", expires_at=far)
+ sibling["apiKey"] = "hch-at-sibling"
+ _write(path, {"hosts": {"hermes": sibling}})
+ return 400, {"error": "invalid_grant", "error_description": "reuse detected"}
+
+ monkeypatch.setattr(oauth, "_http_post_form_status", lost_race)
+ assert (
+ oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
+ == "hch-at-sibling"
+ )
+ assert oauth.reauth_required(path, "hermes") is False
+ # And the adopted grant keeps working on later calls.
+ token, _ = oauth.ensure_fresh_token(path, "hermes", now=time.time())
+ assert token == "hch-at-sibling"
+
+ def test_invalid_grant_with_unchanged_disk_still_marks_dead(self, tmp_path, monkeypatch):
+ path = tmp_path / "honcho.json"
+ far = time.time() + 7200
+ _write(path, {"hosts": {"hermes": _host_block(expires_at=far)}})
+ monkeypatch.setattr(oauth, "_REFRESH_RETRY_DELAY_SECONDS", 0)
+ monkeypatch.setattr(
+ oauth, "_http_post_form_status",
+ lambda *a, **k: (400, {"error": "invalid_grant"}),
+ )
+ assert (
+ oauth.force_refresh_token(path, "hermes", failed_access_token="hch-at-old")
+ is None
+ )
+ assert oauth.reauth_required(path, "hermes") is True
+
def test_transient_failure_returns_none(self, tmp_path, monkeypatch):
path = tmp_path / "honcho.json"
_write(path, {"hosts": {"hermes": _host_block(expires_at=time.time() + 3600)}})
@@ -346,7 +441,7 @@ class TestForceReauth:
applied = {}
monkeypatch.setattr(session_mod, "get_honcho_client", lambda *a, **k: fake_client)
monkeypatch.setattr(client_mod, "resolve_config_path", lambda: tmp_path / "honcho.json")
- monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h: "hch-at-new")
+ monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h, **kw: "hch-at-new")
def apply(client, token):
applied["client"] = client
@@ -363,7 +458,7 @@ class TestForceReauth:
from plugins.memory.honcho import client as client_mod
monkeypatch.setattr(client_mod, "resolve_config_path", lambda: tmp_path / "honcho.json")
- monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h: None)
+ monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h, **kw: None)
mgr = HonchoSessionManager(config=HonchoClientConfig(host="hermes"))
assert mgr._force_reauth() is False
@@ -732,7 +827,7 @@ def _wire_rebuild(tmp_path, monkeypatch, fresh_client):
clients = {"current": MagicMock()}
monkeypatch.setattr(session_mod, "get_honcho_client", lambda *a, **k: clients["current"])
monkeypatch.setattr(client_mod, "resolve_config_path", lambda: tmp_path / "honcho.json")
- monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h: "hch-at-rotated")
+ monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h, **kw: "hch-at-rotated")
monkeypatch.setattr(oauth, "apply_token_to_client", lambda c, t: False)
monkeypatch.setattr(
client_mod, "reset_honcho_client",
@@ -872,7 +967,7 @@ def _wire_init(tmp_path, monkeypatch, client, *, recall_mode="hybrid", dead_refr
monkeypatch.setattr(client_mod, "get_honcho_client", lambda *a, **k: client)
monkeypatch.setattr(session_mod, "get_honcho_client", lambda *a, **k: client)
if dead_refresh:
- monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h: None)
+ monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h, **kw: None)
cfg = HonchoClientConfig(
host="hermes", api_key="hch-at-old", enabled=True, recall_mode=recall_mode,
timeout=0.5, session_strategy="per-session",
@@ -981,7 +1076,7 @@ class TestInitAuthFailureNotice:
client.peer.side_effect = TimeoutError("request timed out")
_wire_init(tmp_path, monkeypatch, client, dead_refresh=False)
reauths = []
- monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h: reauths.append(1))
+ monkeypatch.setattr(oauth, "force_refresh_token", lambda p, h, **kw: reauths.append(1))
provider = _initialized_provider()
assert provider._manager is None