""" ALLI Security - Workspace Environment Variable Encryption Helper Uses Fernet symmetric AEAD encryption backed by ALLI_ENV_ENCRYPTION_KEY. Fails closed when AUTH_REQUIRED=true or STAGE != dev and key is absent. """ import os import tempfile from pathlib import Path from typing import Optional from cryptography.fernet import Fernet, InvalidToken from security.rbac import is_auth_required _EPHEMERAL_DEV_KEY: Optional[bytes] = None _DEV_KEY_FILENAME = "alli_dev_env_fernet.key" _DEV_STAGES = frozenset({"dev", "development", "local", "test"}) def _resolve_raw_key() -> str: return os.environ.get("ALLI_ENV_ENCRYPTION_KEY", "").strip() def is_encryption_key_configured() -> bool: """Return True when ALLI_ENV_ENCRYPTION_KEY is explicitly configured.""" return bool(_resolve_raw_key()) def _resolve_dev_key_path() -> Path: key_dir = Path.home() / ".alli" key_dir.mkdir(parents=True, exist_ok=True) if os.name != "nt": try: os.chmod(key_dir, 0o700) except OSError: pass return key_dir / _DEV_KEY_FILENAME def _get_fernet() -> Fernet: global _EPHEMERAL_DEV_KEY raw_key = _resolve_raw_key() if raw_key: try: return Fernet(raw_key.encode("utf-8")) except Exception as exc: raise RuntimeError( "[ERR-SECURITY-ENV-KEY-INVALID] ALLI_ENV_ENCRYPTION_KEY must be a valid 32-byte url-safe base64 Fernet key." ) from exc stage = (os.environ.get("STAGE") or "dev").strip().lower() if is_auth_required() or stage not in _DEV_STAGES: raise RuntimeError( "[ERR-SECURITY-ENV-KEY-MISSING] ALLI_ENV_ENCRYPTION_KEY must be set when AUTH_REQUIRED=true or STAGE is not dev." ) if _EPHEMERAL_DEV_KEY is None: key_path = _resolve_dev_key_path() if key_path.exists(): try: cached = key_path.read_bytes().strip() Fernet(cached) _EPHEMERAL_DEV_KEY = cached except Exception as exc: raise RuntimeError( "[ERR-SECURITY-ENV-KEY-CORRUPT] Local dev key file is unreadable or corrupt; remove or set ALLI_ENV_ENCRYPTION_KEY." ) from exc if _EPHEMERAL_DEV_KEY is None: candidate = Fernet.generate_key() try: fd = os.open(str(key_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "wb") as handle: handle.write(candidate) if os.name != "nt": os.chmod(key_path, 0o600) _EPHEMERAL_DEV_KEY = candidate except FileExistsError: cached = key_path.read_bytes().strip() Fernet(cached) _EPHEMERAL_DEV_KEY = cached except OSError: _EPHEMERAL_DEV_KEY = candidate return Fernet(_EPHEMERAL_DEV_KEY) def encrypt_env_value(plaintext: str) -> str: """Encrypt plaintext env value using Fernet AEAD.""" token = _get_fernet().encrypt(str(plaintext).encode("utf-8")) return token.decode("utf-8") def decrypt_env_value(ciphertext: str) -> str: """Decrypt stored env value; raise PermissionError on missing/tampered key.""" if ciphertext is None or ciphertext == "": return "" try: plain_bytes = _get_fernet().decrypt(str(ciphertext).encode("utf-8")) return plain_bytes.decode("utf-8") except InvalidToken as exc: raise PermissionError( "[ERR-SECURITY-ENV-DECRYPT] Unable to decrypt workspace environment variable with the active encryption key." ) from exc