File size: 1,636 Bytes
098f3ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1c3c6d
 
 
 
 
098f3ea
 
 
 
 
 
f1c3c6d
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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__": "<token>"}."""
    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