From 47f93968e9f63002bb8a1be8c2fa4a73822e6cf5 Mon Sep 17 00:00:00 2001 From: patrick Date: Sat, 24 Oct 2026 15:15:48 -0400 Subject: [PATCH] Add ntfy alerts for stale hosts and reporting recovery --- README.md | 53 ++++- server/install.sh | 2 + server/kernelwatch-alerts.service | 38 ++++ server/kernelwatch-alerts.timer | 11 + server/kernelwatch/__init__.py | 2 +- server/kernelwatch/alerts.py | 112 ++++++++++ server/kernelwatch/cli.py | 21 +- server/kernelwatch/config.py | 26 ++- server/kernelwatch/db.py | 22 ++ server/server.toml.example | 8 + tests/test_alerts.py | 340 ++++++++++++++++++++++++++++++ 11 files changed, 631 insertions(+), 4 deletions(-) create mode 100644 server/kernelwatch-alerts.service create mode 100644 server/kernelwatch-alerts.timer create mode 100644 server/kernelwatch/alerts.py create mode 100644 tests/test_alerts.py diff --git a/README.md b/README.md index 8502d8d..7659cd3 100644 --- a/README.md +++ b/README.md @@ -369,6 +369,55 @@ Host zeus ProxyJump eurus ``` +## Stale-host and recovery alerts (ntfy) + +The server can notify an [ntfy](https://ntfy.sh/) topic when a host stops +reporting and when its reports resume. Agents report hourly with up to 15 minutes +of jitter. Alerts use the same `stale_after_hours` as the dashboard (3 hours by +default), leaving room for ordinary delays. Newly registered hosts get that same +grace period to send their first report. + +Re-run `sudo ./server/install.sh` to install the alert timer when upgrading. +The installer preserves your existing config, so add these settings to +`/etc/kernelwatch/server.toml`: + +```toml +ntfy_url = "https://ntfy.example.com/kernelwatch" +ntfy_token = "" # optional access token with publish permission for this topic +ntfy_timeout_seconds = 10.0 +``` + +Subscribe to that topic in your ntfy app, then check delivery: + +```sh +sudo kernelwatch test-alert +systemctl list-timers kernelwatch-alerts.timer +``` + +`kernelwatch-alerts.timer` runs a separate, unprivileged check every five minutes, +even when no hosts report and nobody opens the dashboard. Notifications normally +arrive within about five minutes of crossing the stale threshold or receiving a +fresh report. Run `sudo kernelwatch check-alerts` to check immediately, or inspect +`journalctl -u kernelwatch-alerts.service` for delivery failures. + +- Each host gets one stale notification and one reporting-recovery notification + per detected outage. Successful sends are saved in SQLite, so routine checks + and server restarts don't repeat them. Recovery confirms reporting has resumed; + the host may still need updates or a reboot. +- Failed sends are retried on the next check, and a failure for one host doesn't + stop checks for the others. A recovery is sent only after a stale notification + was successfully delivered. A timeout or crash after ntfy accepted a message + can cause a duplicate on retry. +- An empty `ntfy_url` disables notifications. The timer reads its configuration + on every run; changing ntfy settings needs no restart. If you change + `stale_after_hours`, restart `kernelwatch.service` too so the dashboard uses the + new threshold. + +Use the topic's direct publish URL, with token authentication if needed; it must +accept the POST without a browser login or redirect. The topic and token stay +in the server config (root-owned, readable by the `kernelwatch` service group). +Agents need no changes. + ## Server admin commands ``` @@ -379,6 +428,8 @@ sudo kernelwatch list-hosts hosts and when they last reported sudo kernelwatch set-password USER create a user / change password (logs out their sessions) sudo kernelwatch remove-user USER sudo kernelwatch list-users +sudo kernelwatch check-alerts check for stale hosts and reporting recovery now +sudo kernelwatch test-alert send a test notification to the configured ntfy topic ``` ## Security notes @@ -432,7 +483,7 @@ export KERNELWATCH_CONFIG=/tmp/kw.toml ## Ideas for later -- Alerts on status changes (email/ntfy/webhook) +- Notifications for pending updates/reboots, and additional delivery channels - Ubuntu Livepatch / Pro status, so live-patched hosts aren't flagged for reboot - A JSON endpoint for scripting - Grouping or tagging hosts (prod/staging, location) diff --git a/server/install.sh b/server/install.sh index b6fa274..638f9f8 100755 --- a/server/install.sh +++ b/server/install.sh @@ -39,9 +39,11 @@ fi install -d -m 0750 -o kernelwatch -g kernelwatch /var/lib/kernelwatch install -m 0644 "$here/kernelwatch.service" /etc/systemd/system/ +install -m 0644 "$here/kernelwatch-alerts.service" "$here/kernelwatch-alerts.timer" /etc/systemd/system/ systemctl daemon-reload systemctl enable kernelwatch.service systemctl restart kernelwatch.service +systemctl enable --now kernelwatch-alerts.timer echo echo "kernelwatch is running on $(grep -E '^listen_' /etc/kernelwatch/server.toml | tr '\n' ' ')" diff --git a/server/kernelwatch-alerts.service b/server/kernelwatch-alerts.service new file mode 100644 index 0000000..3ba8694 --- /dev/null +++ b/server/kernelwatch-alerts.service @@ -0,0 +1,38 @@ +[Unit] +Description=Check for stale kernelwatch hosts and reporting recovery +Wants=network-online.target +After=network-online.target + +[Service] +Type=oneshot +User=kernelwatch +Group=kernelwatch +Environment=KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml +ExecStart=/usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server check-alerts +TimeoutStartSec=5min +StateDirectory=kernelwatch +StateDirectoryMode=0750 + +CapabilityBoundingSet= +AmbientCapabilities= +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +ProtectProc=invisible +RestrictNamespaces=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +MemoryDenyWriteExecute=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +SystemCallArchitectures=native +SystemCallFilter=@system-service +UMask=0077 diff --git a/server/kernelwatch-alerts.timer b/server/kernelwatch-alerts.timer new file mode 100644 index 0000000..24a5cef --- /dev/null +++ b/server/kernelwatch-alerts.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Periodically check kernelwatch host reporting + +[Timer] +OnBootSec=2min +OnCalendar=*-*-* *:00/5:00 +AccuracySec=30s +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/server/kernelwatch/__init__.py b/server/kernelwatch/__init__.py index 282e81e..13fceb9 100644 --- a/server/kernelwatch/__init__.py +++ b/server/kernelwatch/__init__.py @@ -1,6 +1,6 @@ """kernelwatch: fleet kernel and reboot status dashboard.""" -__version__ = "0.3.3" +__version__ = "0.4.0" # Version of agent/kernelwatch-agent shipped alongside this server; older agents # are noted on the dashboard. tests/test_status.py checks the two stay in sync. diff --git a/server/kernelwatch/alerts.py b/server/kernelwatch/alerts.py new file mode 100644 index 0000000..453385e --- /dev/null +++ b/server/kernelwatch/alerts.py @@ -0,0 +1,112 @@ +"""Periodic stale/recovery notifications, independent of report ingestion.""" + +from __future__ import annotations + +import fcntl +import sqlite3 +import sys +import time +from http.client import HTTPException +from urllib.error import HTTPError, URLError +from urllib.request import HTTPRedirectHandler, Request, build_opener + +from . import db +from .config import Config + + +class DeliveryError(Exception): + """A safe-to-log delivery failure (never includes a URL or access token).""" + + +class _NoRedirect(HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + # A login redirect is not a successful publish. Never forward credentials. + return None + + +def publish(cfg: Config, title: str, message: str, *, stale: bool = False) -> None: + if not cfg.ntfy_url: + raise DeliveryError("ntfy_url is not configured") + headers = { + "Content-Type": "text/plain; charset=utf-8", + "Title": title, + "Tags": "warning" if stale else "white_check_mark", + "Priority": "high" if stale else "default", + } + if cfg.ntfy_token: + headers["Authorization"] = f"Bearer {cfg.ntfy_token}" + try: + request = Request(cfg.ntfy_url.rstrip("/"), data=message.encode(), headers=headers, + method="POST") + with build_opener(_NoRedirect()).open(request, timeout=cfg.ntfy_timeout_seconds) as response: + if response.status != 200: + raise DeliveryError(f"ntfy returned HTTP {response.status}; expected 200") + except HTTPError as exc: + code = exc.code + exc.close() + raise DeliveryError(f"ntfy returned HTTP {code}; expected 200") from None + except (URLError, OSError, ValueError, HTTPException) as exc: + # Exception text can contain the private topic URL. Log only its type. + raise DeliveryError(f"ntfy request failed ({type(exc).__name__})") from None + + +def _utc(timestamp: int | float) -> str: + return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(timestamp)) + + +def check(cfg: Config) -> int: + """Send transitions and return the number of failed deliveries. + + Only successful notifications change the saved state. A process lock avoids + duplicates from overlapping timer/manual runs without holding a SQLite write + transaction during network I/O, so host reports can still be ingested. + """ + if not cfg.ntfy_url: + return 0 + db.init(cfg.db_path) + with open(cfg.db_path + ".alerts.lock", "a") as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return 0 + conn = db.connect(cfg.db_path) + try: + return _check_hosts(cfg, conn) + finally: + conn.close() + + +def _check_hosts(cfg: Config, conn: sqlite3.Connection) -> int: + active = db.stale_alerts(conn) + failures = 0 + for host in db.list_hosts(conn): + name, last_seen = host["name"], host["last_seen"] + now = time.time() + baseline = host["created_at"] if last_seen is None else last_seen + stale = now - baseline > cfg.stale_after_hours * 3600 + if stale and name not in active: + detail = (f"Last report received at {_utc(last_seen)}." if last_seen is not None else + f"No reports received since registration at {_utc(baseline)}.") + title = f"kernelwatch: {name} is stale" + message = (f"{name} has stopped reporting. {detail}\n" + f"Stale threshold: {cfg.stale_after_hours:g} hours. " + "Check the host and kernelwatch-agent.timer.") + elif (not stale and name in active and last_seen is not None + and (active[name] is None or last_seen > active[name])): + title = f"kernelwatch: {name} reporting recovered" + message = (f"{name} is reporting again. Latest report received at {_utc(last_seen)}.\n" + "This confirms reporting has resumed; kernel or package updates may still be pending.") + else: + continue + try: + publish(cfg, title, message, stale=stale) + except DeliveryError as exc: + print(f"kernelwatch: notification failed for {name}: {exc}", file=sys.stderr) + failures += 1 + continue + if stale: + db.record_stale_alert(conn, name, last_seen) + else: + db.clear_stale_alert(conn, name) + print(f"kernelwatch: {'stale' if stale else 'recovery'} notification sent for {name}") + return failures diff --git a/server/kernelwatch/cli.py b/server/kernelwatch/cli.py index 1df51c5..10f1d45 100644 --- a/server/kernelwatch/cli.py +++ b/server/kernelwatch/cli.py @@ -8,7 +8,7 @@ import sqlite3 import sys import time -from . import __version__, auth, db, web +from . import __version__, alerts, auth, db, web from .config import load @@ -28,6 +28,21 @@ def cmd_serve(cfg, args) -> int: return 0 +def cmd_check_alerts(cfg, args) -> int: + return int(alerts.check(cfg) > 0) + + +def cmd_test_alert(cfg, args) -> int: + try: + alerts.publish(cfg, "kernelwatch: test notification", + "Stale-host and reporting-recovery notifications will be delivered to this topic.") + except alerts.DeliveryError as exc: + print(f"kernelwatch: {exc}", file=sys.stderr) + return 1 + print("Test notification sent.") + return 0 + + def cmd_add_host(cfg, args) -> int: token = auth.new_token() conn = _conn(cfg) @@ -134,6 +149,10 @@ def main(argv: list[str] | None = None) -> int: sub = parser.add_subparsers(dest="command", required=True) sub.add_parser("serve", help="run the HTTP server").set_defaults(func=cmd_serve) + sub.add_parser("check-alerts", help="send stale-host and recovery notifications").set_defaults( + func=cmd_check_alerts) + sub.add_parser("test-alert", help="send a test notification to the configured ntfy topic").set_defaults( + func=cmd_test_alert) for name, func, help_ in ( ("add-host", cmd_add_host, "register a host and print its token"), diff --git a/server/kernelwatch/config.py b/server/kernelwatch/config.py index c67b580..9089473 100644 --- a/server/kernelwatch/config.py +++ b/server/kernelwatch/config.py @@ -3,10 +3,12 @@ from __future__ import annotations import dataclasses +import math import os import re from dataclasses import dataclass from typing import Any +from urllib.parse import urlsplit try: import tomllib @@ -35,6 +37,11 @@ class Config: # Honour X-Forwarded-For (for login rate limiting). Enable only behind a proxy. trust_proxy_headers: bool = False + # Full ntfy topic URL; empty disables stale/recovery notifications. + ntfy_url: str = "" + ntfy_token: str = "" + ntfy_timeout_seconds: float = 10.0 + def load(path: str | None = None) -> Config: path = path or os.environ.get("KERNELWATCH_CONFIG") or DEFAULT_PATH @@ -60,7 +67,24 @@ def load(path: str | None = None) -> Config: if not isinstance(value, expected) or (expected is int and isinstance(value, bool)): raise SystemExit(f"{path}: {name} must be {expected.__name__}") values[name] = value - return Config(**values) + cfg = Config(**values) + if not math.isfinite(cfg.stale_after_hours) or cfg.stale_after_hours <= 0: + raise SystemExit(f"{path}: stale_after_hours must be positive and finite") + if not math.isfinite(cfg.ntfy_timeout_seconds) or cfg.ntfy_timeout_seconds <= 0: + raise SystemExit(f"{path}: ntfy_timeout_seconds must be positive and finite") + if any(ord(c) < 32 or ord(c) == 127 for c in cfg.ntfy_url + cfg.ntfy_token): + raise SystemExit(f"{path}: ntfy settings must not contain control characters") + if cfg.ntfy_url: + try: + url = urlsplit(cfg.ntfy_url) + valid = (url.scheme in ("http", "https") and url.hostname and url.port != 0 + and url.path.strip("/") and not url.username and not url.password + and not url.query and not url.fragment and not any(c.isspace() for c in cfg.ntfy_url)) + except ValueError: + valid = False + if not valid: + raise SystemExit(f"{path}: ntfy_url must be an HTTP(S) topic URL without credentials, query or fragment") + return cfg _KEY_VALUE = re.compile(r"^([A-Za-z0-9_-]+)\s*=\s*(.*)$") diff --git a/server/kernelwatch/db.py b/server/kernelwatch/db.py index 2fc5792..cad7915 100644 --- a/server/kernelwatch/db.py +++ b/server/kernelwatch/db.py @@ -30,6 +30,10 @@ CREATE TABLE IF NOT EXISTS sessions ( user TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE, expires_at INTEGER NOT NULL ); +CREATE TABLE IF NOT EXISTS stale_alerts ( + host TEXT PRIMARY KEY REFERENCES hosts(name) ON DELETE CASCADE, + last_seen INTEGER +); """ @@ -142,6 +146,24 @@ def host_exists(conn: sqlite3.Connection, host: str) -> bool: return conn.execute("SELECT 1 FROM hosts WHERE name = ?", (host,)).fetchone() is not None +# --- delivered stale notifications ------------------------------------------ + +def stale_alerts(conn: sqlite3.Connection) -> dict[str, int | None]: + return {r["host"]: r["last_seen"] for r in conn.execute("SELECT * FROM stale_alerts")} + + +def record_stale_alert(conn: sqlite3.Connection, host: str, last_seen: int | None) -> None: + # The host may have been removed while the notification was in flight. + conn.execute( + "INSERT INTO stale_alerts (host, last_seen) SELECT name, ? FROM hosts WHERE name = ?", + (last_seen, host), + ) + + +def clear_stale_alert(conn: sqlite3.Connection, host: str) -> None: + conn.execute("DELETE FROM stale_alerts WHERE host = ?", (host,)) + + # --- users & sessions ------------------------------------------------------- def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None: diff --git a/server/server.toml.example b/server/server.toml.example index 2bb16cf..c10f052 100644 --- a/server/server.toml.example +++ b/server/server.toml.example @@ -23,3 +23,11 @@ secure_cookies = true # rate limiting and origin checks. Only enable if the port isn't reachable # directly, or clients can spoof their IP. trust_proxy_headers = false + +# Stale-host and reporting-recovery notifications. Empty URL disables alerts. +# The server installer enables a timer that checks every five minutes. +# This uses stale_after_hours above (3h allows for hourly reports + 15m jitter). +# Include the topic in the URL; use a topic you subscribe to in your ntfy app. +ntfy_url = "" # e.g. "https://ntfy.example.com/kernelwatch" +ntfy_token = "" # optional ntfy access token (Bearer auth) +ntfy_timeout_seconds = 10.0 diff --git a/tests/test_alerts.py b/tests/test_alerts.py new file mode 100644 index 0000000..b1da876 --- /dev/null +++ b/tests/test_alerts.py @@ -0,0 +1,340 @@ +"""Stale/recovery transitions, durable deduplication, and real ntfy HTTP requests.""" + +import contextlib +import dataclasses +import io +import json +import os +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest import mock +from urllib.error import URLError + +from helpers import temp_config, tempdir +from kernelwatch import alerts, auth, cli, config, db + +NOW = 1_800_000_000 + + +class AlertTransitionsTest(unittest.TestCase): + def setUp(self): + self.tmp = tempdir() + self.addCleanup(self.tmp.cleanup) + self.cfg = temp_config(self.tmp.name, ntfy_url="https://ntfy.example.test/fleet") + db.init(self.cfg.db_path) + self.conn = db.connect(self.cfg.db_path) + self.addCleanup(self.conn.close) + clock = mock.patch("kernelwatch.alerts.time.time", return_value=NOW) + self.clock = clock.start() + self.addCleanup(clock.stop) + publisher = mock.patch("kernelwatch.alerts.publish") + self.publish = publisher.start() + self.addCleanup(publisher.stop) + stack = contextlib.ExitStack() + self.addCleanup(stack.close) + self.output = stack.enter_context(contextlib.redirect_stdout(io.StringIO())) + self.errors = stack.enter_context(contextlib.redirect_stderr(io.StringIO())) + + def host(self, name="web01", *, registered_age=86400, report_age=None): + db.add_host(self.conn, name, auth.token_hash(auth.new_token())) + self.conn.execute("UPDATE hosts SET created_at = ? WHERE name = ?", + (NOW - registered_age, name)) + if report_age is not None: + self.report(name, report_age) + + def report(self, name="web01", age=0): + # A host needing a reboot still counts as recovered when it reports again. + self.conn.execute("INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)", + (name, NOW - age, json.dumps({"kernel_running": "x", "reboot_required": True}))) + + def test_hourly_reports_and_jitter_do_not_alert(self): + self.host(report_age=75 * 60) + self.assertEqual(alerts.check(self.cfg), 0) + self.publish.assert_not_called() + self.assertEqual(db.stale_alerts(self.conn), {}) + + def test_stale_boundary_matches_dashboard_and_survives_restart(self): + self.host(report_age=3 * 3600) + self.assertEqual(alerts.check(self.cfg), 0) + self.publish.assert_not_called() + self.clock.return_value = NOW + 1 + self.assertEqual(alerts.check(self.cfg), 0) + self.assertIn("web01 is stale", self.publish.call_args.args[1]) + self.assertIn("Last report received", self.publish.call_args.args[2]) + self.assertTrue(self.publish.call_args.kwargs["stale"]) + self.assertEqual(db.stale_alerts(self.conn), {"web01": NOW - 3 * 3600}) + # Each run opens new connections, as a fresh timer process would. + self.clock.return_value = NOW + 86400 + self.assertEqual(alerts.check(self.cfg), 0) + self.assertEqual(self.publish.call_count, 1) + + def test_registration_grace_and_first_report_recovery(self): + self.host(registered_age=3600) + self.assertEqual(alerts.check(self.cfg), 0) + self.publish.assert_not_called() + self.clock.return_value = NOW + 7201 + self.assertEqual(alerts.check(self.cfg), 0) + self.assertIn("No reports received since registration", self.publish.call_args.args[2]) + self.report(age=-7201) + self.assertEqual(alerts.check(self.cfg), 0) + self.assertIn("reporting recovered", self.publish.call_args.args[1]) + + def test_one_recovery_and_rearms_for_next_outage(self): + self.host(report_age=10801) + alerts.check(self.cfg) + self.report() + alerts.check(self.cfg) + self.assertIn("web01 reporting recovered", self.publish.call_args.args[1]) + self.assertIn("updates may still be pending", self.publish.call_args.args[2]) + self.assertFalse(self.publish.call_args.kwargs["stale"]) + self.assertEqual(db.stale_alerts(self.conn), {}) + alerts.check(self.cfg) + self.assertEqual(self.publish.call_count, 2) + self.clock.return_value = NOW + 10801 + alerts.check(self.cfg) + self.assertEqual(self.publish.call_count, 3) + self.assertTrue(self.publish.call_args.kwargs["stale"]) + + def test_healthy_host_has_no_initial_recovery(self): + self.host(report_age=1) + alerts.check(self.cfg) + self.publish.assert_not_called() + + def test_recovery_in_same_second_as_stale_threshold(self): + self.clock.return_value = NOW + 0.5 + for last_report in (None, 10800): + with self.subTest(last_report=last_report): + db.remove_host(self.conn, "web01") + self.host(registered_age=10800, report_age=last_report) + alerts.check(self.cfg) + self.publish.reset_mock() + self.report() + alerts.check(self.cfg) + self.assertEqual(self.publish.call_count, 1) + self.assertIn("reporting recovered", self.publish.call_args.args[1]) + self.assertEqual(db.stale_alerts(self.conn), {}) + + def test_stale_failure_retried_and_other_hosts_checked(self): + self.host("a", report_age=10801) + self.host("b", report_age=10801) + self.publish.side_effect = [alerts.DeliveryError("ntfy returned HTTP 503"), None] + self.assertEqual(alerts.check(self.cfg), 1) + self.assertEqual(set(db.stale_alerts(self.conn)), {"b"}) + self.assertIn("notification failed for a", self.errors.getvalue()) + self.publish.side_effect = None + self.assertEqual(alerts.check(self.cfg), 0) + self.assertEqual(set(db.stale_alerts(self.conn)), {"a", "b"}) + self.assertEqual(self.publish.call_count, 3) + + def test_no_recovery_when_stale_was_not_delivered(self): + self.host(report_age=10801) + self.publish.side_effect = alerts.DeliveryError("offline") + self.assertEqual(alerts.check(self.cfg), 1) + self.report() + self.publish.side_effect = None + alerts.check(self.cfg) + self.assertEqual(self.publish.call_count, 1) + + def test_recovery_failure_retried_without_repeating_stale(self): + self.host(report_age=10801) + alerts.check(self.cfg) + self.report() + self.publish.side_effect = alerts.DeliveryError("offline") + self.assertEqual(alerts.check(self.cfg), 1) + self.assertIn("web01", db.stale_alerts(self.conn)) + self.publish.side_effect = None + self.assertEqual(alerts.check(self.cfg), 0) + self.assertEqual(db.stale_alerts(self.conn), {}) + self.assertIn("reporting recovered", self.publish.call_args.args[1]) + + def test_changing_threshold_does_not_invent_recovery(self): + for last_report in (None, 10801): + with self.subTest(last_report=last_report): + db.remove_host(self.conn, "web01") + self.host(registered_age=10801, report_age=last_report) + alerts.check(self.cfg) + self.publish.reset_mock() + alerts.check(dataclasses.replace(self.cfg, stale_after_hours=6.0)) + self.publish.assert_not_called() + self.assertIn("web01", db.stale_alerts(self.conn)) + + def test_removed_host_clears_state(self): + self.host(report_age=10801) + alerts.check(self.cfg) + db.remove_host(self.conn, "web01") + self.assertEqual(db.stale_alerts(self.conn), {}) + self.host(report_age=1) + alerts.check(self.cfg) + self.assertEqual(self.publish.call_count, 1) + + def test_upgrade_adds_alert_state_without_changing_existing_data(self): + self.host(report_age=3600) + self.conn.execute("DROP TABLE stale_alerts") + db.init(self.cfg.db_path) + self.assertEqual(db.stale_alerts(self.conn), {}) + host = db.list_hosts(self.conn)[0] + self.assertEqual(host["name"], "web01") + self.assertEqual(host["last_seen"], NOW - 3600) + + def test_report_ingestion_continues_during_delivery_and_runs_do_not_overlap(self): + self.host(report_age=10801) + + def during_delivery(*args, **kwargs): + conn = db.connect(self.cfg.db_path) + try: + db.add_report(conn, "web01", {"kernel_running": "x"}, 30) + finally: + conn.close() + self.assertEqual(alerts.check(self.cfg), 0) + + self.publish.side_effect = during_delivery + self.assertEqual(alerts.check(self.cfg), 0) + self.assertEqual(self.publish.call_count, 1) + + def test_removal_during_delivery_does_not_restore_host(self): + self.host(report_age=10801) + self.publish.side_effect = lambda *a, **kw: db.remove_host(self.conn, "web01") + self.assertEqual(alerts.check(self.cfg), 0) + self.assertEqual(db.stale_alerts(self.conn), {}) + + def test_disabled_does_not_create_database_or_send(self): + cfg = dataclasses.replace(self.cfg, ntfy_url="", db_path=os.path.join(self.tmp.name, "unused.db")) + self.assertEqual(alerts.check(cfg), 0) + self.assertFalse(os.path.exists(cfg.db_path)) + self.publish.assert_not_called() + + +class NtfyHTTPTest(unittest.TestCase): + def setUp(self): + class Sink(BaseHTTPRequestHandler): + def do_POST(self): + self.server.messages.append((self.path, dict(self.headers), + self.rfile.read(int(self.headers["Content-Length"])))) + self.send_response(self.server.response_code) + if self.server.response_code == 302: + self.send_header("Location", "/redirected") + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Sink) + self.server.messages = [] + self.server.response_code = 200 + thread = threading.Thread(target=self.server.serve_forever, daemon=True) + thread.start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + self.cfg = config.Config(ntfy_url=f"http://127.0.0.1:{self.server.server_port}/fleet", + ntfy_token="tk_secret") + + def test_authenticated_publish(self): + alerts.publish(self.cfg, "kernelwatch: web01 is stale", "Host missed reports.", stale=True) + path, headers, data = self.server.messages[0] + self.assertEqual(path, "/fleet") + self.assertEqual(headers["Authorization"], "Bearer tk_secret") + self.assertEqual(headers["Title"], "kernelwatch: web01 is stale") + self.assertEqual(headers["Priority"], "high") + self.assertEqual(headers["Tags"], "warning") + self.assertEqual(data, b"Host missed reports.") + + def test_recovery_without_auth(self): + alerts.publish(dataclasses.replace(self.cfg, ntfy_token=""), "Recovered", "Reporting again.") + _, headers, _ = self.server.messages[0] + self.assertNotIn("Authorization", headers) + self.assertEqual(headers["Priority"], "default") + self.assertEqual(headers["Tags"], "white_check_mark") + + def test_redirect_rejected_without_following(self): + self.server.response_code = 302 + with self.assertRaisesRegex(alerts.DeliveryError, "HTTP 302"): + alerts.publish(self.cfg, "Test", "Body") + self.assertEqual(len(self.server.messages), 1) + + def test_http_failures_and_unexpected_success_codes(self): + for code in (204, 401, 429, 503): + with self.subTest(code=code): + self.server.response_code = code + with self.assertRaisesRegex(alerts.DeliveryError, f"HTTP {code}") as error: + alerts.publish(self.cfg, "Test", "Body") + self.assertNotIn("tk_secret", str(error.exception)) + self.assertNotIn(self.cfg.ntfy_url, str(error.exception)) + + def test_stale_and_recovery_through_real_http(self): + with tempdir() as tmp, mock.patch("kernelwatch.alerts.time.time", return_value=NOW), \ + contextlib.redirect_stdout(io.StringIO()): + cfg = dataclasses.replace(self.cfg, db_path=os.path.join(tmp, "kw.db")) + db.init(cfg.db_path) + conn = db.connect(cfg.db_path) + try: + db.add_host(conn, "web01", auth.token_hash(auth.new_token())) + conn.execute("UPDATE hosts SET created_at = ?", (NOW - 10801,)) + self.assertEqual(alerts.check(cfg), 0) + self.assertEqual(len(self.server.messages), 1) + self.assertIn("is stale", self.server.messages[-1][1]["Title"]) + alerts.check(cfg) + self.assertEqual(len(self.server.messages), 1) + db.add_report(conn, "web01", {"kernel_running": "x"}, 30) + self.assertEqual(alerts.check(cfg), 0) + self.assertEqual(len(self.server.messages), 2) + self.assertIn("reporting recovered", self.server.messages[-1][1]["Title"]) + self.assertEqual(db.stale_alerts(conn), {}) + finally: + conn.close() + + +class AlertCommandsAndConfigTest(unittest.TestCase): + def test_network_errors_are_redacted_and_timeout_is_passed(self): + cfg = config.Config(ntfy_url="https://ntfy.example/secret-topic", ntfy_token="tk_secret", + ntfy_timeout_seconds=2.5) + with mock.patch("kernelwatch.alerts.build_opener") as opener: + opener.return_value.open.side_effect = URLError(cfg.ntfy_url + cfg.ntfy_token) + with self.assertRaises(alerts.DeliveryError) as error: + alerts.publish(cfg, "Test", "Body") + self.assertNotIn("secret", str(error.exception)) + self.assertEqual(opener.return_value.open.call_args.kwargs["timeout"], 2.5) + + def test_check_alerts_exit_status_and_test_notification(self): + with tempdir() as tmp: + path = os.path.join(tmp, "server.toml") + with open(path, "w") as f: + f.write('ntfy_url = "https://ntfy.example/fleet"\n') + with mock.patch("kernelwatch.cli.alerts.check", return_value=1) as check: + self.assertEqual(cli.main(["-c", path, "check-alerts"]), 1) + self.assertEqual(check.call_args.args[0].ntfy_url, "https://ntfy.example/fleet") + check.return_value = 0 + self.assertEqual(cli.main(["-c", path, "check-alerts"]), 0) + with mock.patch("kernelwatch.cli.alerts.publish") as publish, contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(cli.main(["-c", path, "test-alert"]), 0) + self.assertEqual(publish.call_count, 1) + publish.side_effect = alerts.DeliveryError("offline") + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(cli.main(["-c", path, "test-alert"]), 1) + + def test_disabled_test_alert_is_an_actionable_error(self): + with self.assertRaisesRegex(alerts.DeliveryError, "ntfy_url is not configured"): + alerts.publish(config.Config(), "Test", "Body") + + def test_invalid_alert_config(self): + bad = ('stale_after_hours = 0', 'stale_after_hours = inf', + 'ntfy_timeout_seconds = -1', 'ntfy_timeout_seconds = nan', + 'ntfy_url = "https://ntfy.example"', 'ntfy_url = "file:///topic"', + 'ntfy_url = "https://user:password@ntfy.example/topic"', + 'ntfy_url = "https://ntfy.example/topic?auth=secret"', + 'ntfy_url = "https://ntfy.example/topic#fragment"', + 'ntfy_url = "https://ntfy.example:bad/topic"', + 'ntfy_token = "bad\\nheader"') + with tempdir() as tmp: + path = os.path.join(tmp, "server.toml") + for text in bad: + with self.subTest(text=text): + with open(path, "w") as f: + f.write(text + "\n") + with self.assertRaises(SystemExit): + config.load(path) + + +if __name__ == "__main__": + unittest.main() -- 2.54.1