"""Runs agent/install.sh and server/install.sh for real against a fake root. KERNELWATCH_ROOT prefixes every path the installers touch (and skips their root check). systemctl, apt-get, useradd and the other system commands are stubs that log their arguments, so the tests see what would have run without running it. """ import os import re import shutil import stat import subprocess import unittest from helpers import REPO, tempdir AGENT_DIR = os.path.join(REPO, "agent") SERVER_DIR = os.path.join(REPO, "server") AGENT_INSTALL = os.path.join(AGENT_DIR, "install.sh") SERVER_INSTALL = os.path.join(SERVER_DIR, "install.sh") STUBS = { "systemctl": 'echo "systemctl $*" >> "$KW_LOG/calls"\n' '[ "$1" = start ] && [ -n "${KW_START_FAIL:-}" ] && exit 1\nexit 0\n', "journalctl": 'echo "journalctl $*" >> "$KW_LOG/calls"\necho "journal: unit failed"\n', "apt-get": 'echo "apt-get $*" >> "$KW_LOG/calls"\n', "useradd": 'echo "useradd $*" >> "$KW_LOG/calls"\n', "chown": 'echo "chown $*" >> "$KW_LOG/calls"\n', "curl": "exit 0\n", # Real `kernelwatch list-users`; only the server installer's closing hint uses it. "kernelwatch": 'printf "%s" "${KW_USERS:-}"\n', # Only the kernelwatch user lookup is faked. "id": '[ "${1:-}" = kernelwatch ] && exit "${KW_ID_RC:-0}"\nexec /usr/bin/id "$@"\n', # The kernelwatch user and group don't exist here, so drop -o/-g. "install": 'args=()\nwhile [ $# -gt 0 ]; do\n' ' case $1 in -o | -g) shift 2 ;; *) args+=("$1"); shift ;; esac\ndone\n' 'exec /usr/bin/install "${args[@]}"\n', } def mode(path): return stat.S_IMODE(os.stat(path).st_mode) def read(path): with open(path) as f: return f.read() class InstallCase(unittest.TestCase): def setUp(self): self._tmp = tempdir() self.addCleanup(self._tmp.cleanup) self.tmp = self._tmp.name self.root = os.path.join(self.tmp, "root") self.bin = os.path.join(self.tmp, "bin") self.log = os.path.join(self.tmp, "log") for d in (self.root, self.bin, self.log): os.makedirs(d) os.makedirs(os.path.join(self.root, "etc")) self.os_release("ubuntu", "24.04") for name, body in STUBS.items(): path = os.path.join(self.bin, name) with open(path, "w") as f: f.write("#!/bin/bash\n" + body) os.chmod(path, 0o755) def os_release(self, os_id, version): with open(os.path.join(self.root, "etc/os-release"), "w") as f: f.write(f'ID={os_id}\nVERSION_ID="{version}"\nPRETTY_NAME="{os_id} {version}"\n') def path(self, *parts): return os.path.join(self.root, *parts) def run_script(self, script, *args, env=None, stdin="", with_root=True): full_env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "KW_LOG": self.log, "HOME": self.tmp, **(env or {})} if with_root: full_env["KERNELWATCH_ROOT"] = self.root return subprocess.run(["bash", script, *args], env=full_env, input=stdin, capture_output=True, text=True, timeout=60) def calls(self): path = os.path.join(self.log, "calls") return read(path).splitlines() if os.path.exists(path) else [] def systemctl(self): return [c[len("systemctl "):] for c in self.calls() if c.startswith("systemctl ")] @unittest.skipUnless(shutil.which("bash"), "needs bash") class AgentInstallTest(InstallCase): TOKEN = "tok-AAAA-secret" def install(self, *args, token=TOKEN, **kw): env = dict(kw.pop("env", None) or {}) if token: env["KERNELWATCH_TOKEN"] = token return self.run_script(AGENT_INSTALL, *args, env=env, **kw) def fresh(self, *args, **kw): proc = self.install("--server", "https://k.example", *args, **kw) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) return proc def conf(self): return read(self.path("etc/kernelwatch/agent.conf")) def test_fresh_install(self): proc = self.fresh() self.assertEqual(self.conf(), "SERVER_URL=https://k.example\nTOKEN_FILE=/etc/kernelwatch/agent.token\n") self.assertEqual(mode(self.path("etc/kernelwatch/agent.conf")), 0o644) token = self.path("etc/kernelwatch/agent.token") self.assertEqual(read(token), self.TOKEN + "\n") self.assertEqual(mode(token), 0o600) self.assertNotIn(self.TOKEN, proc.stdout + proc.stderr) self.assertEqual(self.systemctl(), [ "daemon-reload", "enable --now kernelwatch-agent.timer", "start kernelwatch-agent.service"]) self.assertIn("chown root:root " + token, self.calls()) self.assertNotIn("warning", proc.stderr) def test_installs_every_agent_script_and_unit(self): self.fresh() for script in ("kernelwatch-agent", "kernelwatch-livepatch"): installed = self.path("usr/local/sbin", script) self.assertEqual(read(installed), read(os.path.join(AGENT_DIR, script))) self.assertEqual(mode(installed), 0o755) units = sorted(n for n in os.listdir(AGENT_DIR) if n.endswith((".service", ".timer"))) self.assertEqual(sorted(os.listdir(self.path("etc/systemd/system"))), units) for unit in units: self.assertEqual(mode(self.path("etc/systemd/system", unit)), 0o644) def test_everything_installed_is_shipped_by_deploy_sh(self): """deploy.sh copies only its FILES list; the installer can't use anything else.""" deploy = read(os.path.join(AGENT_DIR, "deploy.sh")) shipped = set(re.search(r"^FILES=\(([^)]*)\)", deploy, re.M | re.S).group(1).split()) used = set(re.findall(r'"\$here/([\w.-]+)"', read(AGENT_INSTALL))) self.assertTrue(used) self.assertEqual(sorted(used - shipped), []) def test_token_from_file_and_prompt(self): token_file = os.path.join(self.tmp, "token") with open(token_file, "w") as f: f.write(" file-token \n") self.fresh("--token-file", token_file, token=None) self.assertEqual(read(self.path("etc/kernelwatch/agent.token")), "file-token\n") shutil.rmtree(self.path("etc/kernelwatch")) self.fresh(token=None, stdin="typed-token\n") self.assertEqual(read(self.path("etc/kernelwatch/agent.token")), "typed-token\n") def test_empty_token_is_refused(self): empty = os.path.join(self.tmp, "empty") open(empty, "w").close() proc = self.install("--server", "https://k.example", "--token-file", empty, token=None) self.assertEqual(proc.returncode, 1) self.assertIn("empty token", proc.stderr) self.assertEqual(self.systemctl(), []) proc = self.install("--server", "https://k.example", token=None, stdin="\n") self.assertEqual(proc.returncode, 1) self.assertEqual(self.systemctl(), []) def test_upgrade_keeps_config_and_token(self): self.fresh() before = (self.conf(), read(self.path("etc/kernelwatch/agent.token"))) proc = self.install(token=None) self.assertEqual(proc.returncode, 0, proc.stderr) self.assertEqual((self.conf(), read(self.path("etc/kernelwatch/agent.token"))), before) def test_new_install_needs_a_server(self): proc = self.install() self.assertEqual(proc.returncode, 1) self.assertIn("pass --server URL", proc.stderr) self.assertEqual(self.systemctl(), []) def test_rotating_the_token_replaces_it(self): self.fresh() self.fresh(token="new-token") self.assertEqual(read(self.path("etc/kernelwatch/agent.token")), "new-token\n") self.assertEqual(mode(self.path("etc/kernelwatch/agent.token")), 0o600) def test_report_hostname_set_kept_and_cleared(self): self.fresh("--report-hostname", "iris") self.assertEqual(self.conf().splitlines()[-1], "REPORT_HOSTNAME=iris") self.assertEqual(self.install(token=None).returncode, 0) # upgrade self.assertIn("REPORT_HOSTNAME=iris\n", self.conf()) self.fresh() # --server rewrites the file self.assertEqual(self.conf().count("REPORT_HOSTNAME=iris"), 1) self.assertEqual(self.install("--report-hostname", "web2", token=None).returncode, 0) self.assertEqual(self.conf().count("REPORT_HOSTNAME="), 1) self.assertIn("REPORT_HOSTNAME=web2\n", self.conf()) self.assertEqual(self.install("--default-report-hostname", token=None).returncode, 0) self.assertNotIn("REPORT_HOSTNAME", self.conf()) self.assertEqual(mode(self.path("etc/kernelwatch/agent.conf")), 0o644) def test_invalid_report_hostname_changes_nothing(self): for bad in ("-x", "a b", "a/b", "x" * 64, "$(id)"): with self.subTest(bad=bad): proc = self.install("--server", "https://k.example", "--report-hostname", bad) self.assertEqual(proc.returncode, 2) self.assertIn("invalid --report-hostname", proc.stderr) self.assertFalse(os.path.exists(self.path("etc/kernelwatch"))) def test_apt_update_marker(self): marker = self.path("etc/kernelwatch/apt-update") self.fresh() self.assertFalse(os.path.exists(marker)) self.assertEqual(self.install("--with-apt-update", token=None).returncode, 0) self.assertTrue(os.path.exists(marker)) self.assertEqual(self.install(token=None).returncode, 0) # neither flag: unchanged self.assertTrue(os.path.exists(marker)) self.assertEqual(self.install("--without-apt-update", token=None).returncode, 0) self.assertFalse(os.path.exists(marker)) def test_private_ca(self): ca = os.path.join(self.tmp, "root.pem") with open(ca, "w") as f: f.write("PEM") self.fresh("--ca", ca) self.assertEqual(read(self.path("etc/kernelwatch/ca.pem")), "PEM") self.assertEqual(mode(self.path("etc/kernelwatch/ca.pem")), 0o644) self.assertIn("CA_FILE=/etc/kernelwatch/ca.pem\n", self.conf()) self.fresh() # re-registering without --ca keeps the CA already installed self.assertIn("CA_FILE=/etc/kernelwatch/ca.pem\n", self.conf()) def test_needrestart_is_installed_and_set_to_list_only(self): self.fresh("--with-needrestart") self.assertIn("apt-get install -y --no-install-recommends needrestart", self.calls()) self.assertIn("$nrconf{restart} = 'l';", read(self.path("etc/needrestart/conf.d/kernelwatch.conf"))) def test_needrestart_already_present_is_not_reinstalled(self): os.makedirs(self.path("usr/sbin")) open(self.path("usr/sbin/needrestart"), "w").close() os.chmod(self.path("usr/sbin/needrestart"), 0o755) self.fresh("--with-needrestart") self.assertFalse([c for c in self.calls() if c.startswith("apt-get")]) self.assertTrue(os.path.exists(self.path("etc/needrestart/conf.d/kernelwatch.conf"))) def test_without_needrestart_flag_nothing_is_touched(self): self.fresh() self.assertFalse(os.path.exists(self.path("etc/needrestart"))) def test_failed_first_report_fails_the_install_and_shows_the_journal(self): proc = self.install("--server", "https://k.example", env={"KW_START_FAIL": "1"}) self.assertEqual(proc.returncode, 1) self.assertIn("First report failed", proc.stderr) self.assertIn("journal: unit failed", proc.stderr) def test_unknown_os_warns_but_continues(self): self.os_release("fedora", "40") proc = self.fresh() self.assertIn("warning: untested OS fedora 40", proc.stderr) def test_supported_os_do_not_warn(self): for os_id, version in (("debian", "12"), ("debian", "13"), ("ubuntu", "22.04"), ("ubuntu", "24.04"), ("ubuntu", "26.04")): with self.subTest(os=f"{os_id}:{version}"): self.os_release(os_id, version) self.assertNotIn("warning", self.fresh().stderr) def test_bad_arguments_and_help(self): for args in (("--bogus",), ("--server",), ("--ca",)): with self.subTest(args=args): self.assertNotEqual(self.install(*args).returncode, 0) proc = self.install("--help") self.assertEqual(proc.returncode, 0) for flag in ("--server", "--with-apt-update", "--report-hostname", "--default-report-hostname"): self.assertIn(flag, proc.stdout) self.assertEqual(self.systemctl(), []) @unittest.skipIf(os.geteuid() == 0, "only meaningful when not root") def test_refuses_to_run_unprivileged(self): proc = self.run_script(AGENT_INSTALL, "--server", "https://k.example", with_root=False) self.assertEqual((proc.returncode, proc.stderr.strip()), (1, "run as root")) @unittest.skipUnless(shutil.which("bash"), "needs bash") class ServerInstallTest(InstallCase): def install(self, **env): proc = self.run_script(SERVER_INSTALL, env=env) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) return proc def test_fresh_install(self): proc = self.install(KW_ID_RC="1") useradd = [c for c in self.calls() if c.startswith("useradd")] self.assertEqual(len(useradd), 1) for flag in ("--system", "--no-create-home", "/usr/sbin/nologin"): self.assertIn(flag, useradd[0]) self.assertTrue(useradd[0].endswith(" kernelwatch")) opt = self.path("opt/kernelwatch") self.assertEqual(mode(os.path.join(opt, "kernelwatch-server")), 0o755) modules = sorted(n for n in os.listdir(os.path.join(SERVER_DIR, "kernelwatch")) if n.endswith(".py")) self.assertEqual(sorted(os.listdir(os.path.join(opt, "kernelwatch"))), modules) for module in modules: self.assertEqual(mode(os.path.join(opt, "kernelwatch", module)), 0o644) self.assertEqual(mode(self.path("usr/local/bin/kernelwatch")), 0o755) self.assertEqual(read(self.path("usr/local/bin/kernelwatch")), read(os.path.join(SERVER_DIR, "kernelwatch.sh"))) config = self.path("etc/kernelwatch/server.toml") self.assertEqual(read(config), read(os.path.join(SERVER_DIR, "server.toml.example"))) self.assertEqual(mode(config), 0o640) self.assertEqual(mode(self.path("var/lib/kernelwatch")), 0o750) self.assertEqual(self.systemctl(), [ "daemon-reload", "enable kernelwatch.service", "restart kernelwatch.service", "enable --now kernelwatch-alerts.timer", "enable --now kernelwatch-backup.timer"]) self.assertIn("listen_host = \"127.0.0.1\"", proc.stdout) self.assertIn("set-password admin", proc.stdout) def test_installs_every_server_unit(self): self.install() units = sorted(n for n in os.listdir(SERVER_DIR) if n.endswith((".service", ".timer"))) self.assertEqual(sorted(os.listdir(self.path("etc/systemd/system"))), units) for unit in units: self.assertEqual(mode(self.path("etc/systemd/system", unit)), 0o644) def test_unit_commands_exist_in_the_cli(self): """Every `kernelwatch-server ` a unit runs must be a real subcommand.""" help_text = subprocess.run(["python3", "-I", os.path.join(SERVER_DIR, "kernelwatch-server"), "--help"], capture_output=True, text=True, timeout=30).stdout commands = set() for unit in os.listdir(SERVER_DIR): if unit.endswith(".service"): commands.update(re.findall(r"kernelwatch-server (\S+)$", read(os.path.join(SERVER_DIR, unit)), re.M)) self.assertTrue(commands) for command in commands: self.assertRegex(help_text, rf"\b{re.escape(command)}\b") def test_existing_user_is_not_recreated(self): self.install(KW_ID_RC="0") self.assertFalse([c for c in self.calls() if c.startswith("useradd")]) def test_no_login_hint_once_a_user_exists(self): self.assertNotIn("set-password", self.install(KW_USERS="admin").stdout) def test_upgrade_keeps_config_and_replaces_the_code(self): self.install() config = self.path("etc/kernelwatch/server.toml") with open(config, "w") as f: f.write('listen_port = 9000\nntfy_url = "https://ntfy.example/t"\n') os.chmod(config, 0o640) stale = self.path("opt/kernelwatch/kernelwatch/removed_module.py") with open(stale, "w") as f: f.write("old") proc = self.install() self.assertEqual(read(config), 'listen_port = 9000\nntfy_url = "https://ntfy.example/t"\n') self.assertFalse(os.path.exists(stale)) self.assertEqual(sorted(os.listdir(self.path("opt"))), ["kernelwatch"]) self.assertIn("listen_port = 9000", proc.stdout) def test_recovers_from_an_interrupted_upgrade(self): os.makedirs(self.path("opt/kernelwatch.new/leftover")) os.makedirs(self.path("opt/kernelwatch.old")) self.install() self.assertEqual(sorted(os.listdir(self.path("opt"))), ["kernelwatch"]) @unittest.skipIf(os.geteuid() == 0, "only meaningful when not root") def test_refuses_to_run_unprivileged(self): proc = self.run_script(SERVER_INSTALL, with_root=False) self.assertEqual((proc.returncode, proc.stderr.strip()), (1, "run as root")) if __name__ == "__main__": unittest.main()