Source code for s365b.core.secrets

"""Encryption of secrets stored in the database.

Certificate private keys, SMTP passwords and similar values are stored in
PostgreSQL encrypted with AES-256-GCM under the **master key** (a file passed
to the containers as a Docker secret). A database dump alone therefore does
not reveal them.

This is separate from backup repository encryption
(:mod:`s365b.storage.crypto`), which uses its own passphrase-derived key.
"""

from __future__ import annotations

import base64
import os
import secrets
from pathlib import Path

from cryptography.hazmat.primitives.ciphers.aead import AESGCM

_VERSION = b"\x01"
_NONCE_LEN = 12
[docs] KEY_LEN = 32
[docs] class SecretBoxError(Exception): """Raised when a secret cannot be decrypted (wrong key or tampered data)."""
[docs] def generate_master_key() -> str: """Create a new random master key. Returns: The key as URL-safe base64 text, suitable for writing to a file. """ return base64.urlsafe_b64encode(secrets.token_bytes(KEY_LEN)).decode()
[docs] def load_master_key(path: Path) -> bytes: """Read and decode a master key file. Args: path: File written by :func:`generate_master_key`. Returns: The 32-byte key. Raises: SecretBoxError: If the file does not hold a valid key. """ try: key = base64.urlsafe_b64decode(path.read_text().strip()) except (OSError, ValueError) as exc: raise SecretBoxError(f"cannot read master key from {path}: {exc}") from exc if len(key) != KEY_LEN: raise SecretBoxError(f"master key in {path} must be {KEY_LEN} bytes") return key
[docs] class SecretBox: """Encrypts and decrypts small secrets with the master key. The ciphertext format is ``version(1) || nonce(12) || ciphertext+tag``, base64-encoded so it fits in a text column. An optional *context* string (e.g. ``"tenant:42:cert"``) is bound as associated data, so a ciphertext copied into another row fails to decrypt. Args: key: 32-byte master key. """ def __init__(self, key: bytes) -> None: if len(key) != KEY_LEN: raise ValueError("SecretBox key must be 32 bytes") self._aead = AESGCM(key)
[docs] def encrypt(self, plaintext: bytes, context: str = "") -> str: """Encrypt a secret. Args: plaintext: Secret bytes. context: Associated data that must match on decryption. Returns: Base64 text safe to store in the database. """ nonce = os.urandom(_NONCE_LEN) ct = self._aead.encrypt(nonce, plaintext, context.encode()) return base64.b64encode(_VERSION + nonce + ct).decode()
[docs] def decrypt(self, token: str, context: str = "") -> bytes: """Decrypt a value produced by :meth:`encrypt`. Args: token: Stored base64 text. context: The same associated data used to encrypt. Returns: The plaintext secret. Raises: SecretBoxError: If the key, context or data do not match. """ try: raw = base64.b64decode(token) if raw[:1] != _VERSION: raise SecretBoxError("unknown secret format version") nonce, ct = raw[1 : 1 + _NONCE_LEN], raw[1 + _NONCE_LEN :] return self._aead.decrypt(nonce, ct, context.encode()) except SecretBoxError: raise except Exception as exc: raise SecretBoxError("secret could not be decrypted") from exc