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(claude): harden settings json writes

cyh71200f6bf71f
diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.py
index a6ef51779..b79d77314 100644
--- a/tests/test_settings_disk_fallback.py
+++ b/tests/test_settings_disk_fallback.py
@@ -22,6 +22,7 @@ The fixes:
from __future__ import annotations
import json
+import threading
from pathlib import Path
import pytest
@@ -257,3 +258,60 @@ def test_save_claude_auth_keeps_settings_token_over_legacy_v2_key(
assert settings["env"]["ANTHROPIC_AUTH_TOKEN"] == "token-from-settings"
assert "ANTHROPIC_API_KEY" not in settings["env"]
assert settings["env"]["ANTHROPIC_BASE_URL"] == "https://new-relay.example.invalid"
+
+
+def test_save_claude_auth_fails_without_overwriting_malformed_settings(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))
+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
+ claude_dir = tmp_path / ".claude"
+ claude_dir.mkdir()
+ settings_path = claude_dir / "settings.json"
+ settings_path.write_text('{"model": "claude-sonnet", ', encoding="utf-8")
+
+ from vibe.api import save_claude_auth
+
+ result = save_claude_auth(
+ {
+ "auth_mode": "api_key",
+ "api_key": "sk-new-key",
+ "base_url": "https://relay.example.invalid",
+ }
+ )
+
+ assert result["ok"] is False
+ assert "Expecting property name" in result["message"]
+ assert settings_path.read_text(encoding="utf-8") == '{"model": "claude-sonnet", '
+
+
+def test_apply_claude_auth_uses_unique_temp_files_for_concurrent_writes(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
+
+ from vibe.claude_config import apply_claude_auth
+
+ errors: list[BaseException] = []
+
+ def write_key(index: int) -> None:
+ try:
+ apply_claude_auth(
+ auth_mode="api_key",
+ api_key=f"sk-key-{index}",
+ base_url=f"https://relay-{index}.example.invalid",
+ )
+ except BaseException as exc: # noqa: BLE001
+ errors.append(exc)
+
+ threads = [threading.Thread(target=write_key, args=(index,)) for index in range(8)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+
+ assert errors == []
+ settings = json.loads((tmp_path / ".claude" / "settings.json").read_text())
+ assert settings["env"]["ANTHROPIC_API_KEY"].startswith("sk-key-")
diff --git a/vibe/claude_config.py b/vibe/claude_config.py
index c876cf5f9..7e46ee246 100644
--- a/vibe/claude_config.py
+++ b/vibe/claude_config.py
@@ -23,6 +23,7 @@ from __future__ import annotations
import json
import logging
import os
+import tempfile
from pathlib import Path
from typing import Any, Dict, Optional
@@ -116,11 +117,29 @@ def _load_settings(path: Path) -> Dict[str, Any]:
return {}
+def _load_settings_for_write(path: Path) -> Dict[str, Any]:
+ if not path.exists():
+ return {}
+ data = json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(data, dict):
+ raise ValueError("Claude settings.json must contain a JSON object")
+ return data
+
+
def _atomic_write(path: Path, content: str, *, mode: int = 0o600) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
- tmp = path.with_suffix(path.suffix + ".tmp")
- tmp.write_text(content, encoding="utf-8")
+ fd, tmp_name = tempfile.mkstemp(
+ prefix=f".{path.name}.",
+ suffix=".tmp",
+ dir=str(path.parent),
+ text=True,
+ )
+ tmp = Path(tmp_name)
try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(content)
+ handle.flush()
+ os.fsync(handle.fileno())
os.replace(tmp, path)
finally:
if tmp.exists():
@@ -155,9 +174,7 @@ def apply_claude_auth(
raise ValueError("api_key is required when auth_mode='api_key'")
path = get_claude_settings_path(home)
- settings = _load_settings(path)
- if not isinstance(settings, dict):
- settings = {}
+ settings = _load_settings_for_write(path)
env_block = settings.setdefault("env", {})
if not isinstance(env_block, dict):
env_block = {}