Files
kernel-automation/tests/test_web.py
T
patrickandClaude Opus 5.5 c9912d5fbc
CI / tests (Python 3.10) (pull_request) Successful in 36s
CI / tests (Python 3.11) (pull_request) Successful in 36s
CI / tests (Python 3.12) (pull_request) Successful in 37s
CI / tests (Python 3.13) (pull_request) Successful in 37s
CI / lint (pull_request) Successful in 4s
Check that the release's security repository is configured and fresh
security_count is only meaningful if apt has the release's security
suite. A host missing it from its sources shows 0 security updates
forever, and one whose apt can't fetch it (expired key, wrong URL after
a release upgrade, a mirror that fell behind) keeps the last copy while
the update stamps and other lists move on, so neither the simulation nor
the package list age notices.

The agent (0.9.0) now finds apt's list for <codename>-security by its
Suite: (Ubuntu) or Codename: (Debian) field, since file names depend on
the mirror (mirror+file: sources, several mirrors), and reports
security_repo_suite and security_repo_age_seconds from its Date:, the
newest copy winning. The server puts the host in update when there's no
such list, or when it's older than security_repo_stale_after_days
(default 7) while the package lists are otherwise fresh; if all of
them are old, the existing "package lists N days old" reason covers
it. Releases past the end of support are skipped: their suite has
stopped publishing, and support.check already says so. ESM suites
publish too rarely to judge by date and aren't checked.

The host page gets a "Security repository" row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 14:58:10 -05:00

