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(secrets): macOS Keychain dialog storm — route the secret vault through the Apple-signed security CLI

Personal Jarvis Maintainere717b5cef883
diff --git a/docs/BUGS.md b/docs/BUGS.md
index bed16a9908..8c69e6e3b1 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -7119,14 +7119,51 @@ authenticity"), one per stored provider key — the pre-boot key check reads
~10 slots, and the unsigned venv python keeps "Always allow" from sticking
durably across binary updates.
-**Fix (`jarvis/core/keychain_bundle.py`).** On macOS the platform keyring
-backend is wrapped in `DarwinBundleKeyringBackend`: ALL Jarvis secrets live
-in ONE Keychain item (`__jarvis_vault__`, JSON map) with a process-local
-cache. One item → one dialog → one "Always allow", ever. Legacy per-key
-items migrate into the vault on first read and are deleted so they stop
-prompting. Malformed vault JSON self-disables the wrapper (delegates to the
-inner backend, never destroys data); migration errors fail open. Windows
-and Linux paths are untouched (`sys.platform == "darwin"` gates every
-wrap); the existing write/read/delete backend probe runs THROUGH the
-wrapper, proving the vault lifecycle. Guards:
+**Fix v1 (`jarvis/core/keychain_bundle.py`) — shipped broken, twice over.**
+On macOS the platform keyring backend is wrapped in
+`DarwinBundleKeyringBackend`: ALL Jarvis secrets live in ONE Keychain item
+(`__jarvis_vault__`, JSON map) with a process-local cache. Legacy per-key
+items migrate into the vault on first read and are deleted. Two independent
+reasons this never stopped the storm:
+
+1. **The wrapper never installed.** It was a plain class, but
+ `keyring.set_keyring` type-checks against `keyring.backend.KeyringBackend`
+ and raised `TypeError` — which the fail-open boot path swallowed, leaving
+ the raw per-item backend silently active. The unit tests called the
+ wrapper directly and never went through `set_keyring`, so they stayed
+ green while production behavior was unchanged.
+2. **One item is still one dialog per PROCESS, forever.** Since macOS Sierra
+ a Keychain item carries a partition list: even an "any application may
+ read" ACL silently admits only Apple-signed tools (verified empirically —
+ an in-process `SecItemCopyMatching` from the unsigned uv/venv python
+ blocks on the consent dialog even for a `-A` item). "Always Allow" binds
+ to a code signature the interpreter does not have, so the grant can never
+ stick: every fresh python process (main app, mission worker, CLI, pytest)
+ re-prompts.
+
+**Fix v2 (same module).** `DarwinBundleKeyringBackend` is now a real
+`KeyringBackend` subclass (guarded by
+`test_wrapper_is_accepted_by_keyring_set_keyring`, which installs it through
+the real `keyring` API), and the vault item's I/O goes through the
+Apple-signed `/usr/bin/security` CLI (`SecurityCliVault`): items are created
+via `security -i add-generic-password -A` (payload streamed over stdin,
+never argv, stored as base64 JSON), read via `find-generic-password -w`,
+replaced delete-then-add. An Apple-signed tool inside the `apple-tool:`
+partition reads/writes a `-A` item with ZERO dialogs, from any process,
+regardless of interpreter signing — verified silent end-to-end on the Mac.
+Base64 doubles as the format marker: a plain-JSON vault (written by the v1
+in-process path) is upgraded to a fresh `-A` item on first CLI read.
+Tradeoff, stated honestly: a `-A` item is readable by any local process
+running as the user — the same trust level as the project's 0600 file-store
+fallback — while staying Keychain-encrypted at rest. Any CLI failure falls
+back to the v1 in-process behavior, never losing data. Reading each
+still-existing legacy per-key item needs the user's consent ONE last time
+(migration), after which it is deleted and never prompts again. Direct
+`keyring` users (`jarvis/board/sync.py`, `jarvis/plugins/stt/groq_api.py`)
+now run `_ensure_keyring_backend()` first so they cannot bypass the vault.
+Windows and Linux paths are untouched (`sys.platform == "darwin"` gates
+every wrap, and `darwin_security_cli_vault()` returns `None` elsewhere);
+the write/read/delete backend probe runs THROUGH the wrapper, proving the
+vault lifecycle. Linux-simulation tests force `sys.platform = "linux"` so
+they can never route into the real Mac Keychain. Guards:
`tests/unit/core/test_keychain_bundle.py`.
diff --git a/jarvis/board/sync.py b/jarvis/board/sync.py
index d348b8310e..008ddc9c25 100644
--- a/jarvis/board/sync.py
+++ b/jarvis/board/sync.py
@@ -96,6 +96,16 @@ class _KeyringBackend:
"""
def __init__(self) -> None:
+ try:
+ # Route through the central backend setup first: on macOS this
+ # installs the single-vault-item wrapper (BUG-103), so board
+ # secrets never become per-item Keychain entries that each pop
+ # their own permission dialog.
+ from jarvis.core.config import _ensure_keyring_backend
+
+ _ensure_keyring_backend()
+ except Exception: # noqa: BLE001, S110 -- keyring stays best-effort here
+ pass
try:
import keyring
self._kr = keyring
@@ -280,7 +290,10 @@ class SyncClient:
log.info("board sync: registered as %s...", self._pubkey_hex[:8])
return True
if resp.status_code in (401, 403):
- log.warning("board sync: register rejected (%s) — admin_token korrekt?", resp.status_code)
+ log.warning(
+ "board sync: register rejected (%s) — is admin_token correct?",
+ resp.status_code,
+ )
return False
log.warning("board sync: register failed status=%s body=%s",
resp.status_code, resp.text[:200])
diff --git a/jarvis/core/keychain_bundle.py b/jarvis/core/keychain_bundle.py
index 1897e44fdd..d2a88b08cf 100644
--- a/jarvis/core/keychain_bundle.py
+++ b/jarvis/core/keychain_bundle.py
@@ -10,9 +10,33 @@ storm of 5-10+ dialogs on every single boot.
``DarwinBundleKeyringBackend`` wraps the platform-detected keyring backend
(composition, not a registered ``keyring`` plugin) and collapses every
secret into ONE Keychain item — account name ``__jarvis_vault__`` — holding
-a JSON object that maps key -> value. The user clicks "Always Allow" exactly
-once for that single item; every later get/set/delete is served from an
-in-process cache with no further per-item OS prompt.
+a JSON object that maps key -> value. Every later get/set/delete is served
+from an in-process cache with no further per-item OS prompt.
+
+**Why one item is still not enough (the v2 layer).** Since macOS Sierra a
+Keychain item also carries a *partition list*: even an item whose ACL says
+"any application may read" silently admits only Apple-signed tools; every
+unsigned binary (the venv python) still triggers the confirmation dialog —
+and because "Always Allow" is bound to a code signature the unsigned
+interpreter does not have, the grant never sticks. Each fresh python
+process (main app, mission worker, CLI, pytest) then re-prompts once per
+boot. The fix: route the vault item's I/O through ``/usr/bin/security`` —
+an Apple-signed tool inside the ``apple-tool:`` partition — and create the
+item with the "allow any application" ACL (``add-generic-password -A``).
+Items written that way are readable and writable via the CLI with ZERO
+dialogs, from any process, forever, regardless of interpreter signing.
+
+Security tradeoff, stated honestly: a ``-A`` item is readable by any local
+process running as the user (same trust level as this project's 0600
+file-store fallback), while remaining Keychain-encrypted at rest and locked
+with the keychain. The alternative was an unfixable per-process dialog
+storm, because an unsigned interpreter can never hold a durable grant.
+
+Secrets never appear on a command line: writes stream the payload to
+``security -i`` via stdin, reads receive it on stdout. The payload is the
+base64-encoded JSON bundle — base64 doubles as the format marker that the
+item was already rewritten with the ``-A`` ACL (plain JSON means a
+keyring-written legacy vault that still needs the one-time upgrade).
Windows and Linux never construct this class: ``jarvis/core/config.py`` only
wraps the platform backend when ``sys.platform == "darwin"``, so their
@@ -21,8 +45,13 @@ per-item keyring behavior is byte-identical to before this module existed.
from __future__ import annotations
+import base64
+import binascii
import json
import logging
+import re
+import subprocess
+import sys
import threading
from typing import Any
@@ -34,25 +63,194 @@ logger = logging.getLogger(__name__)
# shape also makes it obviously internal in the macOS Keychain Access UI.
VAULT_ACCOUNT = "__jarvis_vault__"
+_SECURITY_BIN = "/usr/bin/security"
+# ``security`` exits 44 (errSecItemNotFound) when the queried item is absent —
+# probed empirically; the only non-zero exit treated as a clean "no value".
+_SECURITY_NOT_FOUND_EXIT = 44
+# Tokens interpolated into a ``security -i`` command line. Service and account
+# names are fixed internal constants ("personal-jarvis", "__jarvis_vault__");
+# anything outside this conservative charset falls back to the inner backend
+# rather than risking the CLI's whitespace/quote parsing.
+_SAFE_CLI_TOKEN = re.compile(r"^[A-Za-z0-9._-]+$")
+# The written payload is standard base64 (never starts with ``-``, contains no
+# whitespace/quotes), so it is safe on a ``security -i`` line after ``-w``.
+_SAFE_CLI_VALUE = re.compile(r"^[A-Za-z0-9+/=]+$")
+
+
+class SecurityCliVaultError(RuntimeError):
+ """A ``security`` CLI vault operation failed (denied, timed out, crashed)."""
+
+
+class SecurityCliVault:
+ """Vault-item I/O through the Apple-signed ``/usr/bin/security`` tool.
+
+ Only the single bundled vault item goes through this store. Reads may
+ legitimately BLOCK on one interactive dialog exactly once — when the
+ vault item was originally written in-process by ``keyring`` (python ACL)
+ and the CLI needs the user's one-time consent to migrate it — so the
+ read timeout is generous. Writes and deletes only ever touch the
+ CLI-created ``-A`` item (or a deletable legacy one) and never prompt.
+ """
+
+ _READ_TIMEOUT_S = 180.0 # may wait on the ONE interactive upgrade consent
+ _WRITE_TIMEOUT_S = 20.0
+
+ def __init__(self, binary: str = _SECURITY_BIN) -> None:
+ self._binary = binary
+
+ @staticmethod
+ def _creationflags() -> int:
+ # AP-1 discipline; the constant is 0 on POSIX, and this class only
+ # ever runs on macOS anyway.
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ return NO_WINDOW_CREATIONFLAGS
+
+ @staticmethod
+ def _check_tokens(*tokens: str) -> None:
+ for token in tokens:
+ if not _SAFE_CLI_TOKEN.match(token):
+ raise SecurityCliVaultError(
+ f"unsafe token for security CLI interpolation: {token!r}"
+ )
+
+ def read(self, service: str, account: str) -> str | None:
+ """Return the stored payload, ``None`` if absent, raise on denial."""
+ self._check_tokens(service, account)
+ try:
+ proc = subprocess.run( # noqa: S603 -- fixed Apple-signed binary
+ [self._binary, "find-generic-password", "-s", service,
+ "-a", account, "-w"],
+ capture_output=True,
+ text=True,
+ timeout=self._READ_TIMEOUT_S,
+ creationflags=self._creationflags(),
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ raise SecurityCliVaultError(f"security CLI read failed: {exc}") from exc
+ if proc.returncode == 0:
+ return proc.stdout.rstrip("\n")
+ if proc.returncode == _SECURITY_NOT_FOUND_EXIT:
+ return None
+ raise SecurityCliVaultError(
+ f"security CLI read exited {proc.returncode}: {proc.stderr.strip()!r}"
+ )
+
+ def write(self, service: str, account: str, value: str) -> None:
+ """Replace the vault item with a fresh any-application-ACL copy.
+
+ Delete-then-add: updating an item in place would need the OLD item's
+ ACL consent, while deleting never decrypts (always silent) and the
+ fresh ``-A`` item admits every later CLI access without a dialog.
+ The payload streams through stdin (``security -i``), never argv.
+ """
+ self._check_tokens(service, account)
+ if not _SAFE_CLI_VALUE.match(value):
+ raise SecurityCliVaultError(
+ "vault payload is not clean base64; refusing CLI interpolation"
+ )
+ self.delete(service, account)
+ command = (
+ f"add-generic-password -U -A -s {service} -a {account} -w {value}\n"
+ )
+ try:
+ proc = subprocess.run( # noqa: S603 -- fixed Apple-signed binary
+ [self._binary, "-i"],
+ input=command,
+ capture_output=True,
+ text=True,
+ timeout=self._WRITE_TIMEOUT_S,
+ creationflags=self._creationflags(),
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ raise SecurityCliVaultError(f"security CLI write failed: {exc}") from exc
+ if proc.returncode != 0:
+ raise SecurityCliVaultError(
+ f"security CLI write exited {proc.returncode}: {proc.stderr.strip()!r}"
+ )
+ # ``security -i`` can swallow a failing sub-command's exit status;
+ # trust only a verified read-back.
+ if self.read(service, account) != value:
+ raise SecurityCliVaultError("security CLI write read-back mismatch")
+
+ def delete(self, service: str, account: str) -> None:
+ """Best-effort silent delete; absence is not an error."""
+ self._check_tokens(service, account)
+ try:
+ subprocess.run( # noqa: S603 -- fixed Apple-signed binary
+ [self._binary, "delete-generic-password", "-s", service,
+ "-a", account],
+ capture_output=True,
+ text=True,
+ timeout=self._WRITE_TIMEOUT_S,
+ creationflags=self._creationflags(),
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ raise SecurityCliVaultError(f"security CLI delete failed: {exc}") from exc
+
+
+def darwin_security_cli_vault() -> SecurityCliVault | None:
+ """Return the CLI vault store when this host can use it, else ``None``.
+
+ ``None`` (not darwin, or no ``security`` binary) keeps the wrapper on its
+ pure in-process keyring behavior — exactly what every unit test that
+ constructs ``DarwinBundleKeyringBackend(fake_inner)`` relies on.
+ """
+ if sys.platform != "darwin":
+ return None
+ import os
+
+ if not os.path.exists(_SECURITY_BIN):
+ return None
+ return SecurityCliVault()
+
+
+try:
+ # ``keyring.set_keyring`` type-checks against this base class — a plain
+ # object is rejected with ``TypeError`` (which the fail-open boot path
+ # swallowed, silently leaving the raw per-item backend active: the v1
+ # regression that kept the dialog storm alive). Subclass it whenever the
+ # package is present; fall back to ``object`` so this module still
+ # imports without ``keyring`` installed.
+ from keyring.backend import KeyringBackend as _KeyringBackendBase
+except ImportError: # pragma: no cover -- keyring is present in every dev env
+ _KeyringBackendBase = object # type: ignore[assignment, misc]
+
-class DarwinBundleKeyringBackend:
+class DarwinBundleKeyringBackend(_KeyringBackendBase): # type: ignore[valid-type, misc]
"""Wrap an inner keyring backend, collapsing all secrets into one item.
- Only implements the three methods ``jarvis/core/config.py`` calls through
+ Implements the three methods ``jarvis/core/config.py`` calls through
the process-global ``keyring`` module —
``get_password(service, key)``, ``set_password(service, key, value)``,
``delete_password(service, key)`` — so any object exposing that trio (a
- real platform backend, or a fake in tests) can be wrapped.
+ real platform backend, or a fake in tests) can be wrapped. MUST remain a
+ ``keyring.backend.KeyringBackend`` subclass: ``keyring.set_keyring``
+ rejects anything else, and the boot path treats that rejection as a
+ swallowed no-op.
"""
+ # Above every real platform backend (macOS Keychain announces 5), though
+ # the wrapper is only ever installed explicitly via ``set_keyring``,
+ # never through priority-based discovery (its ctor needs ``inner``, so
+ # discovery instantiation fails harmlessly).
+ priority = 6.0 # type: ignore[assignment]
+
# Lets ``config._is_platform_keyring_backend`` recognize this wrapper as
# a platform backend by delegating the check to the wrapped instance,
# instead of inspecting class/module names against an unpinned library
# (AP-28).
_jarvis_platform_wrapper = True
- def __init__(self, inner: Any) -> None:
+ def __init__(self, inner: Any, cli: SecurityCliVault | None = None) -> None:
+ if _KeyringBackendBase is not object:
+ super().__init__()
self._inner = inner
+ # When present, vault-item reads/writes go through the Apple-signed
+ # ``security`` CLI (partition-list-proof, zero dialogs once the item
+ # carries the ``-A`` ACL). ``None`` — the default, and what every
+ # fake-backed unit test gets — keeps pure in-process keyring I/O.
+ self._cli = cli
self._lock = threading.Lock()
# Per-service cache of the parsed vault dict. Keyed by ``service``
# because a single wrapper instance could in principle see more than
@@ -68,6 +266,30 @@ class DarwinBundleKeyringBackend:
# -- internal helpers ---------------------------------------------------
+ @staticmethod
+ def _decode_vault_payload(raw: str) -> tuple[dict[str, Any] | None, bool]:
+ """Parse a stored vault payload.
+
+ Returns ``(bundle, was_base64)``; ``(None, False)`` when malformed.
+ Plain JSON is the legacy in-process ``keyring`` format; base64-wrapped
+ JSON marks an item already rewritten through the ``security`` CLI
+ with the any-application ACL. The two are unambiguous: JSON of an
+ object starts with ``{``, which is outside the base64 alphabet, and
+ base64 text can never parse as a JSON object.
+ """
+ try:
+ parsed = json.loads(raw)
+ except ValueError:
+ parsed = None
+ if parsed is not None:
+ return (parsed, False) if isinstance(parsed, dict) else (None, False)
+ try:
+ decoded = base64.b64decode(raw, validate=True).decode("utf-8")
+ parsed = json.loads(decoded)
+ except (ValueError, binascii.Error, UnicodeDecodeError):
+ return None, False
+ return (parsed, True) if isinstance(parsed, dict) else (None, False)
+
def _load_locked(self, service: str) -> dict[str, str]:
"""Return the parsed vault dict for *service*, loading it once.
@@ -78,16 +300,27 @@ class DarwinBundleKeyringBackend:
cached = self._cache.get(service)
if cached is not None:
return cached
- raw = self._inner.get_password(service, VAULT_ACCOUNT)
+ raw: str | None = None
+ used_cli = False
+ if self._cli is not None:
+ try:
+ raw = self._cli.read(service, VAULT_ACCOUNT)
+ used_cli = True
+ except Exception: # noqa: BLE001 -- CLI oddity must not hide the vault
+ logger.warning(
+ "security CLI vault read failed; falling back to the "
+ "in-process keyring read (which may show one Keychain "
+ "dialog).",
+ exc_info=True,
+ )
+ if not used_cli:
+ raw = self._inner.get_password(service, VAULT_ACCOUNT)
if raw is None:
bundle: dict[str, str] = {}
self._cache[service] = bundle
return bundle
- try:
- parsed = json.loads(raw)
- if not isinstance(parsed, dict):
- raise ValueError("Jarvis Keychain vault item is not a JSON object")
- except Exception: # noqa: BLE001 -- any parse failure disables the bundle
+ parsed, was_base64 = self._decode_vault_payload(raw)
+ if parsed is None:
logger.warning(
"macOS Keychain vault item %r is malformed; falling back to "
"per-item Keychain storage for the rest of this process. The "
@@ -98,11 +331,35 @@ class DarwinBundleKeyringBackend:
return {}
bundle = {str(k): str(v) for k, v in parsed.items()}
self._cache[service] = bundle
+ if used_cli and not was_base64:
+ # A keyring-written legacy vault, just read through the CLI (the
+ # one-time consent dialog, if any, already happened). Rewrite it
+ # with the any-application ACL so no process ever prompts again.
+ try:
+ self._save_locked(service, bundle)
+ except Exception: # noqa: BLE001 -- upgrade is best-effort
+ logger.warning(
+ "one-time Keychain vault ACL upgrade failed; the next "
+ "process may still see a Keychain dialog.",
+ exc_info=True,
+ )
return bundle
def _save_locked(self, service: str, bundle: dict[str, str]) -> None:
"""Persist *bundle* as the single vault item. Caller holds the lock."""
- self._inner.set_password(service, VAULT_ACCOUNT, json.dumps(bundle))
+ payload = json.dumps(bundle)
+ if self._cli is not None:
+ try:
+ encoded = base64.b64encode(payload.encode("utf-8")).decode("ascii")
+ self._cli.write(service, VAULT_ACCOUNT, encoded)
+ return
+ except Exception: # noqa: BLE001 -- CLI failure degrades, never loses
+ logger.warning(
+ "security CLI vault write failed; falling back to the "
+ "in-process keyring write (per-app ACL, may prompt).",
+ exc_info=True,
+ )
+ self._inner.set_password(service, VAULT_ACCOUNT, payload)
@staticmethod
def _raise_missing_password_error(service: str, key: str) -> None:
diff --git a/jarvis/plugins/stt/groq_api.py b/jarvis/plugins/stt/groq_api.py
index 1ebc9a4486..24cc37bd28 100644
--- a/jarvis/plugins/stt/groq_api.py
+++ b/jarvis/plugins/stt/groq_api.py
@@ -212,6 +212,16 @@ class GroqWhisperAPI:
def _read_keyring_secret(service: str, username: str) -> str:
"""Best-effort Credential-Manager lookup. Returns ``""`` on any failure."""
+ try:
+ # Central backend setup first: on macOS this installs the
+ # single-vault-item wrapper (BUG-103) so this read is served from the
+ # bundled vault instead of a per-item Keychain entry with its own
+ # permission dialog.
+ from jarvis.core.config import _ensure_keyring_backend
+
+ _ensure_keyring_backend()
+ except Exception: # noqa: BLE001, S110 -- lookup stays best-effort
+ pass
try:
import keyring # type: ignore[import-not-found]
except ImportError:
diff --git a/tests/unit/core/test_keychain_bundle.py b/tests/unit/core/test_keychain_bundle.py
index d323775f3b..3e75a4c834 100644
--- a/tests/unit/core/test_keychain_bundle.py
+++ b/tests/unit/core/test_keychain_bundle.py
@@ -10,14 +10,52 @@ OS -- the wrapper class itself has no platform gate; that gate lives only in
from __future__ import annotations
+import base64
+import json
+
import pytest
from keyring.errors import PasswordDeleteError
-from jarvis.core.keychain_bundle import VAULT_ACCOUNT, DarwinBundleKeyringBackend
+from jarvis.core.keychain_bundle import (
+ VAULT_ACCOUNT,
+ DarwinBundleKeyringBackend,
+ SecurityCliVault,
+ SecurityCliVaultError,
+)
SERVICE = "personal-jarvis"
+def _b64(payload: dict[str, str]) -> str:
+ return base64.b64encode(json.dumps(payload).encode("utf-8")).decode("ascii")
+
+
+class FakeSecurityCli:
+ """In-memory stand-in for the ``security`` CLI vault store."""
+
+ def __init__(self) -> None:
+ self.items: dict[tuple[str, str], str] = {}
+ self.calls: list[tuple[str, ...]] = []
+ self.fail_reads = False
+ self.fail_writes = False
+
+ def read(self, service: str, account: str) -> str | None:
+ self.calls.append(("read", service, account))
+ if self.fail_reads:
+ raise SecurityCliVaultError("simulated CLI read failure")
+ return self.items.get((service, account))
+
+ def write(self, service: str, account: str, value: str) -> None:
+ self.calls.append(("write", service, account))
+ if self.fail_writes:
+ raise SecurityCliVaultError("simulated CLI write failure")
+ self.items[(service, account)] = value
+
+ def delete(self, service: str, account: str) -> None:
+ self.calls.append(("delete", service, account))
+ self.items.pop((service, account), None)
+
+
class FakeInnerBackend:
"""Minimal per-item keyring backend, matching real backend semantics:
``get_password`` returns ``None`` for a missing item, ``delete_password``
@@ -241,3 +279,186 @@ def test_probe_lifecycle_passes_through_wrapper(
bundle.delete_password(SERVICE, probe_key)
assert bundle.get_password(SERVICE, probe_key) is None
+
+
+# ---------------------------------------------------------------------------
+# security-CLI vault store (BUG-103 v2: partition-list-proof zero-dialog path).
+# ---------------------------------------------------------------------------
+
+
+def cli() -> FakeSecurityCli:
+ return FakeSecurityCli()
+
+
+def cli_bundle(
+ inner: FakeInnerBackend, cli: FakeSecurityCli
+) -> DarwinBundleKeyringBackend:
+ return DarwinBundleKeyringBackend(inner, cli=cli)
+
+
+def test_cli_saves_write_base64_vault_and_never_touch_inner(
+ cli_bundle: DarwinBundleKeyringBackend,
+ inner: FakeInnerBackend,
+ cli: FakeSecurityCli,
+) -> None:
+ cli_bundle.set_password(SERVICE, "anthropic_api_key", "sk-ant-1")
+ cli_bundle.set_password(SERVICE, "groq_api_key", "gsk-2")
+
+ assert inner.values == {}, "with a working CLI the inner keyring stays untouched"
+ raw = cli.items[(SERVICE, VAULT_ACCOUNT)]
+ decoded = json.loads(base64.b64decode(raw, validate=True))
+ assert decoded == {"anthropic_api_key": "sk-ant-1", "groq_api_key": "gsk-2"}
+
+
+def test_cli_base64_vault_roundtrips_across_wrapper_instances(
+ inner: FakeInnerBackend, cli: FakeSecurityCli
+) -> None:
+ first = DarwinBundleKeyringBackend(inner, cli=cli)
+ first.set_password(SERVICE, "groq_api_key", "gsk-secret")
+
+ second = DarwinBundleKeyringBackend(inner, cli=cli)
+ assert second.get_password(SERVICE, "groq_api_key") == "gsk-secret"
+
+
+def test_legacy_plain_json_vault_read_via_cli_is_upgraded_to_base64(
+ cli_bundle: DarwinBundleKeyringBackend, cli: FakeSecurityCli
+) -> None:
+ # A vault item written by the in-process keyring path (plain JSON, per-app
+ # ACL) that the CLI can read after the user's one-time consent.
+ cli.items[(SERVICE, VAULT_ACCOUNT)] = json.dumps({"telegram_bot_token": "123:t"})
+
+ assert cli_bundle.get_password(SERVICE, "telegram_bot_token") == "123:t"
+
+ raw = cli.items[(SERVICE, VAULT_ACCOUNT)]
+ decoded = json.loads(base64.b64decode(raw, validate=True))
+ assert decoded == {"telegram_bot_token": "123:t"}, (
+ "the plain-JSON vault must be rewritten base64-encoded through the "
+ "CLI (fresh -A ACL) on first read"
+ )
+
+
+def test_cli_write_failure_falls_back_to_inner_without_data_loss(
+ cli_bundle: DarwinBundleKeyringBackend,
+ inner: FakeInnerBackend,
+ cli: FakeSecurityCli,
+) -> None:
+ cli.fail_writes = True
+
+ cli_bundle.set_password(SERVICE, "openrouter_api_key", "or-3")
+
+ assert json.loads(inner.values[(SERVICE, VAULT_ACCOUNT)]) == {
+ "openrouter_api_key": "or-3"
+ }
+ assert cli_bundle.get_password(SERVICE, "openrouter_api_key") == "or-3"
+
+
+def test_cli_read_failure_falls_back_to_inner_read(
+ cli_bundle: DarwinBundleKeyringBackend,
+ inner: FakeInnerBackend,
+ cli: FakeSecurityCli,
+) -> None:
+ inner.values[(SERVICE, VAULT_ACCOUNT)] = json.dumps({"groq_api_key": "gsk-4"})
+ cli.fail_reads = True
+
+ assert cli_bundle.get_password(SERVICE, "groq_api_key") == "gsk-4"
+
+
+def test_base64_vault_readable_even_without_cli(
+ inner: FakeInnerBackend,
+) -> None:
+ # A CLI-written vault read by a wrapper WITHOUT a CLI store (e.g. the
+ # security binary vanished): the base64 format must still parse.
+ inner.values[(SERVICE, VAULT_ACCOUNT)] = _b64({"anthropic_api_key": "sk-ant-9"})
+
+ bundle = DarwinBundleKeyringBackend(inner)
+ assert bundle.get_password(SERVICE, "anthropic_api_key") == "sk-ant-9"
+
+
+def test_garbage_that_is_neither_json_nor_base64_json_disables_bundle(
+ cli_bundle: DarwinBundleKeyringBackend, cli: FakeSecurityCli
+) -> None:
+ cli.items[(SERVICE, VAULT_ACCOUNT)] = "%%% definitely not a vault %%%"
+
+ assert cli_bundle.get_password(SERVICE, "anthropic_api_key") is None
+ assert cli.items[(SERVICE, VAULT_ACCOUNT)] == "%%% definitely not a vault %%%", (
+ "a malformed vault item must never be destroyed or overwritten"
+ )
+
+
+def test_legacy_per_key_item_migrates_into_cli_vault(
+ cli_bundle: DarwinBundleKeyringBackend,
+ inner: FakeInnerBackend,
+ cli: FakeSecurityCli,
+) -> None:
+ inner.values[(SERVICE, "discord_bot_token")] = "legacy-token"
+
+ assert cli_bundle.get_password(SERVICE, "discord_bot_token") == "legacy-token"
+
+ assert (SERVICE, "discord_bot_token") not in inner.values
+ decoded = json.loads(
+ base64.b64decode(cli.items[(SERVICE, VAULT_ACCOUNT)], validate=True)
+ )
+ assert decoded == {"discord_bot_token": "legacy-token"}
+
+
+def test_probe_lifecycle_passes_through_cli_vault(
+ cli_bundle: DarwinBundleKeyringBackend, cli: FakeSecurityCli
+) -> None:
+ probe_key = "__jarvis_backend_probe__cafebabe"
+ probe_value = "probe-value-456"
+
+ cli_bundle.set_password(SERVICE, probe_key, probe_value)
+ assert cli_bundle.get_password(SERVICE, probe_key) == probe_value
+
+ cli_bundle.delete_password(SERVICE, probe_key)
+ assert cli_bundle.get_password(SERVICE, probe_key) is None
+
+
+# ---------------------------------------------------------------------------
+# SecurityCliVault interpolation guards (no subprocess involved).
+# ---------------------------------------------------------------------------
+
+
+def test_security_cli_vault_rejects_unsafe_service_and_account_tokens() -> None:
+ vault = SecurityCliVault()
+ with pytest.raises(SecurityCliVaultError):
+ vault.read("bad service with spaces", VAULT_ACCOUNT)
+ with pytest.raises(SecurityCliVaultError):
+ vault.read(SERVICE, "account'with'quotes")
+
+
+def test_security_cli_vault_rejects_non_base64_payloads() -> None:
+ vault = SecurityCliVault()
+ with pytest.raises(SecurityCliVaultError):
+ vault.write(SERVICE, VAULT_ACCOUNT, '{"raw": "json is not allowed"}')
+
+
+# ---------------------------------------------------------------------------
+# The wrapper must be installable through the real ``keyring`` module.
+# ---------------------------------------------------------------------------
+
+
+def test_wrapper_is_accepted_by_keyring_set_keyring(
+ inner: FakeInnerBackend,
+) -> None:
+ """``keyring.set_keyring`` type-checks against ``KeyringBackend`` and
+ REJECTS plain classes with ``TypeError``. The boot path swallows that
+ error fail-open, so a rejected wrapper silently leaves the raw per-item
+ backend active and the whole BUG-103 collapse never engages -- exactly
+ the regression that shipped in the first version of this module. This
+ test installs the wrapper through the real ``keyring`` API and proves
+ reads are actually served through it."""
+ import keyring
+
+ original = keyring.get_keyring()
+ try:
+ keyring.set_keyring(DarwinBundleKeyringBackend(inner))
+ keyring.set_password(SERVICE, "anthropic_api_key", "sk-ant-real-path")
+ assert keyring.get_password(SERVICE, "anthropic_api_key") == "sk-ant-real-path"
+ assert {k for k in inner.values if k[0] == SERVICE} == {
+ (SERVICE, VAULT_ACCOUNT)
+ }, "the write must land in the single vault item, not a per-key item"
+ finally:
+ keyring.set_keyring(original)
diff --git a/tests/unit/core/test_secret_locked_keyring.py b/tests/unit/core/test_secret_locked_keyring.py
index a177c0e33f..0932bec746 100644
--- a/tests/unit/core/test_secret_locked_keyring.py
+++ b/tests/unit/core/test_secret_locked_keyring.py
@@ -14,6 +14,8 @@ file store at RUNTIME, keeping the "recoverable in-app" guarantee (CLAUDE.md §3
from __future__ import annotations
+import sys
+
import keyring
import keyring.backend
import pytest
@@ -22,6 +24,17 @@ from keyring.errors import KeyringLocked
from jarvis.core import config as c
[email protected](autouse=True)
+def _force_non_darwin_platform(monkeypatch: pytest.MonkeyPatch) -> None:
+ """These tests simulate a LINUX locked-Secret-Service host; on a real Mac
+ the darwin branch of ``_ensure_keyring_backend`` would otherwise wrap the
+ fake locked backend in ``DarwinBundleKeyringBackend`` with the REAL
+ ``security`` CLI vault store — routing test writes into the developer's
+ actual login Keychain. Same convention as
+ ``test_keyring_backend_recovery.py``."""
+ monkeypatch.setattr(sys, "platform", "linux")
+
+
class _LockedKeyring(keyring.backend.KeyringBackend):
"""A reachable OS keyring whose collection is locked: raises on every op.