Files
kernel-automation/server/kernelwatch/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

583 lines
24 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.
"""HTTP server: the agent ingest API and the authenticated dashboard.
Meant to sit behind a TLS-terminating reverse proxy (Caddy, nginx). The
standard-library server is plenty for a fleet of tens or hundreds of hosts
reporting hourly.
"""
from __future__ import annotations
import html
import json
import re
import sys
import threading
import time
from http import HTTPStatus
from http.cookies import CookieError, SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any
from urllib.parse import parse_qs, quote, unquote, urlsplit
from . import __version__, auth, db, support
from .config import Config
from .report import MAX_BODY_BYTES, ReportError, sanitize
from .status import LEVELS, Status, evaluate
SESSION_COOKIE = "kw_session"
HOST_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$")
LOGIN_MAX_FAILURES = 10
LOGIN_WINDOW_SECONDS = 15 * 60
e = html.escape
class LoginLimiter:
"""Per-client-IP failed login counter with a fixed window."""
def __init__(self) -> None:
self._lock = threading.Lock()
self._failures: dict[str, tuple[int, float]] = {}
def blocked(self, ip: str) -> bool:
with self._lock:
count, start = self._failures.get(ip, (0, 0.0))
if time.monotonic() - start > LOGIN_WINDOW_SECONDS:
self._failures.pop(ip, None)
return False
return count >= LOGIN_MAX_FAILURES
def failed(self, ip: str) -> None:
with self._lock:
now = time.monotonic()
count, start = self._failures.get(ip, (0, now))
if now - start > LOGIN_WINDOW_SECONDS:
count, start = 0, now
self._failures[ip] = (count + 1, start)
def succeeded(self, ip: str) -> None:
with self._lock:
self._failures.pop(ip, None)
# --- formatting -------------------------------------------------------------
def ago(ts: float | None, now: float) -> str:
if ts is None:
return "never"
s = max(0, int(now - ts))
for unit, size in (("d", 86400), ("h", 3600), ("m", 60)):
if s >= size:
return f"{s // size}{unit} ago"
return "just now"
def duration(seconds: int | None) -> str:
if seconds is None:
return "–"
d, rem = divmod(seconds, 86400)
return f"{d}d {rem // 3600}h" if d else f"{rem // 3600}h {rem % 3600 // 60}m"
def utc(ts: float | None) -> str:
return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(ts)) if ts else ""
def unattended_upgrades_summary(report: dict[str, Any]) -> str | None:
state = report.get("unattended_upgrades")
if state != "enabled":
return state # "disabled", "not-installed", or None from agents before 0.8.0
last = {"success": report.get("unattended_upgrades_success_age_seconds"),
"run": report.get("unattended_upgrades_run_age_seconds")}
return "enabled, " + ", ".join(
f"last {what} " + ("never" if age is None else f"{duration(age)} before the report")
for what, age in last.items())
def security_repo_summary(report: dict[str, Any]) -> str | None:
suite = report.get("security_repo_suite")
if not suite:
return None # agents before 0.9.0, or no release codename
age = report.get("security_repo_age_seconds")
if age is None:
return f"{suite}: not in apt's sources"
return f"{suite}, published {duration(age)} before the report"
def phased_summary(report: dict[str, Any]) -> tuple[str, str]:
"""(short cell text, full description) for updates deferred by Ubuntu's phasing."""
if report.get("os_id") not in (None, "ubuntu"):
return "–", "this distribution doesn't phase updates"
pkgs = report.get("phased_packages")
if pkgs is None:
return "?", "unknown: agent too old to report phased updates"
if not pkgs:
return "0", "none deferred"
return str(len(pkgs)), ("held back by Ubuntu's phased rollout, not offered to this host "
"yet (never security updates): " + ", ".join(pkgs))
def services_summary(report: dict[str, Any]) -> tuple[str, str]:
"""(short cell text, full description) for services needing a restart."""
services = report.get("services_need_restart")
if services is None:
return "?", "unknown: needrestart not installed (install.sh --with-needrestart)"
if not services:
return "0", "none"
return str(len(services)), ", ".join(services)
def badge(level: str) -> str:
return f'<span class="badge {e(level)}">{e(level)}</span>'
STYLE = """
:root {
color-scheme: light dark;
--bg: #f7f7f8; --fg: #1d1d1f; --muted: #6b6b72; --card: #fff; --line: #e2e2e6;
--ok: #1a7f37; --update: #9a6700; --reboot: #cf222e; --stale: #6e7781;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111214; --fg: #e8e8ea; --muted: #9a9aa2; --card: #1a1b1e; --line: #2c2d31;
--ok: #3fb950; --update: #d29922; --reboot: #f85149; --stale: #8b949e;
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--fg);
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; }
header { display: flex; align-items: center; gap: 16px; padding: 12px 16px;
border-bottom: 1px solid var(--line); background: var(--card); }
header h1 { font-size: 16px; margin: 0; flex: 1; }
header h1 a { color: inherit; text-decoration: none; }
header form { margin: 0; }
main { padding: 16px; max-width: 1400px; margin: 0 auto; }
a { color: inherit; }
button { font: inherit; padding: 6px 12px; border: 1px solid var(--line); border-radius: 6px;
background: var(--card); color: var(--fg); cursor: pointer; }
.summary { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; }
.summary div { background: var(--card); border: 1px solid var(--line); border-radius: 8px;
padding: 8px 14px; min-width: 110px; }
.summary b { display: block; font-size: 22px; }
.table-wrap { overflow-x: auto; background: var(--card); border: 1px solid var(--line);
border-radius: 8px; }
table { border-collapse: collapse; width: 100%; }
th, td { text-align: left; padding: 8px 12px; border-bottom: 1px solid var(--line);
vertical-align: top; white-space: nowrap; }
th { font-weight: 600; color: var(--muted); font-size: 12px; text-transform: uppercase; }
tr:last-child td { border-bottom: 0; }
td.reasons { white-space: normal; color: var(--muted); min-width: 260px; }
code { font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; }
.muted { color: var(--muted); }
.badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12px;
font-weight: 600; color: #fff; }
.badge.ok { background: var(--ok); } .badge.update { background: var(--update); }
.badge.reboot { background: var(--reboot); } .badge.stale { background: var(--stale); }
.login { max-width: 340px; margin: 12vh auto; background: var(--card); padding: 24px;
border: 1px solid var(--line); border-radius: 10px; }
.login h1 { font-size: 18px; margin: 0 0 16px; }
.login label { display: block; margin-bottom: 12px; }
.login input { display: block; width: 100%; margin-top: 4px; padding: 8px; font: inherit;
border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--fg); }
.login button { width: 100%; }
.error { color: var(--reboot); }
dl { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0 0 24px; }
dt { color: var(--muted); }
dd { margin: 0; overflow-wrap: anywhere; }
h2 { font-size: 15px; margin: 24px 0 8px; }
"""
def page(title: str, body: str, user: str | None = None, refresh: bool = False) -> str:
logout = (
f'<span class="muted">{e(user)}</span>'
'<form method="post" action="/logout"><button type="submit">Log out</button></form>'
if user else ""
)
header = (
f'<header><h1><a href="/">kernelwatch</a></h1>{logout}</header>' if user else ""
)
meta_refresh = '<meta http-equiv="refresh" content="60">' if refresh else ""
return f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{meta_refresh}<title>{e(title)}</title>
<link rel="stylesheet" href="/static/style.css"></head>
<body>{header}{body}</body></html>"""
# --- handler ----------------------------------------------------------------
class Handler(BaseHTTPRequestHandler):
server_version = "kernelwatch/" + __version__
sys_version = ""
cfg: Config
limiter: LoginLimiter
# -- plumbing --
def log_message(self, fmt: str, *args: Any) -> None:
sys.stderr.write(f"{self.client_ip()} {fmt % args}\n")
def client_ip(self) -> str:
if self.cfg.trust_proxy_headers:
fwd = self.headers.get("X-Forwarded-For", "")
if fwd:
return fwd.split(",")[-1].strip()
return self.client_address[0]
def conn(self):
return db.connect(self.cfg.db_path)
def send(self, status: int, body: str | bytes = b"", content_type: str = "text/html; charset=utf-8",
headers: dict[str, str] | None = None) -> None:
data = body.encode() if isinstance(body, str) else body
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Referrer-Policy", "no-referrer")
self.send_header(
"Content-Security-Policy",
"default-src 'none'; style-src 'self'; form-action 'self'; frame-ancestors 'none'",
)
for k, v in (headers or {}).items():
self.send_header(k, v)
self.end_headers()
if self.command != "HEAD":
self.wfile.write(data)
def send_json(self, status: int, obj: Any) -> None:
self.send(status, json.dumps(obj), "application/json")
def redirect(self, location: str, headers: dict[str, str] | None = None) -> None:
self.send(HTTPStatus.SEE_OTHER, b"", headers={"Location": location, **(headers or {})})
def read_body(self) -> bytes | None:
length = self.headers.get("Content-Length")
if length is None or not length.isdigit():
self.send(HTTPStatus.LENGTH_REQUIRED, "Content-Length required", "text/plain")
return None
if int(length) > MAX_BODY_BYTES:
self.send(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, "body too large", "text/plain")
return None
return self.rfile.read(int(length))
def same_origin(self) -> bool:
"""Reject cross-site form posts. Browsers send Origin on POST."""
origin = self.headers.get("Origin")
if origin is None:
return True
host = self.headers.get("Host", "")
if self.cfg.trust_proxy_headers:
host = self.headers.get("X-Forwarded-Host", host)
return urlsplit(origin).netloc == host
def session_id(self) -> str | None:
raw = self.headers.get("Cookie")
if not raw:
return None
try:
morsel = SimpleCookie(raw).get(SESSION_COOKIE)
except CookieError:
return None
return morsel.value if morsel else None
def current_user(self) -> str | None:
sid = self.session_id()
if not sid:
return None
conn = self.conn()
try:
return db.session_user(conn, auth.token_hash(sid))
finally:
conn.close()
def cookie(self, value: str, max_age: int) -> str:
parts = [f"{SESSION_COOKIE}={value}", "Path=/", "HttpOnly", "SameSite=Strict",
f"Max-Age={max_age}"]
if self.cfg.secure_cookies:
parts.append("Secure")
return "; ".join(parts)
# -- routing --
def do_HEAD(self) -> None:
self.do_GET()
def do_GET(self) -> None:
path = urlsplit(self.path).path
if path == "/healthz":
return self.send(HTTPStatus.OK, "ok\n", "text/plain")
if path == "/static/style.css":
return self.send(HTTPStatus.OK, STYLE, "text/css; charset=utf-8")
if path == "/login":
return self.login_page()
user = self.current_user()
if user is None:
return self.redirect("/login")
if path == "/":
return self.dashboard(user)
if path.startswith("/host/"):
return self.host_page(user, unquote(path[len("/host/"):]))
self.send(HTTPStatus.NOT_FOUND, page("Not found", "<main><p>Not found.</p></main>", user))
def do_POST(self) -> None:
path = urlsplit(self.path).path
if path == "/api/v1/report":
return self.ingest()
if path == "/login":
return self.login()
if path == "/logout":
return self.logout()
self.send(HTTPStatus.NOT_FOUND, "not found", "text/plain")
# -- API --
def ingest(self) -> None:
header = self.headers.get("Authorization", "")
scheme, _, token = header.partition(" ")
if scheme.lower() != "bearer" or not token.strip():
return self.send_json(HTTPStatus.UNAUTHORIZED, {"error": "missing bearer token"})
body = self.read_body()
if body is None:
return
conn = self.conn()
try:
host = db.host_for_token(conn, auth.token_hash(token.strip()))
if host is None:
return self.send_json(HTTPStatus.UNAUTHORIZED, {"error": "unknown token"})
try:
report = sanitize(json.loads(body))
except (ValueError, ReportError) as exc:
return self.send_json(HTTPStatus.BAD_REQUEST, {"error": str(exc)})
wait = db.add_report(conn, host, report, self.cfg.report_retention_days,
self.cfg.report_min_interval_seconds)
finally:
conn.close()
if wait:
return self.send(HTTPStatus.TOO_MANY_REQUESTS, json.dumps({"error": "reporting too often"}),
"application/json", {"Retry-After": str(wait)})
self.send(HTTPStatus.NO_CONTENT, b"", "text/plain")
# -- auth pages --
def login_page(self, error: str = "", status: int = HTTPStatus.OK) -> None:
err = f'<p class="error">{e(error)}</p>' if error else ""
body = f"""<main><form class="login" method="post" action="/login">
<h1>kernelwatch</h1>{err}
<label>Username<input name="username" autocomplete="username" required autofocus></label>
<label>Password<input name="password" type="password" autocomplete="current-password" required></label>
<button type="submit">Log in</button></form></main>"""
self.send(status, page("Log in · kernelwatch", body))
def login(self) -> None:
if not self.same_origin():
return self.send(HTTPStatus.FORBIDDEN, "cross-origin request refused", "text/plain")
ip = self.client_ip()
if self.limiter.blocked(ip):
return self.login_page("Too many failed attempts. Try again later.",
HTTPStatus.TOO_MANY_REQUESTS)
body = self.read_body()
if body is None:
return
form = parse_qs(body.decode("utf-8", "replace"))
username = form.get("username", [""])[0]
password = form.get("password", [""])[0]
conn = self.conn()
try:
stored = db.user_pw_hash(conn, username)
ok = auth.verify_password(password, stored or auth.DUMMY_HASH) and stored is not None
if not ok:
self.limiter.failed(ip)
self.log_message("login failed for %r", username)
return self.login_page("Invalid username or password.", HTTPStatus.UNAUTHORIZED)
self.limiter.succeeded(ip)
sid = auth.new_token()
ttl = self.cfg.session_hours * 3600
db.create_session(conn, auth.token_hash(sid), username, ttl)
finally:
conn.close()
self.redirect("/", {"Set-Cookie": self.cookie(sid, ttl)})
def logout(self) -> None:
if not self.same_origin():
return self.send(HTTPStatus.FORBIDDEN, "cross-origin request refused", "text/plain")
sid = self.session_id()
if sid:
conn = self.conn()
try:
db.delete_session(conn, auth.token_hash(sid))
finally:
conn.close()
self.redirect("/login", {"Set-Cookie": self.cookie("", 0)})
# -- dashboard --
def dashboard(self, user: str) -> None:
now = time.time()
conn = self.conn()
try:
hosts = db.latest_reports(conn)
finally:
conn.close()
rows = []
for h in hosts:
h["status"] = evaluate(h["received_at"], h["report"], now, self.cfg, h["host"])
hosts.sort(key=lambda h: (h["status"].rank, h["host"]))
counts = {level: 0 for level in LEVELS}
for h in hosts:
counts[h["status"].level] += 1
rows.append(self.host_row(h, now))
summary = "".join(
f'<div><b>{counts[level]}</b>{badge(level)}</div>' for level in LEVELS
)
table = (
"<p class=muted>No hosts yet. Add one with <code>kernelwatch add-host NAME</code>.</p>"
if not hosts else
'<div class="table-wrap"><table><thead><tr>'
"<th>Status</th><th>Host</th><th>OS</th><th>Running kernel</th>"
"<th>Newest installed</th><th>Updates</th><th>Phased</th><th>Services</th><th>Uptime</th><th>Last seen</th>"
"<th>Details</th></tr></thead><tbody>" + "".join(rows) + "</tbody></table></div>"
)
body = f'<main><div class="summary">{summary}</div>{table}</main>'
self.send(HTTPStatus.OK, page("Fleet · kernelwatch", body, user, refresh=True))
@staticmethod
def host_row(h: dict[str, Any], now: float) -> str:
r = h["report"] or {}
status: Status = h["status"]
name = h["host"]
sec = r.get("security_count")
total = r.get("upgradable_count")
updates = "–" if total is None else f"{total}" + (f" ({sec} sec)" if sec else "")
phased = phased_summary(r)
services = services_summary(r)
return (
"<tr>"
f"<td>{badge(status.level)}</td>"
f'<td><a href="/host/{quote(name)}">{e(name)}</a></td>'
f"<td>{e(r.get('os_pretty_name') or '–')}</td>"
f"<td><code>{e(r.get('kernel_running') or '–')}</code></td>"
f"<td><code>{e(r.get('kernel_newest_installed') or '–')}</code></td>"
f"<td>{e(updates)}</td>"
f'<td title="{e(phased[1])}">{e(phased[0])}</td>'
f'<td title="{e(services[1])}">{e(services[0])}</td>'
f"<td>{e(duration(r.get('uptime_seconds')))}</td>"
f'<td title="{e(utc(h["received_at"]))}">{e(ago(h["received_at"], now))}</td>'
f'<td class="reasons">{"<br>".join(e(x) for x in status.reasons) or "–"}</td>'
"</tr>"
)
def host_page(self, user: str, name: str) -> None:
if not HOST_NAME_RE.match(name):
return self.send(HTTPStatus.NOT_FOUND, page("Not found", "<main><p>Not found.</p></main>", user))
now = time.time()
conn = self.conn()
try:
exists = db.host_exists(conn, name)
history = db.host_history(conn, name) if exists else []
finally:
conn.close()
if not exists:
return self.send(HTTPStatus.NOT_FOUND, page("Not found", "<main><p>Not found.</p></main>", user))
latest = history[0] if history else None
status = evaluate(latest and latest["received_at"], latest and latest["report"], now, self.cfg, name)
r = latest["report"] if latest else {}
def field(label: str, value: Any, code: bool = False) -> str:
if value is None or value == "" or value == []:
text = "–"
elif isinstance(value, list):
text = ", ".join(str(v) for v in value)
else:
text = str(value)
inner = f"<code>{e(text)}</code>" if code and text != "–" else e(text)
return f"<dt>{e(label)}</dt><dd>{inner}</dd>"
details = "".join([
f"<dt>Status</dt><dd>{badge(status.level)}</dd>",
field("Why", "; ".join(status.reasons) or None),
field("Last report", f"{ago(latest['received_at'], now)} ({utc(latest['received_at'])})"
if latest else None),
field("Reported hostname", r.get("reported_hostname")),
field("OS", r.get("os_pretty_name")),
field("OS security support", support.summary(r)),
field("Running kernel", r.get("kernel_running"), code=True),
field("Kernel build", r.get("kernel_build"), code=True),
field("Running kernel package", r.get("kernel_running_pkg_version"), code=True),
field("Installed kernels", r.get("kernels_installed"), code=True),
field("needrestart", None if r.get("needrestart_ksta") is None else
f"KSTA={r['needrestart_ksta']} expected={r.get('needrestart_kexp') or '?'}"),
field("Livepatch", None if r.get("livepatch_state") is None else
f"{r['livepatch_state']}, {r.get('livepatch_fix_count') or 0} fixes applied, "
f"{r.get('livepatch_supported') or '?'} until {r.get('livepatch_upgrade_required') or '?'}"),
field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True),
field("Updates pending", r.get("upgradable_count")),
field("Security updates", r.get("security_count")),
field("apt simulation", None if r.get("apt_simulation_ok") is None else
"ok" if r["apt_simulation_ok"] else f"failed: {r.get('apt_simulation_error') or '?'}"),
field("Deferred by phasing", r.get("phased_packages"), code=True),
field("Reboot-required packages", r.get("reboot_required_pkgs"), code=True),
field("Services needing restart", services_summary(r)[1]),
field("Sessions needing restart", r.get("sessions_need_restart")),
field("/boot free", None if r.get("boot_free_kb") is None else
f"{r['boot_free_kb'] // 1024} MB of {(r.get('boot_size_kb') or 0) // 1024} MB"),
field("Unfinished dpkg packages", r.get("dpkg_unfinished_packages"), code=True),
field("unattended-upgrades", unattended_upgrades_summary(r)),
field("Kept back by unattended-upgrades", r.get("unattended_upgrades_kept_back"), code=True),
field("Package lists age", duration(r.get("apt_lists_age_seconds"))
if r.get("apt_lists_age_seconds") is not None else None),
field("Security repository", security_repo_summary(r)),
field("Uptime", duration(r.get("uptime_seconds")) if r.get("uptime_seconds") is not None else None),
field("Agent version", r.get("agent_version")),
])
# History: status as it was at the time of each report (so never "stale").
hist_rows = "".join(
"<tr>"
f'<td title="{e(utc(h["received_at"]))}">{e(ago(h["received_at"], now))}</td>'
f"<td>{badge(evaluate(h['received_at'], h['report'], h['received_at'], self.cfg).level)}</td>"
f"<td><code>{e(h['report'].get('kernel_running') or '–')}</code></td>"
f"<td>{e('–' if (n := h['report'].get('upgradable_count')) is None else str(n))}</td>"
"</tr>"
for h in history
)
history_html = (
'<h2>Recent reports</h2><div class="table-wrap"><table><thead><tr>'
"<th>When</th><th>Status</th><th>Running kernel</th><th>Updates</th>"
f"</tr></thead><tbody>{hist_rows}</tbody></table></div>"
if history else "<p class=muted>No reports yet.</p>"
)
body = f"<main><h2>{e(name)}</h2><dl>{details}</dl>{history_html}</main>"
self.send(HTTPStatus.OK, page(f"{name} · kernelwatch", body, user, refresh=True))
def make_server(cfg: Config) -> ThreadingHTTPServer:
db.init(cfg.db_path)
handler = type("BoundHandler", (Handler,), {"cfg": cfg, "limiter": LoginLimiter()})
server = ThreadingHTTPServer((cfg.listen_host, cfg.listen_port), handler)
server.daemon_threads = True
return server
def serve(cfg: Config) -> None:
server = make_server(cfg)
host, port = server.server_address[:2]
print(f"kernelwatch {__version__} listening on http://{host}:{port}", file=sys.stderr, flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()