Rate-limit report ingestion per host #12

Merged
patrick merged 2 commits from feat/ingest-rate-limit into main 2026-10-30 01:16:32 +00:00
7 changed files with 77 additions and 3 deletions

No files matched your search

+6
View File
@@ -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 - **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 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 - **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 capability set of just `CAP_SYS_PTRACE` + `CAP_DAC_READ_SEARCH` (to read other
processes' memory maps), a read-only filesystem except `/run/kernelwatch`, processes' memory maps), a read-only filesystem except `/run/kernelwatch`,
+4
View File
@@ -30,6 +30,8 @@ class Config:
# Package lists older than this make "no updates" untrustworthy. # Package lists older than this make "no updates" untrustworthy.
apt_stale_after_hours: float = 48.0 apt_stale_after_hours: float = 48.0
report_retention_days: int = 30 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 session_hours: int = 12
# Leave on unless you serve the dashboard over plain HTTP on a non-localhost name. # 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") 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: 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") 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: 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") 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): if any(ord(c) < 32 or ord(c) == 127 for c in cfg.ntfy_url + cfg.ntfy_token):
+12 -2
View File
@@ -127,10 +127,18 @@ def list_hosts(conn: sqlite3.Connection) -> list[sqlite3.Row]:
# --- reports ---------------------------------------------------------------- # --- reports ----------------------------------------------------------------
def add_report(conn: sqlite3.Connection, host: str, payload: dict[str, Any], 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()) now = int(time.time())
conn.execute("BEGIN IMMEDIATE") conn.execute("BEGIN IMMEDIATE")
try: 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( conn.execute(
"INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)", "INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)",
(host, now, json.dumps(payload, separators=(",", ":"))), (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), (host, now - retention_days * 86400),
) )
conn.execute("COMMIT") conn.execute("COMMIT")
return 0
except BaseException: except BaseException:
conn.execute("ROLLBACK") if conn.in_transaction:
conn.execute("ROLLBACK")
raise raise
+5 -1
View File
@@ -334,9 +334,13 @@ class Handler(BaseHTTPRequestHandler):
report = sanitize(json.loads(body)) report = sanitize(json.loads(body))
except (ValueError, ReportError) as exc: except (ValueError, ReportError) as exc:
return self.send_json(HTTPStatus.BAD_REQUEST, {"error": str(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: finally:
conn.close() 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") self.send(HTTPStatus.NO_CONTENT, b"", "text/plain")
# -- auth pages -- # -- auth pages --
+5
View File
@@ -13,6 +13,11 @@ stale_after_hours = 3.0
apt_stale_after_hours = 48.0 apt_stale_after_hours = 48.0
report_retention_days = 30 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_hours = 12
# Session cookie gets the Secure flag. Leave on unless you're testing over # Session cookie gets the Secure flag. Leave on unless you're testing over
+8
View File
@@ -67,6 +67,14 @@ class ConfigTest(unittest.TestCase):
with self.assertRaises(SystemExit): with self.assertRaises(SystemExit):
config.load(self.write(tmp, "secure_cookies = 1\n")) 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): def test_status_alert_hours_validated(self):
with tempdir() as tmp: with tempdir() as tmp:
self.assertEqual(config.load(self.write(tmp, "status_alert_after_hours = 0\n")) self.assertEqual(config.load(self.write(tmp, "status_alert_after_hours = 0\n"))
+37
View File
@@ -4,6 +4,7 @@ import unittest
import urllib.error import urllib.error
import urllib.parse import urllib.parse
import urllib.request import urllib.request
from unittest import mock
from helpers import temp_config, tempdir from helpers import temp_config, tempdir
from kernelwatch import auth, db, web from kernelwatch import auth, db, web
@@ -90,6 +91,42 @@ class IngestTest(ServerCase):
{"Authorization": f"Bearer {token}"}) {"Authorization": f"Bearer {token}"})
self.assertEqual(status, 413) 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): class PhasedSummaryTest(unittest.TestCase):
def test_cells(self): def test_cells(self):