"""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
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 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'{e(level)} '
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'{e(user)} '
'
'
if user else ""
)
header = (
f'' if user else ""
)
meta_refresh = ' ' if refresh else ""
return f"""
{meta_refresh}{e(title)}
{header}{body}"""
# --- 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", "Not found.
", 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'{e(error)}
' if error else ""
body = f""" """
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)
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'{counts[level]} {badge(level)}
' for level in LEVELS
)
table = (
"No hosts yet. Add one with kernelwatch add-host NAME.
"
if not hosts else
''
"Status Host OS Running kernel "
"Newest installed Updates Phased Services Uptime Last seen "
"Details " + "".join(rows) + "
"
)
body = f'{summary}
{table} '
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 (
""
f"{badge(status.level)} "
f'{e(name)} '
f"{e(r.get('os_pretty_name') or '–')} "
f"{e(r.get('kernel_running') or '–')} "
f"{e(r.get('kernel_newest_installed') or '–')} "
f"{e(updates)} "
f'{e(phased[0])} '
f'{e(services[0])} '
f"{e(duration(r.get('uptime_seconds')))} "
f'{e(ago(h["received_at"], now))} '
f'{" ".join(e(x) for x in status.reasons) or "–"} '
" "
)
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", "Not found.
", 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", "Not found.
", user))
latest = history[0] if history else None
status = evaluate(latest and latest["received_at"], latest and latest["report"], now, self.cfg)
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"{e(text)}" if code and text != "–" else e(text)
return f"{e(label)} {inner} "
details = "".join([
f"Status {badge(status.level)} ",
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("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("Kernel packages upgradable", r.get("kernel_upgradable"), code=True),
field("Updates pending", r.get("upgradable_count")),
field("Security updates", r.get("security_count")),
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("Package lists age", duration(r.get("apt_lists_age_seconds"))
if r.get("apt_lists_age_seconds") is not None else None),
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(
""
f'{e(ago(h["received_at"], now))} '
f"{badge(evaluate(h['received_at'], h['report'], h['received_at'], self.cfg).level)} "
f"{e(h['report'].get('kernel_running') or '–')} "
f"{e(str(h['report'].get('upgradable_count', '–')))} "
" "
for h in history
)
history_html = (
'Recent reports '
"When Status Running kernel Updates "
f" {hist_rows}
"
if history else "No reports yet.
"
)
body = f"{e(name)} {details} {history_html} "
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()