"""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 from kernelwatch.status import evaluate 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") # The full-database query (unfinished packages) prints $KERNELWATCH_ROOT/dpkg-all. stub(self.bin, "dpkg-query", 'case "$*" in *binary:Package*) cat "$KERNELWATCH_ROOT/dpkg-all" 2>/dev/null;; ' '*Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n' f"{DPKG_DEBIAN}X\n;; esac\n") self.stub_df("/dev/sda1 999320 187364 743144 21% /boot\n") stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n") def tearDown(self): self._tmp.cleanup() def stub_df(self, line, rc=0): stub(self.bin, "df", "echo 'Filesystem 1024-blocks Used Available Capacity Mounted on'\n" f"cat <<'X'\n{line}X\nexit {rc}\n") 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.assertEqual(r["kernel_running_pkg_version"], "6.12.48-2") 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.assertEqual(r["phased_packages"], [], "Debian: no phasing") self.assertAlmostEqual(r["apt_lists_age_seconds"], 7200, delta=60) self.assertEqual(r["uptime_seconds"], 93784) self.assertIsNone(r["services_need_restart"], "no needrestart results: unknown") self.assertIsNone(r["sessions_need_restart"]) def write_needrestart(self, text, age=60): d = os.path.join(self.root, "run/kernelwatch") os.makedirs(d, exist_ok=True) path = os.path.join(d, "needrestart") with open(path, "w") as f: f.write(text) t = time.time() - age os.utime(path, (t, t)) def test_needrestart_results(self): self.write_needrestart( "NEEDRESTART-VER: 3.6\nNEEDRESTART-KCUR: 6.12.48+deb13-amd64\n" "NEEDRESTART-KEXP: 6.12.57+deb13-amd64\nNEEDRESTART-KSTA: 3\n" "NEEDRESTART-SVC: ssh.service\nNEEDRESTART-SVC: nginx.service\n" "NEEDRESTART-SVC: nginx.service\nNEEDRESTART-SESS: patrick @ session #3\n") r = self.report() self.assertEqual(r["needrestart_ksta"], 3) self.assertEqual(r["needrestart_kexp"], "6.12.57+deb13-amd64") self.assertEqual(r["services_need_restart"], ["nginx.service", "ssh.service"]) self.assertEqual(r["sessions_need_restart"], 1) def write_livepatch(self, text, age=60): d = os.path.join(self.root, "run/kernelwatch") os.makedirs(d, exist_ok=True) path = os.path.join(d, "livepatch") with open(path, "w") as f: f.write(text) t = time.time() - age os.utime(path, (t, t)) def test_boot_space(self): r = self.report() self.assertEqual((r["boot_size_kb"], r["boot_free_kb"]), (999320, 743144)) def test_boot_space_unknown_when_df_fails(self): self.stub_df("", rc=1) r = self.report() self.assertIsNone(r["boot_size_kb"]) self.assertIsNone(r["boot_free_kb"]) def test_boot_space_unknown_when_df_prints_garbage(self): self.stub_df("/dev/sda1 - - - - /boot\n") self.assertIsNone(self.report()["boot_free_kb"]) def test_unfinished_packages(self): with open(os.path.join(self.root, "dpkg-all"), "w") as f: f.write("ii \tcurl\n" "iF \tlinux-image-6.12.60+deb13-amd64\n" "iU \tlinux-headers-6.12.60+deb13-amd64\n" "iHR\tlibfoo1:amd64\n" "iiR\tlibbar2\n" "it \tman-db\n" "rc \told-pkg\n") self.assertEqual(self.report()["dpkg_unfinished_packages"], [ "libbar2", "libfoo1:amd64", "linux-headers-6.12.60+deb13-amd64", "linux-image-6.12.60+deb13-amd64", "man-db"]) def test_no_unfinished_packages(self): with open(os.path.join(self.root, "dpkg-all"), "w") as f: f.write("ii \tcurl\nrc \told-pkg\n") self.assertEqual(self.report()["dpkg_unfinished_packages"], []) def write_pro_status(self, text): d = os.path.join(self.root, "var/lib/ubuntu-advantage") os.makedirs(d, exist_ok=True) with open(os.path.join(d, "status.json"), "w") as f: f.write(text) def test_ubuntu_pro_attached_with_esm(self): self.write_pro_status(json.dumps({"attached": True, "services": [ {"name": "esm-apps", "status": "enabled"}, {"name": "esm-infra", "status": "enabled"}, {"name": "livepatch", "status": "enabled"}]})) r = self.report() self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (True, "enabled")) def test_ubuntu_pro_attached_esm_disabled(self): self.write_pro_status(json.dumps({"attached": True, "services": [ {"name": "esm-infra", "status": "disabled"}]})) r = self.report() self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (True, "disabled")) def test_ubuntu_pro_not_attached(self): # Unattached, the cache lists services as available, which isn't the same as on. self.write_pro_status(json.dumps({"attached": False, "services": [ {"name": "esm-infra", "available": "yes", "status": "enabled"}]})) r = self.report() self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (False, None)) def test_no_pro_client_or_unreadable_status(self): r = self.report() self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (None, None)) self.write_pro_status("{not json") r = self.report() self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (None, None)) def test_odd_esm_status_is_dropped(self): self.write_pro_status(json.dumps({"attached": True, "services": [ {"name": "esm-infra", "status": "en abled\" x"}]})) r = self.report() self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (True, None)) def test_every_reported_field_is_accepted_by_the_server(self): from kernelwatch.report import FIELDS self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n") self.write_pro_status('{"attached": true, "services": [{"name": "esm-infra", "status": "enabled"}]}') self.assertEqual(sorted(set(self.report()) - set(FIELDS)), []) def write_conf(self, text): with open(os.path.join(self.root, "etc/kernelwatch/agent.conf"), "w") as f: f.write(text) def test_report_hostname_overrides_the_machines_own(self): self.write_conf("SERVER_URL=http://x\nREPORT_HOSTNAME=iris\n") self.assertEqual(self.report()["reported_hostname"], "iris") def test_blank_report_hostname_uses_the_machines_own(self): self.write_conf("REPORT_HOSTNAME=\n") self.assertEqual(self.report()["reported_hostname"], "web01.example") def test_report_hostname_is_json_escaped(self): self.write_conf('REPORT_HOSTNAME=a"b\\c\n') self.assertEqual(self.report()["reported_hostname"], 'a"b\\c') def test_no_livepatch_file_reports_nulls(self): r = self.report() for key in ("state", "check_state", "supported", "upgrade_required", "fix_count"): self.assertIsNone(r["livepatch_" + key]) def test_livepatch_results(self): self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-CHECK: checked\n" "LIVEPATCH-SUPPORTED: supported\nLIVEPATCH-UPGRADE-REQUIRED: 2027-09-07\n" "LIVEPATCH-FIXES: 2\n") r = self.report() self.assertEqual((r["livepatch_state"], r["livepatch_check_state"], r["livepatch_supported"]), ("applied", "checked", "supported")) self.assertEqual((r["livepatch_upgrade_required"], r["livepatch_fix_count"]), ("2027-09-07", 2)) def test_stale_livepatch_results_ignored(self): self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n", age=3 * 3600) r = self.report() self.assertIsNone(r["livepatch_state"]) self.assertIsNone(r["livepatch_fix_count"]) def test_agent_never_runs_livepatch_itself(self): marker = os.path.join(self.tmp, "livepatch-ran") stub(self.bin, "canonical-livepatch", f"touch {marker}\n") self.report() self.assertFalse(os.path.exists(marker)) def test_needrestart_nothing_to_restart(self): self.write_needrestart("NEEDRESTART-VER: 3.6\nNEEDRESTART-KSTA: 1\n") r = self.report() self.assertEqual(r["services_need_restart"], []) self.assertEqual(r["sessions_need_restart"], 0) def test_stale_needrestart_results_ignored(self): self.write_needrestart("NEEDRESTART-KSTA: 3\nNEEDRESTART-SVC: ssh.service\n", age=3 * 3600) r = self.report() self.assertIsNone(r["needrestart_ksta"]) self.assertIsNone(r["services_need_restart"]) def test_agent_never_runs_needrestart_itself(self): marker = os.path.join(self.tmp, "needrestart-ran") stub(self.bin, "needrestart", f"touch {marker}\n") self.report() self.assertFalse(os.path.exists(marker)) 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", 'case "$*" in *Version*) echo "ii 6.8.0-85.85";; ' "*) printf 'ii linux-image-6.8.0-85-generic\\n" "ii linux-image-unsigned-6.8.0-100-generic\\n';; esac\n") stub(self.bin, "apt-get", "echo 'NOTE: This is only a simulation!'\n") self.write_needrestart("NEEDRESTART-VER: 3.6\nNEEDRESTART-KCUR: 6.8.0-85-generic\n" "NEEDRESTART-KEXP: 6.8.0-100-generic\nNEEDRESTART-KSTA: 3\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["kernel_running_pkg_version"], "6.8.0-85.85") 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_ubuntu_phased_updates(self): # Shape of real `apt-get -s dist-upgrade` output on 24.04 with phasing. stub(self.bin, "apt-get", """cat <<'X' NOTE: This is only a simulation! apt-get needs root privileges for real execution. Keep also in mind that locking is deactivated, so don't depend on the relevance to the real current situation! Reading package lists... Building dependency tree... Reading state information... Calculating upgrade... The following upgrades have been deferred due to phasing: libnss-systemd libpam-systemd libsystemd-shared libsystemd0 libudev1 systemd systemd-resolved udev The following packages will be upgraded: curl libcurl4t64 2 upgraded, 0 newly installed, 0 to remove and 8 not upgraded. Inst libcurl4t64 [8.5.0-2ubuntu10.6] (8.5.0-2ubuntu10.7 Ubuntu:24.04/noble-security [amd64]) Inst curl [8.5.0-2ubuntu10.6] (8.5.0-2ubuntu10.7 Ubuntu:24.04/noble-security [amd64]) Conf libcurl4t64 (8.5.0-2ubuntu10.7 Ubuntu:24.04/noble-security [amd64]) X """) r = self.report() self.assertEqual(r["upgradable_count"], 2) self.assertEqual(r["security_count"], 2) self.assertEqual(r["phased_packages"], sorted( ["libnss-systemd", "libpam-systemd", "libsystemd-shared", "libsystemd0", "libudev1", "systemd", "systemd-resolved", "udev"])) def test_apt_told_it_is_not_in_a_chroot(self): # Otherwise unprivileged apt thinks it's in a chroot and ignores phasing # (seen on a real 26.04 host: 4 phased updates counted as installable). stub(self.bin, "apt-get", 'case "$*" in *Dir::Bin::ischroot=/bin/false*) ;; *) exit 1;; esac\n' 'echo "The following upgrades have been deferred due to phasing:"\n' 'echo " snapd open-vm-tools"\n' 'echo "0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded."\n') r = self.report() self.assertEqual(r["phased_packages"], ["open-vm-tools", "snapd"]) self.assertEqual(r["upgradable_count"], 0) def test_apt_runs_in_c_locale(self): stub(self.bin, "apt-get", 'echo "Inst locale-$LC_ALL [1] (2 x [amd64])"\n') self.assertEqual(self.report()["upgradable_count"], 1) stub(self.bin, "apt-get", '[ "$LC_ALL" = C ] || exit 1; echo "Inst ok [1] (2 x [amd64])"\n') self.assertEqual(self.report()["upgradable_count"], 1) def test_apt_simulation_ok(self): r = self.report() self.assertIs(r["apt_simulation_ok"], True) self.assertIsNone(r["apt_simulation_error"]) def test_apt_failure_reports_unknown_counts_not_zero(self): # A failed simulation prints no Inst lines; that must not read as "no updates". stub(self.bin, "apt-get", "echo 'Reading package lists...'\n" "echo 'W: Some warning' >&2\n" "echo \"E: Unmet dependencies. Try 'apt --fix-broken install'.\" >&2\n" "exit 100\n") r = self.report() self.assertIs(r["apt_simulation_ok"], False) self.assertEqual(r["apt_simulation_error"], "Unmet dependencies. Try 'apt --fix-broken install'.") for key in ("upgradable_count", "security_count", "kernel_upgradable", "phased_packages"): self.assertIsNone(r[key], key) def test_apt_failure_without_an_error_line(self): stub(self.bin, "apt-get", "echo 'something broke' >&2\nexit 1\n") self.assertEqual(self.report()["apt_simulation_error"], "something broke") stub(self.bin, "apt-get", "exit 100\n") self.assertEqual(self.report()["apt_simulation_error"], "apt-get exited with status 100") def test_apt_warnings_dont_mix_into_the_simulation(self): stub(self.bin, "apt-get", f"echo 'W: Inst fake [1] (2 x [amd64])' >&2\ncat <<'X'\n{APT_SIM_DEBIAN}X\n") r = self.report() self.assertIs(r["apt_simulation_ok"], True) self.assertEqual(r["upgradable_count"], 3) 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") # Stub uname -v says build 6.12.48-1, dpkg says 6.12.48-2: upgraded in place. status = evaluate(latest[0]["received_at"], latest[0]["report"], time.time(), cfg) self.assertEqual(status.level, "reboot") self.assertIn("upgraded in place to 6.12.48-2", status.reasons[0]) 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()