fix: APIKeyManager.load crashes app startup on a corrupt/wrong-shape api_keys.json (#1565)

This commit is contained in:
Afonso Coutinho
2026-06-03 00:11:37 +01:00
committed by GitHub
parent 0e6cbd8315
commit c9361262df
2 changed files with 44 additions and 2 deletions
@@ -0,0 +1,32 @@
"""Regression: APIKeyManager.load() must not crash on a corrupt/wrong-shape file.
load() is called during startup (app_initializer). It had no try/except around
`json.load` and called `encrypted_keys.items()` directly, so a corrupt/truncated
api_keys.json raised JSONDecodeError and a legacy list-shaped file raised
AttributeError — both crashing app startup. It now returns {} instead.
"""
from src.api_key_manager import APIKeyManager
def _mgr(tmp_path):
return APIKeyManager(str(tmp_path))
def test_corrupt_json_returns_empty(tmp_path):
(tmp_path / "api_keys.json").write_text("{not valid json", encoding="utf-8")
assert _mgr(tmp_path).load() == {}
def test_list_shape_returns_empty(tmp_path):
(tmp_path / "api_keys.json").write_text('["openai", "anthropic"]', encoding="utf-8")
assert _mgr(tmp_path).load() == {}
def test_missing_file_returns_empty(tmp_path):
assert _mgr(tmp_path).load() == {}
def test_valid_roundtrip(tmp_path):
mgr = _mgr(tmp_path)
mgr.save("openai", "sk-secret")
assert mgr.load() == {"openai": "sk-secret"}