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

View File

@@ -48,8 +48,18 @@ class APIKeyManager:
"""Load and decrypt API keys"""
if not os.path.exists(self.api_keys_file):
return {}
with open(self.api_keys_file, 'r', encoding="utf-8") as f:
encrypted_keys = json.load(f)
try:
with open(self.api_keys_file, 'r', encoding="utf-8") as f:
encrypted_keys = json.load(f)
except (json.JSONDecodeError, OSError) as e:
# A corrupt/truncated api_keys.json must not crash load() (called on
# startup via app_initializer) — treat it as no stored keys.
logger.warning("Failed to read API keys file: %s", e)
return {}
if not isinstance(encrypted_keys, dict):
# Legacy/wrong shape (e.g. a list) — .items() would raise. Ignore it.
logger.warning("API keys file has unexpected shape (%s); ignoring", type(encrypted_keys).__name__)
return {}
decrypted = {}
for provider, key in encrypted_keys.items():