Files
romm/backend/utils/secret_box.py
zurdi 7ac95be747 feat: forward notifications to webhooks and email
Each user can add channels that forward their notifications: a webhook
posting RomM's JSON (optionally HMAC-signed), a Discord embed or an ntfy
message, or an email address confirmed with a code. A channel filters by
minimum level and by topic, and every stored notification that passes goes
out in its own RQ job, retried three times; ten failures in a row turn the
channel off and tell its owner.

Channel configs are sealed with a key derived from ROMM_AUTH_SECRET_KEY,
since a webhook URL carries its own token. Only an admin's webhooks may
reach private addresses; everyone else's go through the SSRF guard. Email
goes out over the SMTP_* settings, which the heartbeat reports as
NOTIFICATIONS.EMAIL_ENABLED.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 16:30:33 +02:00

43 lines
1.2 KiB
Python

"""Symmetric sealing of small secrets kept in the database, keyed off the auth secret."""
import base64
import hashlib
import json
from functools import cache
from typing import Any
from cryptography.fernet import Fernet, InvalidToken
from config import ROMM_AUTH_SECRET_KEY
class UnsealError(ValueError):
"""The value was sealed with another key, or is not a sealed value."""
@cache
def _fernet() -> Fernet:
# Derived rather than the raw secret, so the key serves this purpose only.
digest = hashlib.sha256(f"romm:secret-box:{ROMM_AUTH_SECRET_KEY}".encode()).digest()
return Fernet(base64.urlsafe_b64encode(digest))
def seal(value: dict[str, Any]) -> str:
return _fernet().encrypt(json.dumps(value).encode()).decode()
def unseal(token: str) -> dict[str, Any]:
"""Open a value `seal` produced.
Raises:
UnsealError: ROMM_AUTH_SECRET_KEY changed since it was sealed, or the
value was never sealed.
"""
try:
value = json.loads(_fernet().decrypt(token.encode()))
except (InvalidToken, ValueError) as exc:
raise UnsealError("Could not unseal the value") from exc
if not isinstance(value, dict):
raise UnsealError("The sealed value is not an object")
return value