import asyncio import gzip import logging import os import re import secrets from datetime import datetime, timezone from pathlib import Path from typing import Literal from sqlalchemy import select from sqlalchemy.engine import make_url from sqlalchemy.ext.asyncio import AsyncSession from app.config import settings from app.database import engine from app.models.admin_settings import AdminSettings from app.schemas.admin import BackupFileOut logger = logging.getLogger("bourbonacci.backup") BACKUP_ROOT = Path("/backups") _FILENAME_PREFIX = "bourbonacci_" _FILENAME_SUFFIX = ".sql.gz" _TABLE_MARKER = re.compile(rb"^-- Table structure for table `([^`]+)`", re.MULTILINE) # First statement of the trailer mysqldump/mariadb-dump writes after the last table. _TRAILER_MARKER = re.compile(rb"^/\*!40103 SET TIME_ZONE=@OLD_TIME_ZONE \*/;", re.MULTILINE) class BackupError(Exception): """A mariadb-dump/mariadb subprocess exited non-zero.""" def _utcnow() -> datetime: # MySQL DATETIME columns are naive; store UTC. return datetime.now(timezone.utc).replace(tzinfo=None) def _conn_args() -> tuple[list[str], dict[str, str]]: """Connection flags for the MariaDB CLI tools, derived from DATABASE_URL. The password goes in MYSQL_PWD so it never shows up in the process list.""" url = make_url(settings.database_url) args = [ "-h", url.host or "localhost", "-P", str(url.port or 3306), "-u", url.username or "", # MySQL 8.4 serves TLS with an auto-generated self-signed cert. "--skip-ssl-verify-server-cert", ] env = {**os.environ, "MYSQL_PWD": url.password or ""} return args, env def _db_name() -> str: return make_url(settings.database_url).database or "" async def _get_settings(db: AsyncSession) -> AdminSettings: row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none() if not row: row = AdminSettings(id=1) db.add(row) await db.flush() return row _LOCATION_RE = re.compile(r"^[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*$") def normalize_backup_location(location: str | None) -> str | None: """Validate the admin's optional backup subfolder: plain folder names (letters, digits, - and _) nested with "/", so it can't point outside BACKUP_ROOT. Raises ValueError otherwise.""" location = (location or "").strip().strip("/") if not location: return None if not _LOCATION_RE.match(location): raise ValueError("Subfolder may only contain letters, numbers, - and _, separated by /.") return location def backup_dir(location: str | None = None) -> Path: d = BACKUP_ROOT / location.strip("/") if location else BACKUP_ROOT # Belt and braces alongside normalize_backup_location: never create or # use a directory outside BACKUP_ROOT, whatever is stored in the row. if not d.resolve().is_relative_to(BACKUP_ROOT.resolve()): raise ValueError("Backup location must be inside the backup directory") d.mkdir(parents=True, exist_ok=True) return d def _resolve_backup_file(filename: str, location: str | None) -> Path: """Resolve a filename against the backup directory, rejecting anything that escapes it (path traversal via `..`, absolute paths, etc).""" base = backup_dir(location).resolve() candidate = (base / filename).resolve() if not candidate.is_relative_to(base) or candidate.parent != base: raise ValueError("Invalid backup filename") return candidate def list_backups(location: str | None = None) -> list[BackupFileOut]: d = backup_dir(location) files = [ BackupFileOut( filename=f.name, size_bytes=f.stat().st_size, created_at=datetime.fromtimestamp(f.stat().st_mtime, tz=timezone.utc), ) for f in d.iterdir() if f.is_file() and f.name.startswith(_FILENAME_PREFIX) and f.name.endswith(_FILENAME_SUFFIX) ] files.sort(key=lambda b: b.created_at, reverse=True) return files def prune_backups(retention: int, location: str | None = None) -> int: files = list_backups(location) to_delete = files[retention:] for f in to_delete: (backup_dir(location) / f.filename).unlink(missing_ok=True) return len(to_delete) async def _dump_to(path: Path) -> None: conn, env = _conn_args() proc = await asyncio.create_subprocess_exec( "mariadb-dump", *conn, "--single-transaction", "--no-tablespaces", "--skip-lock-tables", _db_name(), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env, ) stderr_task = asyncio.create_task(proc.stderr.read()) with gzip.open(path, "wb") as out: while chunk := await proc.stdout.read(65536): out.write(chunk) stderr = await stderr_task await proc.wait() if proc.returncode != 0: raise BackupError(stderr.decode(errors="replace").strip() or f"mariadb-dump exited {proc.returncode}") async def _load_sql(sql: bytes) -> None: conn, env = _conn_args() proc = await asyncio.create_subprocess_exec( "mariadb", *conn, _db_name(), stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env, ) _, stderr = await proc.communicate(input=sql) if proc.returncode != 0: raise BackupError(stderr.decode(errors="replace").strip() or f"mariadb exited {proc.returncode}") def _extract_table(sql: bytes, table: str) -> bytes: """Return the dump's header + the given table's DROP/CREATE/INSERT section + trailer, so just that one table can be reloaded from a full-database dump.""" markers = list(_TABLE_MARKER.finditer(sql)) trailer = _TRAILER_MARKER.search(sql) if not markers or not trailer: raise BackupError("Backup file is not in the expected mysqldump format") header = sql[: markers[0].start()] for i, m in enumerate(markers): if m.group(1).decode() == table: end = markers[i + 1].start() if i + 1 < len(markers) else trailer.start() return header + sql[m.start(): end] + sql[trailer.start():] raise BackupError(f"Backup file has no `{table}` table") async def run_backup(db: AsyncSession) -> BackupFileOut: row = await _get_settings(db) d = backup_dir(row.backup_location) # A short random suffix guards against two backups landing in the same # second (e.g. rapid "Backup now" clicks), which would otherwise silently # overwrite one another. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") path = d / f"{_FILENAME_PREFIX}{stamp}_{secrets.token_hex(3)}{_FILENAME_SUFFIX}" try: await _dump_to(path) except BackupError as exc: path.unlink(missing_ok=True) row.last_backup_at = _utcnow() row.last_backup_status = "error" row.last_backup_error = str(exc)[:2000] await db.commit() logger.error("Backup failed: %s", exc) raise # Full user data in plaintext -- keep it readable only by the app user. path.chmod(0o600) prune_backups(row.backup_retention, row.backup_location) row.last_backup_at = _utcnow() row.last_backup_status = "success" row.last_backup_error = None await db.commit() stat = path.stat() return BackupFileOut( filename=path.name, size_bytes=stat.st_size, created_at=datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc), ) async def restore_backup(filename: str, scope: Literal["entries", "all"], db: AsyncSession) -> None: row = await _get_settings(db) path = _resolve_backup_file(filename, row.backup_location) if not path.is_file(): raise FileNotFoundError(filename) # Reading admin_settings above left this session in an open transaction # holding a metadata lock on that table; a full restore DROPs and # recreates it, which would block on that lock. Close the transaction first. await db.commit() sql = await asyncio.to_thread(lambda: gzip.decompress(path.read_bytes())) if scope == "entries": sql = _extract_table(sql, "entries") await _load_sql(sql) # Tables were dropped and recreated -- discard pooled connections so none # carries state from before the restore. await engine.dispose() def delete_backup(filename: str, location: str | None) -> None: path = _resolve_backup_file(filename, location) path.unlink(missing_ok=True)