Source code for s365b.core.branding

"""Branding: product name, colours, logo and sign-in text.

Branding applies to the web UI (including the sign-in page, so it is readable
without signing in), notification emails and exports. Defaults give the
stock Mail Safehouse look.

Images are stored in the ``asset`` table rather than on disk, so every API
replica serves the same files and the containers can keep a read-only
filesystem.
"""

from __future__ import annotations

import hashlib
import re
from typing import Literal

from pydantic import Field, HttpUrl, field_validator
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession

from s365b.core.settings_store import SettingsGroup
from s365b.db.models import Asset

[docs] HEX_COLOR = re.compile(r"^#[0-9a-fA-F]{6}$")
[docs] MAX_IMAGE_BYTES = 512 * 1024
[docs] ASSET_KEYS = ("logo", "logo_dark", "favicon")
# Magic numbers of accepted raster formats. _SIGNATURES: dict[str, tuple[bytes, ...]] = { "image/png": (b"\x89PNG\r\n\x1a\n",), "image/jpeg": (b"\xff\xd8\xff",), "image/webp": (b"RIFF",), "image/x-icon": (b"\x00\x00\x01\x00",), }
[docs] class BrandingError(ValueError): """Raised for an invalid branding image."""
[docs] class Branding(SettingsGroup): """Branding settings. Attributes: product_name: Name shown in the header, page titles and emails. tagline: Short line under the name on the sign-in page. primary_color: Main colour (buttons, links, focus), ``#rrggbb``. accent_color: Secondary colour (highlights, charts), ``#rrggbb``. default_theme: Theme for users who have not chosen one. default_language: Language for users who have not chosen one: ``auto`` follows the browser. Web UI only: emails are in English. login_message: Text on the sign-in page, e.g. an acceptable-use notice. support_email: Contact shown in the UI footer and emails. support_url: Link shown in the UI footer and emails. email_footer: Plain text appended to every notification email. """
[docs] key = "branding"
[docs] product_name: str = Field("Mail Safehouse", min_length=1, max_length=64)
[docs] tagline: str = Field("Microsoft 365 backup", max_length=120)
[docs] primary_color: str = "#2563eb"
[docs] accent_color: str = "#0d9488"
[docs] default_theme: Literal["system", "light", "dark"] = "system"
[docs] default_language: Literal["auto", "en", "es", "fr"] = "auto"
[docs] login_message: str = Field("", max_length=1000)
[docs] support_email: str = Field("", max_length=256)
[docs] support_url: HttpUrl | None = None
@field_validator("primary_color", "accent_color") @classmethod def _hex(cls, value: str) -> str: """Require ``#rrggbb`` colours (stored lowercase).""" if not HEX_COLOR.match(value): raise ValueError("colour must look like #1a2b3c") return value.lower() @field_validator("support_email") @classmethod def _email(cls, value: str) -> str: """Require a plausible email address when one is given.""" if value and not re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", value): raise ValueError("not a valid email address") return value
[docs] def sniff_image(data: bytes) -> str: """Validate an uploaded image and return its content type. Accepts PNG, JPEG, WebP, ICO and SVG up to 512 KiB. SVG files must not contain scripts, event handlers or external references; they are also served with a sandboxing Content-Security-Policy. Args: data: Uploaded bytes. Returns: The detected content type. Raises: BrandingError: If the file is too large, not an accepted type, or an unsafe SVG. """ if not data: raise BrandingError("empty file") if len(data) > MAX_IMAGE_BYTES: raise BrandingError(f"image larger than {MAX_IMAGE_BYTES // 1024} KiB") for ctype, magics in _SIGNATURES.items(): if any(data.startswith(m) for m in magics): if ctype == "image/webp" and data[8:12] != b"WEBP": continue return ctype head = data[:2048].lstrip().lower() if head.startswith((b"<svg", b"<?xml")) and b"<svg" in data[:4096].lower(): _check_svg(data) return "image/svg+xml" raise BrandingError("unsupported image type (use PNG, JPEG, WebP, ICO or SVG)")
_SVG_FORBIDDEN = re.compile( rb"<script|<foreignobject|javascript:|\son[a-z]+\s*=|<!entity|xlink:href\s*=\s*[\"']?(?!#)|href\s*=\s*[\"']?(?!#)", re.IGNORECASE, ) def _check_svg(data: bytes) -> None: if _SVG_FORBIDDEN.search(data): raise BrandingError("SVG contains scripts, event handlers or external references")
[docs] async def save_asset(session: AsyncSession, key: str, data: bytes) -> Asset: """Validate and store a branding image. Args: session: Open session; the caller commits. key: One of :data:`ASSET_KEYS`. data: Image bytes. Returns: The stored asset. Raises: BrandingError: If the key or image is invalid. """ if key not in ASSET_KEYS: raise BrandingError(f"unknown asset {key!r}") ctype = sniff_image(data) digest = hashlib.sha256(data).hexdigest() row = ( await session.execute( insert(Asset) .values(key=key, content_type=ctype, data=data, sha256=digest) .on_conflict_do_update( index_elements=["key"], set_={"content_type": ctype, "data": data, "sha256": digest} ) .returning(Asset) ) ).scalar_one() return row