From a6a43b142fc804d0e345bec8fe3549e07c10237e Mon Sep 17 00:00:00 2001 From: patrickbeane Date: Thu, 29 Oct 2026 20:46:09 -0400 Subject: [PATCH 1/2] Rate-limit report ingestion per host Reports arriving sooner than report_min_interval_seconds (default 30) after the host's previous one are refused with 429 and a Retry-After header. The check shares the insert's transaction so concurrent requests can't bypass it. Co-Authored-By: Claude Sonnet 5.5 --- server/kernelwatch/config.py | 4 ++++ server/kernelwatch/db.py | 14 ++++++++++-- server/kernelwatch/web.py | 6 +++++- server/server.toml.example | 5 +++++ tests/test_report_auth_config.py | 8 +++++++ tests/test_web.py | 37 ++++++++++++++++++++++++++++++++ 6 files changed, 71 insertions(+), 3 deletions(-) diff --git a/server/kernelwatch/config.py b/server/kernelwatch/config.py index 840faab..0e9c806 100644 --- a/server/kernelwatch/config.py +++ b/server/kernelwatch/config.py @@ -30,6 +30,8 @@ class Config: # Package lists older than this make "no updates" untrustworthy. apt_stale_after_hours: float = 48.0 report_retention_days: int = 30 + # A host's reports closer together than this are refused with 429; 0 disables. + report_min_interval_seconds: int = 30 session_hours: int = 12 # Leave on unless you serve the dashboard over plain HTTP on a non-localhost name. @@ -74,6 +76,8 @@ def load(path: str | None = None) -> Config: 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 cfg.report_min_interval_seconds < 0: + raise SystemExit(f"{path}: report_min_interval_seconds must be zero or positive") if not math.isfinite(cfg.status_alert_after_hours) or cfg.status_alert_after_hours < 0: raise SystemExit(f"{path}: status_alert_after_hours must be zero or positive and finite") if any(ord(c) < 32 or ord(c) == 127 for c in cfg.ntfy_url + cfg.ntfy_token): diff --git a/server/kernelwatch/db.py b/server/kernelwatch/db.py index a1bd688..4fe01a1 100644 --- a/server/kernelwatch/db.py +++ b/server/kernelwatch/db.py @@ -127,10 +127,18 @@ def list_hosts(conn: sqlite3.Connection) -> list[sqlite3.Row]: # --- reports ---------------------------------------------------------------- def add_report(conn: sqlite3.Connection, host: str, payload: dict[str, Any], - retention_days: int) -> None: + retention_days: int, min_interval: int = 0) -> int: + """Store a report. Returns 0, or the seconds to wait if the host's previous report + is newer than min_interval (nothing is stored then). The check and the insert share + one transaction, so concurrent requests can't both slip past it.""" now = int(time.time()) conn.execute("BEGIN IMMEDIATE") try: + last = conn.execute("SELECT MAX(received_at) FROM reports WHERE host = ?", + (host,)).fetchone()[0] + if last is not None and 0 <= now - last < min_interval: + conn.execute("ROLLBACK") + return min_interval - (now - last) conn.execute( "INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)", (host, now, json.dumps(payload, separators=(",", ":"))), @@ -140,8 +148,10 @@ def add_report(conn: sqlite3.Connection, host: str, payload: dict[str, Any], (host, now - retention_days * 86400), ) conn.execute("COMMIT") + return 0 except BaseException: - conn.execute("ROLLBACK") + if conn.in_transaction: + conn.execute("ROLLBACK") raise diff --git a/server/kernelwatch/web.py b/server/kernelwatch/web.py index 89c238d..9a48b52 100644 --- a/server/kernelwatch/web.py +++ b/server/kernelwatch/web.py @@ -334,9 +334,13 @@ class Handler(BaseHTTPRequestHandler): report = sanitize(json.loads(body)) except (ValueError, ReportError) as exc: return self.send_json(HTTPStatus.BAD_REQUEST, {"error": str(exc)}) - db.add_report(conn, host, report, self.cfg.report_retention_days) + 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 -- diff --git a/server/server.toml.example b/server/server.toml.example index b7e1fbb..9593ab5 100644 --- a/server/server.toml.example +++ b/server/server.toml.example @@ -13,6 +13,11 @@ stale_after_hours = 3.0 apt_stale_after_hours = 48.0 report_retention_days = 30 + +# Refuse (HTTP 429) a report that arrives sooner than this after the host's +# previous one. Agents report hourly; this only stops a stuck or abusive client +# from flooding the history. 0 disables. +report_min_interval_seconds = 30 session_hours = 12 # Session cookie gets the Secure flag. Leave on unless you're testing over diff --git a/tests/test_report_auth_config.py b/tests/test_report_auth_config.py index 69407a3..090ff2b 100644 --- a/tests/test_report_auth_config.py +++ b/tests/test_report_auth_config.py @@ -67,6 +67,14 @@ class ConfigTest(unittest.TestCase): with self.assertRaises(SystemExit): config.load(self.write(tmp, "secure_cookies = 1\n")) + def test_report_min_interval_validated(self): + with tempdir() as tmp: + self.assertEqual(config.load(self.write(tmp, "report_min_interval_seconds = 0\n")) + .report_min_interval_seconds, 0) + for bad in ("-1", "1.5", '"30"'): + with self.subTest(bad=bad), self.assertRaises(SystemExit): + config.load(self.write(tmp, f"report_min_interval_seconds = {bad}\n")) + def test_status_alert_hours_validated(self): with tempdir() as tmp: self.assertEqual(config.load(self.write(tmp, "status_alert_after_hours = 0\n")) diff --git a/tests/test_web.py b/tests/test_web.py index b716b00..6bba422 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -4,6 +4,7 @@ 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 @@ -90,6 +91,42 @@ class IngestTest(ServerCase): {"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): From 51732066d07a0e93127119187d7294ce64230ed7 Mon Sep 17 00:00:00 2001 From: patrickbeane Date: Thu, 29 Oct 2026 20:46:09 -0400 Subject: [PATCH 2/2] Document report rate limit Co-Authored-By: Claude Sonnet 5.5 --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 0035ea2..8e30bce 100644 --- a/README.md +++ b/README.md @@ -468,6 +468,12 @@ To restore, stop the service, put the file at `db_path` owned by `kernelwatch` - **Host identity comes from the token, not the payload.** A host can only report as itself. Tokens are 256-bit random values; only their SHA-256 is stored. +- **Report rate limit.** A report arriving less than `report_min_interval_seconds` + (default 30) after the host's previous one gets HTTP 429 with a `Retry-After` + header, and isn't stored. So a stuck agent or a leaked token can't flood the + database or push real history off the host page. The agent's curl waits out the + `Retry-After` and retries, so running `systemctl start kernelwatch-agent` twice + in a row just pauses briefly. Set it to `0` to disable. - **needrestart** runs in a separate root unit with `PrivateNetwork=yes`, a capability set of just `CAP_SYS_PTRACE` + `CAP_DAC_READ_SEARCH` (to read other processes' memory maps), a read-only filesystem except `/run/kernelwatch`,