"""kernelwatch backup: consistent copy, permissions, and refusal to clobber the live DB.""" import calendar import contextlib import io import os import sqlite3 import stat import time import unittest from unittest import mock from helpers import temp_config, tempdir from kernelwatch import auth, cli, config, db class BackupTest(unittest.TestCase): def setUp(self): self.tmp = tempdir() self.addCleanup(self.tmp.cleanup) self.cfg = temp_config(self.tmp.name) self.config_path = os.path.join(self.tmp.name, "server.toml") with open(self.config_path, "w") as f: f.write(f'db_path = "{self.cfg.db_path}"\n') db.init(self.cfg.db_path) self.conn = db.connect(self.cfg.db_path) self.addCleanup(self.conn.close) db.add_host(self.conn, "web01", auth.token_hash("tok")) db.add_report(self.conn, "web01", {"kernel_running": "6.1.0-1"}, 30) self.dest = os.path.join(self.tmp.name, "backup.db") def run_cli(self, *args): out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = cli.main(["-c", self.config_path, *args]) return code, err.getvalue() def test_backup_contains_data_and_is_private(self): # The reader holds an open WAL connection, so the data may only be in the -wal file. self.assertEqual(self.run_cli("backup", self.dest)[0], 0) self.assertEqual(stat.S_IMODE(os.stat(self.dest).st_mode), 0o600) copy = db.connect(self.dest) self.addCleanup(copy.close) self.assertEqual([h["name"] for h in db.list_hosts(copy)], ["web01"]) self.assertEqual(db.host_for_token(copy, auth.token_hash("tok")), "web01") self.assertEqual(copy.execute("PRAGMA integrity_check").fetchone()[0], "ok") self.assertFalse([n for n in os.listdir(self.tmp.name) if ".tmp-" in n]) def test_replaces_an_existing_backup(self): with open(self.dest, "w") as f: f.write("old") self.assertEqual(self.run_cli("backup", self.dest)[0], 0) copy = sqlite3.connect(self.dest) self.addCleanup(copy.close) self.assertEqual(copy.execute("SELECT count(*) FROM hosts").fetchone()[0], 1) def test_refuses_the_live_database(self): code, err = self.run_cli("backup", self.cfg.db_path) self.assertEqual(code, 1) self.assertIn("live database", err) self.assertEqual([h["name"] for h in db.list_hosts(self.conn)], ["web01"]) def test_failure_leaves_no_partial_file(self): missing = os.path.join(self.tmp.name, "nope", "backup.db") code, err = self.run_cli("backup", missing) self.assertEqual(code, 1) self.assertIn("backup failed", err) self.assertFalse([n for n in os.listdir(self.tmp.name) if ".tmp-" in n]) NOW = calendar.timegm((2026, 11, 20, 3, 30, 0)) def day(offset): return time.strftime("kernelwatch-%Y-%m-%d.db", time.gmtime(NOW + offset * 86400)) class RotateBackupsTest(unittest.TestCase): def setUp(self): self.tmp = tempdir() self.addCleanup(self.tmp.cleanup) self.db_path = os.path.join(self.tmp.name, "kw.db") self.dir = os.path.join(self.tmp.name, "backups") db.init(self.db_path) conn = db.connect(self.db_path) self.addCleanup(conn.close) db.add_host(conn, "web01", auth.token_hash("tok")) def touch(self, name): os.makedirs(self.dir, exist_ok=True) with open(os.path.join(self.dir, name), "w") as f: f.write("x") def names(self): return sorted(os.listdir(self.dir)) def rotate(self, keep=7, now=NOW): return db.rotate_backups(self.db_path, self.dir, keep, now) def test_writes_a_dated_private_copy_and_creates_the_directory(self): dest = self.rotate() self.assertEqual(dest, os.path.join(self.dir, "kernelwatch-2026-11-20.db")) self.assertEqual(stat.S_IMODE(os.stat(self.dir).st_mode), 0o700) self.assertEqual(stat.S_IMODE(os.stat(dest).st_mode), 0o600) copy = sqlite3.connect(dest) self.addCleanup(copy.close) self.assertEqual(copy.execute("SELECT name FROM hosts").fetchall(), [("web01",)]) def test_same_day_replaces_the_file(self): self.rotate() self.rotate() self.assertEqual(self.names(), [day(0)]) def test_prunes_by_age_and_keeps_the_boundary(self): for offset in range(-10, 0): self.touch(day(offset)) self.rotate(keep=7) # keep=7 keeps today and the six days before it. self.assertEqual(self.names(), sorted(day(o) for o in range(-6, 1))) def test_only_dated_backup_files_are_ever_deleted(self): keepers = ["kernelwatch.db", "notes.txt", "kernelwatch-2020-01-01.db.bak", "kernelwatch-2020-01-01.db.tmp-1", "kernelwatch-2020-13-45.db", "other-2020-01-01.db"] for name in keepers + [day(-30)]: self.touch(name) self.rotate(keep=7) self.assertEqual(self.names(), sorted(keepers + [day(0)])) def test_zero_keeps_everything(self): for offset in (-400, -30, -8): self.touch(day(offset)) self.rotate(keep=0) self.assertEqual(len(self.names()), 4) def test_a_failed_backup_prunes_nothing(self): for offset in (-30, -1): self.touch(day(offset)) with mock.patch("kernelwatch.db.backup", side_effect=sqlite3.OperationalError("disk full")): with self.assertRaises(sqlite3.OperationalError): self.rotate(keep=7) self.assertEqual(self.names(), sorted([day(-30), day(-1)])) def test_the_live_database_is_never_pruned(self): os.makedirs(self.dir) live = os.path.join(self.dir, "kernelwatch-2000-01-01.db") db.init(live) with self.assertRaisesRegex(ValueError, "live database"): db.rotate_backups(live, self.dir, 7, calendar.timegm((2000, 1, 1, 0, 0, 0))) self.assertTrue(os.path.exists(live)) class ScheduledBackupCommandTest(unittest.TestCase): def setUp(self): self.tmp = tempdir() self.addCleanup(self.tmp.cleanup) self.dir = os.path.join(self.tmp.name, "backups") self.config_path = os.path.join(self.tmp.name, "server.toml") self.write_config(f'db_path = "{self.tmp.name}/kw.db"\nbackup_dir = "{self.dir}"\nbackup_keep_days = 3\n') def write_config(self, text): with open(self.config_path, "w") as f: f.write(text) def run_cli(self): out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = cli.main(["-c", self.config_path, "scheduled-backup"]) return code, out.getvalue(), err.getvalue() def test_backs_up_to_the_configured_directory_and_prunes_with_the_configured_age(self): os.makedirs(self.dir) old = os.path.join(self.dir, "kernelwatch-2020-01-01.db") open(old, "w").close() code, out, _ = self.run_cli() self.assertEqual(code, 0) today = time.strftime("kernelwatch-%Y-%m-%d.db", time.gmtime()) self.assertIn(os.path.join(self.dir, today), out) self.assertEqual(os.listdir(self.dir), [today]) def test_failure_exits_nonzero(self): with open(os.path.join(self.tmp.name, "blocker"), "w") as f: f.write("a file where the directory should go") self.write_config(f'db_path = "{self.tmp.name}/kw.db"\nbackup_dir = "{self.tmp.name}/blocker/x"\n') code, _, err = self.run_cli() self.assertEqual(code, 1) self.assertIn("scheduled backup failed", err) def test_config_defaults_and_validation(self): cfg = config.Config() self.assertEqual((cfg.backup_dir, cfg.backup_keep_days), ("/var/lib/kernelwatch/backups", 7)) for bad in ("backup_keep_days = -1", 'backup_dir = ""', 'backup_dir = "relative/dir"', "backup_keep_days = 1.5", "backup_dir = 5"): with self.subTest(bad=bad): self.write_config(bad + "\n") with self.assertRaises(SystemExit): config.load(self.config_path) self.write_config("backup_keep_days = 0\n") self.assertEqual(config.load(self.config_path).backup_keep_days, 0) if __name__ == "__main__": unittest.main()