"""Runs agent/deploy.sh with ssh/sudo stubbed to run "remote" commands locally. The dashboard side is the real kernelwatch CLI on a temp database; install.sh is replaced by a recorder so we can check what each host received. """ import os import re import shutil import stat import subprocess import sys import unittest from helpers import REPO, tempdir from kernelwatch import auth, db AGENT_DIR = os.path.join(REPO, "agent") SSH_STUB = r"""#!/usr/bin/env bash while [[ $1 == -* ]]; do case $1 in -o) shift 2 ;; *) shift ;; esac done target=$1; shift echo "$target" >> "$KW_LOG/ssh.log" export KW_TARGET=$target mkdir -p "$KW_HOMES/$target" && cd "$KW_HOMES/$target" exec bash -c "$*" """ FAKE_INSTALL = r"""#!/usr/bin/env bash out=$KW_LOG/install-$KW_TARGET printf '%s\n' "$@" > "$out.args" while (($#)); do [[ $1 == --token-file ]] && cp "$2" "$out.token" shift done """ def write_exec(path, text): with open(path, "w") as f: f.write(text) os.chmod(path, os.stat(path).st_mode | stat.S_IEXEC) @unittest.skipUnless(shutil.which("bash") and shutil.which("tar"), "needs bash and tar") class DeployTest(unittest.TestCase): def setUp(self): self._tmp = tempdir() t = self.tmp = self._tmp.name self.agent = os.path.join(t, "agent") self.log = os.path.join(t, "log") self.homes = os.path.join(t, "homes") self.remote_tmp = os.path.join(t, "remote-tmp") bindir = os.path.join(t, "bin") for d in (self.agent, self.log, self.homes, self.remote_tmp, bindir): os.makedirs(d) for name in ("deploy.sh", "kernelwatch-agent", "kernelwatch-agent.service", "kernelwatch-agent.timer", "kernelwatch-needrestart.service", "kernelwatch-livepatch", "kernelwatch-livepatch.service", "kernelwatch-apt-update.service"): shutil.copy2(os.path.join(AGENT_DIR, name), self.agent) write_exec(os.path.join(self.agent, "install.sh"), FAKE_INSTALL) self.db_path = os.path.join(t, "kw.db") server_conf = os.path.join(t, "server.toml") with open(server_conf, "w") as f: f.write(f'db_path = "{self.db_path}"\n') write_exec(os.path.join(bindir, "ssh"), SSH_STUB) write_exec(os.path.join(bindir, "sudo"), '#!/bin/sh\nexec "$@"\n') write_exec(os.path.join(bindir, "hostname"), '#!/bin/sh\nt=${KW_TARGET#*@}; echo "${t%%.*}"\n') write_exec(os.path.join(bindir, "kernelwatch"), f'#!/bin/sh\nexec {sys.executable} {REPO}/server/kernelwatch-server "$@"\n') with open(os.path.join(self.agent, "deploy.conf"), "w") as f: f.write("SERVER_URL=https://kernels.example.test\nDASHBOARD=admin@dash\n") self.hosts_file = os.path.join(self.agent, "hosts") with open(self.hosts_file, "w") as f: f.write("# fleet\nweb01.example.test\npatrick@10.0.0.31 db01 # explicit name\n") self.env = { "PATH": f"{bindir}:{os.environ['PATH']}", "KW_LOG": self.log, "KW_HOMES": self.homes, "TMPDIR": self.remote_tmp, "KERNELWATCH_CONFIG": server_conf, } def tearDown(self): self._tmp.cleanup() def deploy(self, *args): return subprocess.run(["bash", os.path.join(self.agent, "deploy.sh"), *args], env=self.env, capture_output=True, text=True, timeout=60) def installed(self, target): base = os.path.join(self.log, f"install-{target}") with open(base + ".args") as f: args = f.read().split() token = None if os.path.exists(base + ".token"): with open(base + ".token") as f: token = f.read().strip() return args, token def host_for(self, token): conn = db.connect(self.db_path) try: return db.host_for_token(conn, auth.token_hash(token)) finally: conn.close() def assert_clean(self): self.assertEqual(os.listdir(self.remote_tmp), [], "remote temp dirs removed") dash = os.path.join(self.homes, "admin@dash") if os.path.isdir(dash): self.assertEqual(os.listdir(dash), [], "no token left on the dashboard") def test_register_hosts_from_file_and_cli(self): proc = self.deploy("--register", "web01.example.test", "patrick@10.0.0.31", "new01.example.test") self.assertEqual(proc.returncode, 0, proc.stderr) for target, name in (("web01.example.test", "web01"), ("patrick@10.0.0.31", "db01"), ("new01.example.test", "new01")): with self.subTest(target=target): args, token = self.installed(target) self.assertIn("--server", args) self.assertIn("https://kernels.example.test", args) self.assertEqual(self.host_for(token), name, "token authenticates as that host") self.assertNotIn(token, proc.stdout + proc.stderr, "token never printed") with open(self.hosts_file) as f: self.assertIn("new01.example.test new01\n", f.read(), "new host remembered") self.assert_clean() def test_upgrade_all_keeps_config(self): proc = self.deploy() self.assertEqual(proc.returncode, 0, proc.stderr) for target in ("web01.example.test", "patrick@10.0.0.31"): args, token = self.installed(target) self.assertEqual(len(args), 0, "plain install.sh: keeps existing config and token") self.assertIsNone(token) with open(os.path.join(self.log, "ssh.log")) as f: self.assertNotIn("admin@dash", f.read(), "upgrades don't touch the dashboard") self.assert_clean() def test_install_args_passed_through(self): proc = self.deploy("web01.example.test", "--", "--with-needrestart") self.assertEqual(proc.returncode, 0, proc.stderr) self.assertEqual(self.installed("web01.example.test")[0], ["--with-needrestart"]) def test_register_existing_fails_but_others_continue(self): self.assertEqual(self.deploy("--register", "web01.example.test").returncode, 0) proc = self.deploy("--register", "web01.example.test", "new01.example.test") self.assertEqual(proc.returncode, 1) self.assertIn("already exists", proc.stderr) self.assertIn("Failed (1/2): web01.example.test", proc.stderr) self.assertEqual(self.host_for(self.installed("new01.example.test")[1]), "new01") self.assert_clean() def test_rotate(self): self.deploy("--register", "web01.example.test") old = self.installed("web01.example.test")[1] proc = self.deploy("--rotate", "web01.example.test") self.assertEqual(proc.returncode, 0, proc.stderr) new = self.installed("web01.example.test")[1] self.assertNotEqual(old, new) self.assertIsNone(self.host_for(old)) self.assertEqual(self.host_for(new), "web01") def test_register_needs_explicit_hosts(self): proc = self.deploy("--register") self.assertNotEqual(proc.returncode, 0) self.assertIn("name the hosts", proc.stderr) def test_dry_run_touches_nothing(self): proc = self.deploy("--dry-run", "--register", "new01.example.test") self.assertEqual(proc.returncode, 0, proc.stderr) self.assertIn("kernelwatch add-host", proc.stderr) self.assertFalse(os.path.exists(os.path.join(self.log, "ssh.log"))) def test_missing_config(self): os.remove(os.path.join(self.agent, "deploy.conf")) proc = self.deploy() self.assertNotEqual(proc.returncode, 0) self.assertIn("deploy.conf.example", proc.stderr) class PackagingTest(unittest.TestCase): def read(self, name): with open(os.path.join(AGENT_DIR, name)) as f: return f.read() def test_deploy_ships_every_file_install_uses(self): files = re.search(r"^FILES=\(([^)]*)\)", self.read("deploy.sh"), re.M).group(1).split() used = set(re.findall(r'"\$here/([^"]+)"', self.read("install.sh"))) self.assertTrue(used) self.assertEqual(used - set(files), set()) def test_apt_update_is_opt_in_and_runs_before_reports(self): unit = self.read("kernelwatch-apt-update.service") self.assertIn("ConditionPathExists=/etc/kernelwatch/apt-update", unit) self.assertIn("ExecStart=-/usr/bin/apt-get -q update", unit, "failure mustn't block the report") agent = self.read("kernelwatch-agent.service") for key in ("Wants=", "After="): line = next(l for l in agent.splitlines() if l.startswith(key)) self.assertIn("kernelwatch-apt-update.service", line) if __name__ == "__main__": unittest.main()