dodil/erp-brick-purchasing

DODIL ERP brick: purchasing

src/brick_purchasing/infrastructure/vault.py

"""Supplier bank details are stored ENCRYPTED and shown masked (module.yaml supplier_bank): a database dump holds no account number.

Fernet (AES-128-CBC + HMAC) with the key in PURCHASING_BANK_KEY (a urlsafe base64 32-byte key, from the deployment's secrets).
With no key configured the details cannot be stored (503): an unencrypted account number is never written."""
import os


class NoKey(Exception):
    pass


def _fernet():
    key = os.environ.get("PURCHASING_BANK_KEY", "")
    if not key:
        raise NoKey("PURCHASING_BANK_KEY is not set: supplier bank details are stored encrypted and cannot be kept without it")
    from cryptography.fernet import Fernet
    return Fernet(key.encode())


def seal(value: str) -> str:
    return _fernet().encrypt((value or "").encode()).decode() if value else ""


def unseal(token: str) -> str:
    return _fernet().decrypt(token.encode()).decode() if token else ""