import json from cryptography.fernet import Fernet from backend.core.config import settings from backend.core.logging import get_logger logger = get_logger(__name__) _ENCRYPTED_KEY = "__enc__" def _fernet() -> Fernet: if not settings.ENCRYPTION_KEY: raise ValueError("ENCRYPTION_KEY is not set in environment. Cannot encrypt credentials.") return Fernet(settings.ENCRYPTION_KEY.encode()) def encrypt_credentials(data: dict) -> dict: """Encrypt a credentials dict for storage. Returns {"__enc__": ""}.""" if not settings.ENCRYPTION_KEY: logger.warning("ENCRYPTION_KEY not set — credentials stored in plaintext") return data token = _fernet().encrypt(json.dumps(data).encode()).decode() return {_ENCRYPTED_KEY: token} def decrypt_credentials(data: dict) -> dict: """Decrypt a stored credentials dict. Transparently handles legacy plaintext dicts. Recursively unwraps nested __enc__ layers that can occur when save_credentials previously merged into an already-encrypted blob instead of decrypting first. """ if not isinstance(data, dict): return data if _ENCRYPTED_KEY not in data: return data # legacy plaintext — return as-is if not settings.ENCRYPTION_KEY: raise ValueError("ENCRYPTION_KEY is not set — cannot decrypt stored credentials.") inner = json.loads(_fernet().decrypt(data[_ENCRYPTED_KEY].encode())) # Recursively unwrap any nested __enc__ from historical double-encryption if isinstance(inner, dict) and _ENCRYPTED_KEY in inner: return decrypt_credentials(inner) return inner