"""Runs the real agent script against stubbed system commands and a fake root.""" import json import os import shutil import stat import subprocess import threading import time import unittest from helpers import REPO, temp_config, tempdir from kernelwatch import auth, db, web AGENT = os.path.join(REPO, "agent", "kernelwatch-agent") DPKG_DEBIAN = """\ ii linux-image-6.12.48+deb13-amd64 ii linux-image-6.12.57+deb13-amd64 rc linux-image-6.12.38+deb13-amd64 ii linux-image-6.12.57+deb13-amd64-dbg """ APT_SIM_DEBIAN = """\ NOTE: This is only a simulation! Reading package lists... Inst libssl3t64 [3.5.1-1] (3.5.1-1+deb13u1 Debian-Security:13/stable-security [amd64]) Inst linux-image-6.12.60+deb13-amd64 (6.12.60-1 Debian-Security:13/stable-security [amd64]) Inst curl [8.14.1-2] (8.14.1-2+deb13u1 Debian:13.2/stable [amd64]) Conf libssl3t64 (3.5.1-1+deb13u1 Debian-Security:13/stable-security [amd64]) """ def stub(bindir, name, script): path = os.path.join(bindir, name) with open(path, "w") as f: f.write("#!/bin/sh\n" + script) os.chmod(path, os.stat(path).st_mode | stat.S_IEXEC) class AgentCase(unittest.TestCase): def setUp(self): self._tmp = tempdir() self.tmp = self._tmp.name self.root = os.path.join(self.tmp, "root") self.bin = os.path.join(self.tmp, "bin") for d in ("etc/kernelwatch", "proc", "run", "var/lib/apt/periodic", self.bin): os.makedirs(os.path.join(self.root, d), exist_ok=True) with open(os.path.join(self.root, "etc/os-release"), "w") as f: f.write('PRETTY_NAME="Debian GNU/Linux 13 (trixie)"\nID=debian\nVERSION_ID="13"\n') with open(os.path.join(self.root, "proc/uptime"), "w") as f: f.write("93784.21 180000.00\n") stamp = os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp") open(stamp, "w").close() two_hours_ago = time.time() - 7200 os.utime(stamp, (two_hours_ago, two_hours_ago)) stub(self.bin, "uname", 'case "$1" in -r) echo 6.12.48+deb13-amd64;; ' '-v) echo "#1 SMP PREEMPT_DYNAMIC Debian 6.12.48-1";; esac\n') stub(self.bin, "hostname", "echo web01.example\n") stub(self.bin, "dpkg-query", f"cat <<'X'\n{DPKG_DEBIAN}X\n") stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n") def tearDown(self): self._tmp.cleanup() def run_agent(self, *args, env=None): full_env = { "PATH": f"{self.bin}:{os.environ['PATH']}", "KERNELWATCH_ROOT": self.root, **(env or {}), } return subprocess.run(["bash", AGENT, *args], env=full_env, capture_output=True, text=True, timeout=30) def report(self): proc = self.run_agent("--print") self.assertEqual(proc.returncode, 0, proc.stderr) return json.loads(proc.stdout) @unittest.skipUnless(shutil.which("bash") and shutil.which("curl"), "needs bash and curl") class AgentReportTest(AgentCase): def test_debian_report(self): r = self.report() self.assertEqual(r["os_id"], "debian") self.assertEqual(r["os_version_id"], "13") self.assertEqual(r["os_pretty_name"], "Debian GNU/Linux 13 (trixie)") self.assertEqual(r["reported_hostname"], "web01.example") self.assertEqual(r["kernel_running"], "6.12.48+deb13-amd64") self.assertEqual(r["kernels_installed"], ["6.12.48+deb13-amd64", "6.12.57+deb13-amd64"]) self.assertEqual(r["kernel_newest_installed"], "6.12.57+deb13-amd64") self.assertIsNone(r["needrestart_ksta"]) self.assertFalse(r["reboot_required"]) self.assertEqual(r["upgradable_count"], 3) self.assertEqual(r["security_count"], 2) self.assertEqual(r["kernel_upgradable"], ["linux-image-6.12.60+deb13-amd64"]) self.assertAlmostEqual(r["apt_lists_age_seconds"], 7200, delta=60) self.assertEqual(r["uptime_seconds"], 93784) def test_ubuntu_with_needrestart_and_reboot_required(self): with open(os.path.join(self.root, "etc/os-release"), "w") as f: f.write('PRETTY_NAME="Ubuntu 24.04.3 LTS"\nID=ubuntu\nVERSION_ID="24.04"\n') stub(self.bin, "uname", 'case "$1" in -r) echo 6.8.0-85-generic;; -v) echo "#85-Ubuntu";; esac\n') stub(self.bin, "dpkg-query", "printf 'ii linux-image-6.8.0-85-generic\\n" "ii linux-image-unsigned-6.8.0-100-generic\\n'\n") stub(self.bin, "apt-get", "echo 'NOTE: This is only a simulation!'\n") stub(self.bin, "needrestart", "printf 'NEEDRESTART-VER: 3.6\\nNEEDRESTART-KCUR: 6.8.0-85-generic\\n" "NEEDRESTART-KEXP: 6.8.0-100-generic\\nNEEDRESTART-KSTA: 3\\n'\n") open(os.path.join(self.root, "run/reboot-required"), "w").close() with open(os.path.join(self.root, "run/reboot-required.pkgs"), "w") as f: f.write('linux-image-6.8.0-100-generic\nlinux-base\nlinux-base\n') r = self.report() self.assertEqual(r["os_id"], "ubuntu") self.assertEqual(r["kernel_newest_installed"], "6.8.0-100-generic", "sort -V, not lexical") self.assertEqual(r["needrestart_ksta"], 3) self.assertEqual(r["needrestart_kexp"], "6.8.0-100-generic") self.assertTrue(r["reboot_required"]) self.assertEqual(r["reboot_required_pkgs"], ["linux-base", "linux-image-6.8.0-100-generic"]) self.assertEqual(r["upgradable_count"], 0) self.assertEqual(r["security_count"], 0) self.assertEqual(r["kernel_upgradable"], []) def test_hostile_strings_stay_valid_json(self): stub(self.bin, "hostname", "printf 'a\"b\\\\c\\tq'\n") self.assertEqual(self.report()["reported_hostname"], 'a"b\\cq') def test_missing_apt_stamps(self): os.remove(os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp")) self.assertIsNone(self.report()["apt_lists_age_seconds"]) def test_send_without_config_fails_cleanly(self): proc = self.run_agent() self.assertNotEqual(proc.returncode, 0) self.assertIn("SERVER_URL", proc.stderr) @unittest.skipUnless(shutil.which("bash") and shutil.which("curl"), "needs bash and curl") class AgentEndToEndTest(AgentCase): def test_agent_reports_to_server(self): cfg = temp_config(self.tmp) server = web.make_server(cfg) threading.Thread(target=server.serve_forever, daemon=True).start() try: token = auth.new_token() conn = db.connect(cfg.db_path) db.add_host(conn, "web01", auth.token_hash(token)) conn.close() port = server.server_address[1] with open(os.path.join(self.root, "etc/kernelwatch/agent.conf"), "w") as f: f.write(f"SERVER_URL=http://127.0.0.1:{port}/\n") creds = os.path.join(self.tmp, "creds") os.mkdir(creds) with open(os.path.join(creds, "token"), "w") as f: f.write(token + "\n") proc = self.run_agent(env={"CREDENTIALS_DIRECTORY": creds}) self.assertEqual(proc.returncode, 0, proc.stderr) self.assertNotIn(token, proc.stdout + proc.stderr) conn = db.connect(cfg.db_path) latest = db.latest_reports(conn) conn.close() self.assertEqual(latest[0]["report"]["kernel_newest_installed"], "6.12.57+deb13-amd64") with open(os.path.join(creds, "token"), "w") as f: f.write("wrong-token\n") proc = self.run_agent(env={"CREDENTIALS_DIRECTORY": creds}) self.assertNotEqual(proc.returncode, 0) finally: server.shutdown() server.server_close() if __name__ == "__main__": unittest.main()