Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(backends): prefer auth.json over V2Config cache for Codex key reuse

cyh8df0c454ee5a
diff --git a/tests/test_codex_api_auth.py b/tests/test_codex_api_auth.py
new file mode 100644
index 000000000..8fb05fdca
--- /dev/null
+++ b/tests/test_codex_api_auth.py
@@ -0,0 +1,115 @@
+"""Tests for ``vibe.api.get_codex_auth`` and ``save_codex_auth``.
+
+Pins two contracts:
+
+- ``get_codex_auth`` must forward the credentials-store fields so the
+ Settings UI can render the keyring warning correctly.
+- ``save_codex_auth`` must prefer the API key on disk over the
+ V2Config cache when no key is supplied in the payload. Reversing this
+ would let a stale cache silently overwrite a freshly-rotated key
+ (e.g. one written by ``codex login --with-api-key`` outside our flow).
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import types
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from vibe import api # noqa: E402
+
+
+def _seed_disk(home: Path, *, api_key: str | None, store: str | None) -> None:
+ codex_home = home / ".codex"
+ codex_home.mkdir(parents=True, exist_ok=True)
+ auth: dict = {}
+ if api_key is not None:
+ auth["OPENAI_API_KEY"] = api_key
+ (codex_home / "auth.json").write_text(json.dumps(auth), encoding="utf-8")
+ toml = ""
+ if store is not None:
+ toml = f'cli_auth_credentials_store = "{store}"\n'
+ (codex_home / "config.toml").write_text(toml, encoding="utf-8")
+
+
+def test_get_codex_auth_forwards_credentials_store_fields(monkeypatch, tmp_path: Path) -> None:
+ """The keyring-warning gate in SettingsCodexProviderPage reads both
+ fields; dropping them silently caused incorrect warnings even when
+ the store was already ``file``."""
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))
+ _seed_disk(tmp_path, api_key="sk-disk", store="file")
+
+ monkeypatch.setattr(api, "load_config", lambda: types.SimpleNamespace(agents=None))
+
+ state = api.get_codex_auth()
+ assert state["credentials_store"] == "file"
+ assert state["file_store_active"] is True
+ assert state["has_api_key"] is True
+
+
+def test_get_codex_auth_defaults_store_to_auto_when_unset(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))
+ _seed_disk(tmp_path, api_key=None, store=None)
+ monkeypatch.setattr(api, "load_config", lambda: types.SimpleNamespace(agents=None))
+
+ state = api.get_codex_auth()
+ assert state["credentials_store"] == "auto"
+ assert state["file_store_active"] is False
+
+
+def test_save_codex_auth_prefers_disk_over_v2config_cache(monkeypatch, tmp_path: Path) -> None:
+ """When the user clicks Save with only base_url filled, we reuse the
+ stored key. If the cached V2Config key is stale (user rotated the
+ key via ``codex login --with-api-key``), trusting the cache writes
+ the old key back into ``auth.json`` — silently reverting working
+ credentials. Disk must win."""
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))
+ _seed_disk(tmp_path, api_key="sk-fresh-on-disk", store="file")
+
+ # Cached V2Config carries a stale key.
+ fake_codex = types.SimpleNamespace(
+ auth_mode="api_key", api_key="sk-stale-from-cache", base_url=None
+ )
+ fake_agents = types.SimpleNamespace(codex=fake_codex)
+ fake_config = types.SimpleNamespace(agents=fake_agents, save=lambda: None)
+ monkeypatch.setattr(api, "load_config", lambda: fake_config)
+ # Don't actually restart the backend in unit tests.
+ monkeypatch.setattr(api, "restart_backend", lambda name: {"ok": True})
+
+ payload = {"auth_mode": "api_key", "api_key": None, "base_url": "https://example/v1"}
+ result = api.save_codex_auth(payload)
+ assert result.get("ok") is True
+
+ # The disk write is authoritative — assert the key on disk is still
+ # the freshly-rotated one, not the stale cache value.
+ auth = json.loads((tmp_path / ".codex" / "auth.json").read_text(encoding="utf-8"))
+ assert auth["OPENAI_API_KEY"] == "sk-fresh-on-disk"
+ # And the V2Config write should reflect the same (disk-sourced) key.
+ assert fake_codex.api_key == "sk-fresh-on-disk"
+
+
+def test_save_codex_auth_falls_back_to_v2config_when_disk_empty(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """Legacy installs may have never written ``auth.json``. The
+ V2Config cache is still a valid fallback in that case."""
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))
+ _seed_disk(tmp_path, api_key=None, store="file")
+
+ fake_codex = types.SimpleNamespace(
+ auth_mode="api_key", api_key="sk-from-cache", base_url=None
+ )
+ fake_agents = types.SimpleNamespace(codex=fake_codex)
+ fake_config = types.SimpleNamespace(agents=fake_agents, save=lambda: None)
+ monkeypatch.setattr(api, "load_config", lambda: fake_config)
+ monkeypatch.setattr(api, "restart_backend", lambda name: {"ok": True})
+
+ payload = {"auth_mode": "api_key", "api_key": None, "base_url": "https://example/v1"}
+ result = api.save_codex_auth(payload)
+ assert result.get("ok") is True
+
+ auth = json.loads((tmp_path / ".codex" / "auth.json").read_text(encoding="utf-8"))
+ assert auth["OPENAI_API_KEY"] == "sk-from-cache"
diff --git a/vibe/api.py b/vibe/api.py
index 043ac3247..9deed5f2e 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2105,6 +2105,14 @@ def get_codex_auth() -> dict:
"api_key_length": int(disk_state.get("api_key_length") or 0),
"base_url": disk_state.get("base_url"),
"has_chatgpt_tokens": bool(disk_state.get("has_chatgpt_tokens")),
+ # Forward the live Codex credentials-store status so the UI can
+ # warn when the user is about to switch storage backends
+ # (Codex's documented default is ``auto`` → keyring-preferred).
+ # Dropping these here was the bug: the React page would treat
+ # ``file_store_active`` as undefined and surface a keyring
+ # warning even when the store is already ``file``.
+ "credentials_store": disk_state.get("credentials_store") or "auto",
+ "file_store_active": bool(disk_state.get("file_store_active")),
}
@@ -2141,25 +2149,27 @@ def save_codex_auth(payload: dict) -> dict:
if auth_mode == "api_key" and not api_key:
# Allow callers to PATCH base_url alone by reusing the stored key.
- # Try V2Config first (typical case after a save via this endpoint),
- # then fall back to ``~/.codex/auth.json`` for keys written outside
- # our flow (e.g. ``codex login --with-api-key`` or pre-Settings
- # installs); the live Codex process reads from there too, so a
- # base-URL-only update must succeed if either source has the key.
- with CONFIG_LOCK:
- try:
- existing = load_config()
- stored = getattr(getattr(existing, "agents", None), "codex", None)
- api_key = getattr(stored, "api_key", None) or None
- except Exception:
- api_key = None
- if not api_key:
- try:
- from vibe.codex_config import read_codex_api_key
+ # ``auth.json`` is the live source Codex reads at launch, and it
+ # captures keys rotated outside this flow (e.g. ``codex login
+ # --with-api-key``). The V2Config cache can be stale relative to
+ # disk, so trusting it first would silently revert a freshly
+ # rotated key when we re-write ``auth.json`` below. Prefer disk;
+ # fall back to V2Config only if disk has nothing (legacy installs
+ # that never wrote ``auth.json``).
+ try:
+ from vibe.codex_config import read_codex_api_key
- api_key = read_codex_api_key()
- except Exception:
- api_key = None
+ api_key = read_codex_api_key()
+ except Exception:
+ api_key = None
+ if not api_key:
+ with CONFIG_LOCK:
+ try:
+ existing = load_config()
+ stored = getattr(getattr(existing, "agents", None), "codex", None)
+ api_key = getattr(stored, "api_key", None) or None
+ except Exception:
+ api_key = None
if not api_key:
return {"ok": False, "message": "api_key is required when auth_mode='api_key'"}