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(config): degrade to file cred store on a locked OS keyring (headless Linux)

Ruben Lütkef66b096306e4
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 208b39698a..01fd065961 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2383,6 +2383,7 @@ def load_config(
# keyring stays the secure path whenever it is functional (the file backend is
# installed ONLY when the current backend is the no-op fail.Keyring).
_KEYRING_BACKEND_READY: bool = False
+_FILE_BACKEND_ACTIVE: bool = False
class _FileCredStore:
@@ -2431,24 +2432,24 @@ class _FileCredStore:
self._save(data)
-def _ensure_keyring_backend() -> None:
- """Install the local-file credential store when the OS keyring is non-functional.
+def _install_file_cred_backend(reason: str) -> bool:
+ """Force the local 0600 file credential store as the active keyring backend.
- Runs once. Installs the file backend ONLY when the current backend is the no-op
- ``fail.Keyring`` (so a working Windows/macOS/Linux OS keyring is never replaced).
- Any error is swallowed — a missing keyring must never break boot.
+ Used both when NO OS keyring exists at all (headless VPS → ``fail.Keyring``)
+ AND when a reachable-but-unusable OS keyring RAISES at runtime — e.g. a Linux
+ Secret Service that is present but whose collection is LOCKED, which
+ ``keyring.get_keyring()`` still reports as a viable backend, so the
+ ``fail.Keyring`` check alone never engages the fallback. Idempotent: safe to
+ call repeatedly (it just re-sets the same backend); the swap is logged once.
+ The OS keyring stays the secure path whenever it is functional — the file
+ backend is installed only when the real one is absent or provably broken.
+
+ Returns True iff the file backend is now active.
"""
- global _KEYRING_BACKEND_READY
- if _KEYRING_BACKEND_READY:
- return
- _KEYRING_BACKEND_READY = True
+ global _FILE_BACKEND_ACTIVE
try:
import keyring
import keyring.backend
- from keyring.backends import fail
-
- if not isinstance(keyring.get_keyring(), fail.Keyring):
- return
_store = _FileCredStore()
@@ -2465,11 +2466,38 @@ def _ensure_keyring_backend() -> None:
_store.delete(service, username)
keyring.set_keyring(_FileKeyringBackend())
- logging.getLogger(__name__).warning(
- "No OS credential store available (headless host) — API keys are stored "
- "in a local 0600 file under %s. Configure a Secret Service / Keychain "
- "for OS-encrypted storage.", DATA_DIR / "credentials.json",
- )
+ if not _FILE_BACKEND_ACTIVE:
+ logging.getLogger(__name__).warning(
+ "OS credential store unusable (%s) — API keys are stored in a local "
+ "0600 file under %s. Configure a Secret Service / Keychain for "
+ "OS-encrypted storage.", reason, DATA_DIR / "credentials.json",
+ )
+ _FILE_BACKEND_ACTIVE = True
+ return True
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _ensure_keyring_backend() -> None:
+ """Install the local-file credential store when the OS keyring is non-functional.
+
+ Runs once. Installs the file backend when the current backend is the no-op
+ ``fail.Keyring`` (no OS keyring at all — the headless VPS case). A
+ reachable-but-LOCKED keyring that only reveals itself by RAISING on a real
+ read/write is handled at runtime by ``get_secret``/``set_secret``/
+ ``delete_secret`` via ``_install_file_cred_backend``. Any error is swallowed —
+ a missing keyring must never break boot.
+ """
+ global _KEYRING_BACKEND_READY
+ if _KEYRING_BACKEND_READY:
+ return
+ _KEYRING_BACKEND_READY = True
+ try:
+ import keyring
+ from keyring.backends import fail
+
+ if isinstance(keyring.get_keyring(), fail.Keyring):
+ _install_file_cred_backend("no OS credential store available (headless host)")
except Exception: # noqa: BLE001
pass
@@ -2498,8 +2526,19 @@ def get_secret(key: str, env_fallback: str | None = None) -> str | None:
if val:
return val
except Exception: # noqa: BLE001
- # keyring failed — silent fallback to env
- pass
+ # A reachable-but-locked OS keyring raises here even though
+ # _ensure_keyring_backend saw a viable backend. Degrade to the 0600 file
+ # store and retry once, so a key saved to the file fallback in a prior run
+ # is still visible instead of dead-ending on the locked keyring.
+ if _install_file_cred_backend("keyring read failed"):
+ try:
+ import keyring
+
+ val = keyring.get_password(KEYRING_SERVICE, key)
+ if val:
+ return val
+ except Exception: # noqa: BLE001
+ pass
if env_fallback and (val := os.environ.get(env_fallback)):
return val
@@ -2597,7 +2636,19 @@ def set_secret(key: str, value: str) -> bool:
keyring.set_password(KEYRING_SERVICE, key, value)
return True
- except Exception: # noqa: BLE001
+ except Exception as exc: # noqa: BLE001
+ # A reachable-but-unusable OS keyring (e.g. a locked Linux Secret Service)
+ # raises even though _ensure_keyring_backend saw a viable backend. Degrade
+ # to the 0600 file store and retry once, so in-app key save never 500s and
+ # the credential actually persists (CLAUDE.md §3, recoverable in-app).
+ if _install_file_cred_backend(f"keyring write failed: {exc!r}"):
+ try:
+ import keyring
+
+ keyring.set_password(KEYRING_SERVICE, key, value)
+ return True
+ except Exception: # noqa: BLE001
+ return False
return False
@@ -2610,6 +2661,16 @@ def delete_secret(key: str) -> bool:
keyring.delete_password(KEYRING_SERVICE, key)
return True
except Exception: # noqa: BLE001
+ # Locked/unusable OS keyring: degrade to the file store and retry, so a
+ # file-stored credential is actually removed rather than left stale.
+ if _install_file_cred_backend("keyring delete failed"):
+ try:
+ import keyring
+
+ keyring.delete_password(KEYRING_SERVICE, key)
+ return True
+ except Exception: # noqa: BLE001
+ return False
return False
diff --git a/tests/unit/core/test_secret_locked_keyring.py b/tests/unit/core/test_secret_locked_keyring.py
new file mode 100644
index 0000000000..fbf4dcf035
--- /dev/null
+++ b/tests/unit/core/test_secret_locked_keyring.py
@@ -0,0 +1,81 @@
+"""In-app secret save must survive a viable-but-LOCKED OS keyring (headless Linux).
+
+The pure-headless case (no D-Bus at all -> keyring resolves to ``fail.Keyring``)
+already degrades to the 0600 file store. But on a Linux host where a Secret
+Service IS reachable yet its collection is LOCKED (a common SSH / auto-login /
+partial-D-Bus container session), ``keyring.get_keyring()`` returns a viable
+SecretService backend, NOT ``fail.Keyring`` — so the old fallback that only
+engaged for ``fail.Keyring`` was skipped, ``keyring.set_password`` raised
+``KeyringLocked``, and ``set_secret`` returned False. The in-app POST
+``/secrets/{key}`` route turns that into HTTP 500, so pasting a key in the UI
+failed and nothing persisted. A locked/unusable OS keyring must degrade to the
+file store at RUNTIME, keeping the "recoverable in-app" guarantee (CLAUDE.md §3).
+"""
+from __future__ import annotations
+
+import keyring
+import keyring.backend
+import pytest
+from keyring.errors import KeyringLocked
+
+from jarvis.core import config as c
+
+
+class _LockedKeyring(keyring.backend.KeyringBackend):
+ """A reachable OS keyring whose collection is locked: raises on every op.
+
+ Deliberately NOT ``fail.Keyring`` — that is exactly the case the old
+ ``isinstance(..., fail.Keyring)`` gate missed.
+ """
+
+ priority = 5 # type: ignore[assignment]
+
+ def get_password(self, service: str, username: str) -> str | None:
+ raise KeyringLocked("collection is locked")
+
+ def set_password(self, service: str, username: str, password: str) -> None:
+ raise KeyringLocked("collection is locked")
+
+ def delete_password(self, service: str, username: str) -> None:
+ raise KeyringLocked("collection is locked")
+
+
+def locked_os_keyring(monkeypatch, tmp_path):
+ """Install a locked (non-fail) OS keyring; file store writes under tmp."""
+ original = keyring.get_keyring()
+ keyring.set_keyring(_LockedKeyring())
+ monkeypatch.setattr(c, "DATA_DIR", tmp_path)
+ monkeypatch.setattr(c, "_KEYRING_BACKEND_READY", False)
+ if hasattr(c, "_FILE_BACKEND_ACTIVE"):
+ monkeypatch.setattr(c, "_FILE_BACKEND_ACTIVE", False)
+ try:
+ yield tmp_path
+ finally:
+ keyring.set_keyring(original)
+
+
+def test_set_secret_degrades_to_file_store_on_locked_keyring(locked_os_keyring) -> None:
+ # Old behaviour: returns False (KeyringLocked swallowed) -> HTTP 500 upstream.
+ assert c.set_secret("probe_locked_key", "v-123") is True
+ # And the value must persist + read back through the same file fallback.
+ assert c.get_secret("probe_locked_key") == "v-123"
+ # It must have landed in the 0600 file store, not silently vanished.
+ assert (locked_os_keyring / "credentials.json").exists()
+
+
+def test_get_secret_reads_file_store_on_locked_keyring(locked_os_keyring) -> None:
+ # A prior run saved to the file store; a NEW process boots with the same locked
+ # keyring (backend not yet swapped). get_secret must degrade to the file store
+ # and still find the key instead of dead-ending on the locked OS keyring.
+ store = c._FileCredStore()
+ store.set(c.KEYRING_SERVICE, "prior_key", "prior-val")
+ assert c.get_secret("prior_key") == "prior-val"
+
+
+def test_delete_secret_degrades_to_file_store_on_locked_keyring(locked_os_keyring) -> None:
+ store = c._FileCredStore()
+ store.set(c.KEYRING_SERVICE, "del_prior", "y")
+ # Old behaviour: keyring.delete_password raises -> returns False, value stays.
+ assert c.delete_secret("del_prior") is True
+ assert c.get_secret("del_prior") is None