# SPDX-License-Identifier: AGPL-3.0-or-later from __future__ import annotations import os import socket import subprocess from collections.abc import Iterator from datetime import UTC, datetime from pathlib import Path import pytest from surveybox import backup # --------------------------------------------------------------------------- # Reine Hilfsfunktionen # --------------------------------------------------------------------------- def _fake_pg_lib(root: Path, versions: list[int]) -> Path: for v in versions: bindir = root / str(v) / "bin" bindir.mkdir(parents=True) for tool in ("pg_dump", "pg_restore"): (bindir / tool).write_text("#!/bin/sh\n") (root / "notaversion").mkdir() return root @pytest.mark.parametrize( ("server", "expected"), [(17, 17), (18, 18), (16, 17), (19, 19)], ) def test_find_pg_tool_prefers_same_then_next_higher( tmp_path: Path, server: int, expected: int ) -> None: root = _fake_pg_lib(tmp_path, [17, 18, 19]) assert backup.find_pg_tool("pg_dump", server, root) == root / str(expected) / "bin/pg_dump" def test_find_pg_tool_refuses_newer_server(tmp_path: Path) -> None: root = _fake_pg_lib(tmp_path, [17, 18]) with pytest.raises(backup.BackupError, match="PostgreSQL 19"): backup.find_pg_tool("pg_dump", 19, root) def test_backup_filename_sorts_chronologically() -> None: a = backup.backup_filename("daily", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)) b = backup.backup_filename("daily", datetime(2026, 11, 2, 3, 4, 5, tzinfo=UTC)) assert a == "surveybox-daily-20260102T030405Z.dump" assert a < b def test_backup_filename_with_revisions_is_safe() -> None: name = backup.backup_filename( "pre-upgrade", datetime(2026, 1, 1, tzinfo=UTC), "0001_initial", "../../evil rev" ) assert "/" not in name and " " not in name assert name.startswith("surveybox-pre-upgrade-20260101T000000Z-from-0001_initial-to-") def test_apply_retention_keeps_newest(tmp_path: Path) -> None: names = [ backup.backup_filename("daily", datetime(2026, 1, day, tzinfo=UTC)) for day in range(1, 6) ] for n in names: (tmp_path / n).write_bytes(b"x") (tmp_path / "surveybox-daily-20260106T000000Z.dump.partial").write_bytes(b"x") deleted = backup.apply_retention(tmp_path, keep=2) assert [p.name for p in deleted] == names[:3] remaining = sorted(p.name for p in tmp_path.iterdir()) assert names[3] in remaining and names[4] in remaining assert any(n.endswith(".partial") for n in remaining) # unfertige bleiben unangetastet def test_subprocess_env_does_not_leak_app_secrets(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("SURVEYBOX_SECRET_KEY", "geheim") env = backup._subprocess_env({"PGHOST": "db"}) assert "SURVEYBOX_SECRET_KEY" not in env assert env["PGHOST"] == "db" # --------------------------------------------------------------------------- # Gegen ein echtes PostgreSQL (temporärer Cluster oder Test-Datenbank) # --------------------------------------------------------------------------- def _free_port() -> int: with socket.socket() as s: s.bind(("127.0.0.1", 0)) return int(s.getsockname()[1]) @pytest.fixture(scope="module") def pg_cluster(tmp_path_factory: pytest.TempPathFactory) -> Iterator[tuple[dict[str, str], int]]: """Startet einen Wegwerf-Cluster mit den lokal installierten Werkzeugen.""" versions = backup.available_pg_versions() initdb = [backup.PG_LIB_ROOT / str(v) / "bin/initdb" for v in versions] initdb = [p for p in initdb if p.is_file()] if not initdb: pytest.skip("kein initdb vorhanden") if os.geteuid() == 0: pytest.skip("PostgreSQL startet nicht als root") bindir = initdb[-1].parent major = int(bindir.parent.name) base = tmp_path_factory.mktemp("pg") data, sock = base / "data", base / "sock" sock.mkdir() subprocess.run( [str(bindir / "initdb"), "-D", str(data), "-U", "test", "--auth=trust", "-E", "UTF8"], check=True, capture_output=True, ) port = _free_port() subprocess.run( [str(bindir / "pg_ctl"), "-D", str(data), "-w", "-l", str(base / "log"), "-o", f"-p {port} -k {sock} -c listen_addresses=''", "start"], check=True, capture_output=True, ) env = {"PGHOST": str(sock), "PGPORT": str(port), "PGUSER": "test", "PGDATABASE": "postgres"} try: yield env, major finally: subprocess.run([str(bindir / "pg_ctl"), "-D", str(data), "-m", "fast", "stop"], check=False, capture_output=True) def _psql(bindir: Path, env: dict[str, str], sql: str) -> str: out = subprocess.run( [str(bindir / "psql"), "-XAtq", "-v", "ON_ERROR_STOP=1", "-c", sql], env={**os.environ, **env}, check=True, capture_output=True, text=True, ) return out.stdout.strip() def _tools(major: int) -> tuple[Path, Path, Path]: return ( backup.find_pg_tool("pg_dump", major), backup.find_pg_tool("pg_restore", major), backup.find_pg_tool("psql", major), ) def test_dump_verify_and_restore_roundtrip( pg_cluster: tuple[dict[str, str], int], tmp_path: Path ) -> None: env, major = pg_cluster pg_dump, pg_restore, psql = _tools(major) bindir = pg_dump.parent _psql(bindir, env, "DROP SCHEMA IF EXISTS surveybox CASCADE; CREATE SCHEMA surveybox") _psql(bindir, env, "CREATE TABLE surveybox.t (id int primary key, note text)") _psql(bindir, env, "INSERT INTO surveybox.t VALUES (1, 'vorher')") _psql(bindir, env, "CREATE TABLE public.fremd (x int); INSERT INTO public.fremd VALUES (7)") target = tmp_path / "out" / "surveybox-manual-test.dump" backup.dump_to_file(pg_dump, pg_restore, env, target) assert target.is_file() assert oct(target.stat().st_mode & 0o777) == "0o600" assert not list(target.parent.glob("*.partial")) # Ein "Update" nach der Sicherung: Daten geändert, neue Tabelle mit # Fremdschlüssel auf eine alte Tabelle. Genau das ließe ein einfaches # pg_restore --clean scheitern. _psql(bindir, env, "UPDATE surveybox.t SET note = 'nachher'") _psql( bindir, env, "CREATE TABLE surveybox.neu (id int primary key, t_id int references surveybox.t(id))", ) _psql(bindir, env, "INSERT INTO surveybox.neu VALUES (1, 1)") _psql(bindir, env, "UPDATE public.fremd SET x = 8") backup.restore_from_file(pg_restore, psql, env, target, tmp_path / "work") assert _psql(bindir, env, "SELECT note FROM surveybox.t WHERE id = 1") == "vorher" assert _psql(bindir, env, "SELECT to_regclass('surveybox.neu') IS NULL") == "t" # Andere Schemata bleiben unberührt assert _psql(bindir, env, "SELECT x FROM public.fremd") == "8" assert not list((tmp_path / "work").glob(".restore-*")) def test_failed_restore_keeps_current_state( pg_cluster: tuple[dict[str, str], int], tmp_path: Path ) -> None: """Bricht das Einspielen ab, bleibt der bisherige Stand vollständig erhalten.""" env, major = pg_cluster pg_dump, pg_restore, psql = _tools(major) bindir = pg_dump.parent _psql(bindir, env, "DROP SCHEMA IF EXISTS surveybox CASCADE; CREATE SCHEMA surveybox") _psql(bindir, env, "CREATE TABLE surveybox.t (v text); INSERT INTO surveybox.t VALUES ('a')") target = tmp_path / "surveybox-manual-t.dump" backup.dump_to_file(pg_dump, pg_restore, env, target) _psql(bindir, env, "UPDATE surveybox.t SET v = 'b'") # Eine Rolle, die es beim Einspielen nicht gibt, lässt einen Befehl der # Sicherung scheitern: Wir hängen ihn an das erzeugte Skript an, indem # wir pg_restore durch einen Wrapper ersetzen. wrapper = tmp_path / "pg_restore_wrapper.sh" wrapper.write_text( "#!/bin/sh\n" f'"{pg_restore}" "$@" || exit $?\n' 'for a in "$@"; do case "$a" in --file=*) ' 'echo "SELECT kaputt_absichtlich();" >> "${a#--file=}";; esac; done\n' ) wrapper.chmod(0o755) with pytest.raises(backup.BackupError, match="Einspielen"): backup.restore_from_file(wrapper, psql, env, target, tmp_path / "work") assert _psql(bindir, env, "SELECT v FROM surveybox.t") == "b" def test_failed_dump_leaves_no_file( pg_cluster: tuple[dict[str, str], int], tmp_path: Path ) -> None: env, major = pg_cluster pg_dump, pg_restore, _ = _tools(major) target = tmp_path / "surveybox-manual-broken.dump" with pytest.raises(backup.BackupError, match="pg_dump"): backup.dump_to_file(pg_dump, pg_restore, {**env, "PGDATABASE": "gibtsnicht"}, target) assert not target.exists() assert not list(tmp_path.glob("*.partial")) def test_restore_rejects_corrupt_file( pg_cluster: tuple[dict[str, str], int], tmp_path: Path ) -> None: env, major = pg_cluster _, pg_restore, psql = _tools(major) bad = tmp_path / "kaputt.dump" bad.write_bytes(b"keine Sicherung") with pytest.raises(backup.BackupError, match="Prüfung"): backup.restore_from_file(pg_restore, psql, env, bad, tmp_path / "work") def test_restore_rejects_bad_schema_name(tmp_path: Path) -> None: f = tmp_path / "x.dump" f.write_bytes(b"x") with pytest.raises(backup.BackupError, match="Schemaname"): backup.restore_from_file(f, f, {}, f, tmp_path, schema="x; DROP")