300 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import threading
import unittest
import urllib.error
import urllib.parse
import urllib.request
from unittest import mock
from helpers import temp_config, tempdir
from kernelwatch import auth, db, web
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
OPENER = urllib.request.build_opener(NoRedirect)
class ServerCase(unittest.TestCase):
"""Runs a real server on an ephemeral port with a temp database."""
def setUp(self):
self._tmp = tempdir()
self.cfg = temp_config(self._tmp.name)
self.server = web.make_server(self.cfg)
self.base = "http://127.0.0.1:%d" % self.server.server_address[1]
threading.Thread(target=self.server.serve_forever, daemon=True).start()
def tearDown(self):
self.server.shutdown()
self.server.server_close()
self._tmp.cleanup()
def request(self, method, path, body=None, headers=None):
req = urllib.request.Request(self.base + path, data=body, method=method, headers=headers or {})
try:
with OPENER.open(req) as resp:
return resp.status, dict(resp.headers), resp.read().decode()
except urllib.error.HTTPError as err:
with err:
return err.code, dict(err.headers), err.read().decode()
def add_host(self, name):
token = auth.new_token()
conn = db.connect(self.cfg.db_path)
db.add_host(conn, name, auth.token_hash(token))
conn.close()
return token
def add_user(self, name, password):
conn = db.connect(self.cfg.db_path)
db.set_user(conn, name, auth.hash_password(password))
conn.close()
def post_report(self, token, payload):
return self.request("POST", "/api/v1/report", json.dumps(payload).encode(),
{"Authorization": f"Bearer {token}", "Content-Type": "application/json"})
def login(self, username, password, headers=None):
body = urllib.parse.urlencode({"username": username, "password": password}).encode()
return self.request("POST", "/login", body,
{"Content-Type": "application/x-www-form-urlencoded", **(headers or {})})
class IngestTest(ServerCase):
def test_requires_valid_token(self):
self.add_host("web01")
self.assertEqual(self.post_report("", {"kernel_running": "x"})[0], 401)
self.assertEqual(self.post_report("nope", {"kernel_running": "x"})[0], 401)
def test_accepts_report_and_binds_host_to_token(self):
token = self.add_host("web01")
status, _, _ = self.post_report(token, {"kernel_running": "6.8.0-85-generic",
"reported_hostname": "spoofed"})
self.assertEqual(status, 204)
conn = db.connect(self.cfg.db_path)
latest = db.latest_reports(conn)
conn.close()
self.assertEqual(latest[0]["host"], "web01")
self.assertEqual(latest[0]["report"]["kernel_running"], "6.8.0-85-generic")
def test_rejects_bad_payloads(self):
token = self.add_host("web01")
self.assertEqual(self.post_report(token, {"os_id": "debian"})[0], 400)
status, _, _ = self.request("POST", "/api/v1/report", b"{not json",
{"Authorization": f"Bearer {token}"})
self.assertEqual(status, 400)
status, _, _ = self.request("POST", "/api/v1/report", b"x" * (70 * 1024),
{"Authorization": f"Bearer {token}"})
self.assertEqual(status, 413)
def count_reports(self, host):
conn = db.connect(self.cfg.db_path)
try:
return conn.execute("SELECT COUNT(*) FROM reports WHERE host = ?", (host,)).fetchone()[0]
finally:
conn.close()
def test_reports_closer_than_min_interval_are_refused(self):
token, other = self.add_host("web01"), self.add_host("web02")
report = {"kernel_running": "6.8.0-85-generic"}
with mock.patch("kernelwatch.db.time.time", return_value=1_800_000_000):
self.assertEqual(self.post_report(token, report)[0], 204)
with mock.patch("kernelwatch.db.time.time", return_value=1_800_000_010):
status, headers, body = self.post_report(token, report)
self.assertEqual((status, headers["Retry-After"]), (429, "20"))
self.assertIn("too often", body)
# Limits are per host.
self.assertEqual(self.post_report(other, report)[0], 204)
self.assertEqual(self.count_reports("web01"), 1)
with mock.patch("kernelwatch.db.time.time", return_value=1_800_000_030):
self.assertEqual(self.post_report(token, report)[0], 204)
self.assertEqual(self.count_reports("web01"), 2)
def test_invalid_reports_do_not_count_against_the_interval(self):
token = self.add_host("web01")
self.assertEqual(self.post_report(token, {"os_id": "debian"})[0], 400)
self.assertEqual(self.post_report(token, {"kernel_running": "x"})[0], 204)
def test_zero_disables_the_limit(self):
self.add_host("web01")
conn = db.connect(self.cfg.db_path)
self.addCleanup(conn.close)
for _ in range(3):
self.assertEqual(db.add_report(conn, "web01", {"kernel_running": "x"}, 30), 0)
self.assertEqual(self.count_reports("web01"), 3)
class PhasedSummaryTest(unittest.TestCase):
def test_cells(self):
self.assertEqual(web.phased_summary({"os_id": "debian", "phased_packages": []})[0], "–")
self.assertEqual(web.phased_summary({"os_id": "ubuntu"})[0], "?")
self.assertEqual(web.phased_summary({"os_id": "ubuntu", "phased_packages": []})[0], "0")
self.assertEqual(web.phased_summary({"os_id": "ubuntu", "phased_packages": ["a", "b"]})[0], "2")
class DashboardTest(ServerCase):
def test_requires_login(self):
for path in ("/", "/host/web01"):
status, headers, _ = self.request("GET", path)
self.assertEqual(status, 303)
self.assertEqual(headers["Location"], "/login")
def test_public_endpoints(self):
self.assertEqual(self.request("GET", "/healthz")[0], 200)
self.assertEqual(self.request("GET", "/login")[0], 200)
def test_bad_login(self):
self.add_user("admin", "a-long-password")
self.assertEqual(self.login("admin", "wrong")[0], 401)
self.assertEqual(self.login("nobody", "a-long-password")[0], 401)
def test_login_rate_limited(self):
self.add_user("admin", "a-long-password")
for _ in range(web.LOGIN_MAX_FAILURES):
self.login("admin", "wrong")
self.assertEqual(self.login("admin", "a-long-password")[0], 429)
def test_cross_origin_login_refused(self):
self.add_user("admin", "a-long-password")
status, _, _ = self.login("admin", "a-long-password", {"Origin": "https://evil.example"})
self.assertEqual(status, 403)
def test_hostname_mismatch_shown_on_dashboard_and_host_page(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.post_report(token, {"kernel_running": "6.8.0-85-generic", "apt_lists_age_seconds": 60,
"reported_hostname": "db01.example.internal <b>"})
_, headers, _ = self.login("admin", "a-long-password")
cookie = {"Cookie": headers["Set-Cookie"].split(";")[0]}
for path in ("/", "/host/web01"):
body = self.request("GET", path, headers=cookie)[2]
self.assertIn("registered as web01 but reports itself as db01.example.internal &lt;b&gt;", body)
def test_host_page_shows_livepatch(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60,
"livepatch_state": "applied", "livepatch_fix_count": 2,
"livepatch_supported": "supported",
"livepatch_upgrade_required": "2099-09-07"})
_, headers, _ = self.login("admin", "a-long-password")
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("applied, 2 fixes applied, supported until 2099-09-07", body)
def test_host_page_shows_boot_space_and_unfinished_packages(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60,
"boot_size_kb": 487 * 1024, "boot_free_kb": 95 * 1024,
"dpkg_unfinished_packages": ["linux-image-6.8.0-138-generic"]})
_, headers, _ = self.login("admin", "a-long-password")
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("95 MB of 487 MB", body)
self.assertIn("<code>linux-image-6.8.0-138-generic</code>", body)
self.assertIn("/boot has 95 MB free, 81% used; the next kernel may not fit", body)
def test_host_page_shows_unattended_upgrades(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60,
"unattended_upgrades": "enabled",
"unattended_upgrades_success_age_seconds": 5 * 86400 + 7200,
"unattended_upgrades_run_age_seconds": 6 * 3600,
"unattended_upgrades_kept_back": ["openssl"]})
_, headers, _ = self.login("admin", "a-long-password")
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("enabled, last success 5d 2h before the report, last run 6h 0m before the report", body)
self.assertIn("<code>openssl</code>", body)
self.assertIn("unattended-upgrades last succeeded 5d ago and is failing", body)
def test_host_page_shows_os_support(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60,
"os_id": "ubuntu", "os_version_id": "24.04", "ubuntu_pro_attached": True,
"ubuntu_esm_infra": "enabled"})
_, headers, _ = self.login("admin", "a-long-password")
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("standard until 2029-05-31, ESM until 2034-04-25 (esm-infra: enabled)", body)
def test_host_page_shows_security_repo(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60,
"security_repo_suite": "noble-security",
"security_repo_age_seconds": 14 * 3600 + 120})
_, headers, _ = self.login("admin", "a-long-password")
cookie = {"Cookie": headers["Set-Cookie"].split(";")[0]}
body = self.request("GET", "/host/web01", headers=cookie)[2]
self.assertIn("noble-security, published 14h 2m before the report", body)
self.post_report(self.add_host("web02"), {"kernel_running": "6.8.0-136-generic",
"apt_lists_age_seconds": 60,
"security_repo_suite": "noble-security"})
body = self.request("GET", "/host/web02", headers=cookie)[2]
self.assertIn("noble-security: not in apt&#x27;s sources", body)
self.assertIn("apt has no noble-security repository", body)
def test_login_dashboard_logout(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.add_host("db01") # never reports
self.post_report(token, {"kernel_running": "6.8.0-85-generic",
"kernel_newest_installed": "6.8.0-87-generic",
"os_pretty_name": "Ubuntu 24.04.3 LTS <b>", "os_id": "ubuntu",
"apt_lists_age_seconds": 60,
"agent_version": "0.1.0",
"services_need_restart": ["nginx.service"],
"upgradable_count": 2, "security_count": 1,
"phased_packages": ["systemd", "udev", "libudev1"]})
status, headers, _ = self.login("admin", "a-long-password")
self.assertEqual(status, 303)
cookie = headers["Set-Cookie"].split(";")[0]
self.assertIn("HttpOnly", headers["Set-Cookie"])
self.assertIn("SameSite=Strict", headers["Set-Cookie"])
status, _, body = self.request("GET", "/", headers={"Cookie": cookie})
self.assertEqual(status, 200)
self.assertIn("web01", body)
self.assertIn("db01", body)
self.assertIn("6.8.0-87-generic installed", body)
self.assertIn("never reported", body)
self.assertIn("1 service needs restart: nginx", body)
self.assertIn("agent 0.1.0 is older", body)
self.assertIn("<th>Phased</th>", body)
self.assertIn("<td>2 (1 sec)</td>", body)
self.assertIn('held back by Ubuntu&#x27;s phased rollout, not offered to this host yet '
'(never security updates): systemd, udev, libudev1">3</td>', body)
web01_reasons = body[body.rindex('<td class="reasons">'):].split("</td>")[0] # last row
self.assertIn("security update", web01_reasons)
self.assertNotIn("phas", web01_reasons, "phasing is never a status reason")
self.assertIn("&lt;b&gt;", body, "report content must be escaped")
self.assertNotIn("<b>\n", body)
# Worst first: stale db01 before reboot web01.
self.assertLess(body.index("db01"), body.index("web01"))
status, _, body = self.request("GET", "/host/web01", headers={"Cookie": cookie})
self.assertEqual(status, 200)
self.assertIn("Recent reports", body)
self.assertEqual(self.request("GET", "/host/nope", headers={"Cookie": cookie})[0], 404)
status, _, _ = self.request("POST", "/logout", b"", {"Cookie": cookie})
self.assertEqual(status, 303)
self.assertEqual(self.request("GET", "/", headers={"Cookie": cookie})[0], 303)
def test_password_change_ends_sessions(self):
self.add_user("admin", "a-long-password")
_, headers, _ = self.login("admin", "a-long-password")
cookie = headers["Set-Cookie"].split(";")[0]
self.add_user("admin", "another-long-password")
self.assertEqual(self.request("GET", "/", headers={"Cookie": cookie})[0], 303)
if __name__ == "__main__":
unittest.main()