apt lists updates deferred by phasing in an indented block rather than as Inst lines, so they were already excluded from the counts but invisible. The agent now parses that block into phased_packages; the dashboard shows "+N phased" in the Updates column (with a tooltip) and the list on the host page. Phasing never affects status: Ubuntu doesn't phase security updates, and there's nothing to act on until apt offers the update. Run the apt simulation with LC_ALL=C since we parse its messages (the systemd unit already runs in the C locale; manual --print may not). Agent and server 0.3.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
265 lines
12 KiB
Python
265 lines
12 KiB
Python
"""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")
|
|
stub(self.bin, "dpkg-query", 'case "$*" in *Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n'
|
|
f"{DPKG_DEBIAN}X\n;; esac\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.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 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_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_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()
|