CI / tests (Python 3.10) (pull_request) Successful in 19s
CI / tests (Python 3.11) (pull_request) Successful in 17s
CI / tests (Python 3.12) (pull_request) Successful in 17s
CI / tests (Python 3.13) (pull_request) Successful in 18s
CI / lint (pull_request) Successful in 3s
211 lines
6.9 KiB
Python
211 lines
6.9 KiB
Python
"""SQLite storage. One connection per thread/request; WAL keeps readers and the writer apart."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import time
|
|
from typing import Any
|
|
|
|
SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS hosts (
|
|
name TEXT PRIMARY KEY,
|
|
token_hash TEXT NOT NULL UNIQUE,
|
|
created_at INTEGER NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS reports (
|
|
id INTEGER PRIMARY KEY,
|
|
host TEXT NOT NULL REFERENCES hosts(name) ON DELETE CASCADE,
|
|
received_at INTEGER NOT NULL,
|
|
payload TEXT NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS reports_host_time ON reports(host, received_at);
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
name TEXT PRIMARY KEY,
|
|
pw_hash TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
id_hash TEXT PRIMARY KEY,
|
|
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
|
|
);
|
|
"""
|
|
|
|
|
|
def connect(path: str) -> sqlite3.Connection:
|
|
conn = sqlite3.connect(path, timeout=10, isolation_level=None)
|
|
conn.row_factory = sqlite3.Row
|
|
conn.execute("PRAGMA foreign_keys = ON")
|
|
conn.execute("PRAGMA journal_mode = WAL")
|
|
conn.execute("PRAGMA busy_timeout = 10000")
|
|
return conn
|
|
|
|
|
|
def init(path: str) -> None:
|
|
directory = os.path.dirname(os.path.abspath(path))
|
|
os.makedirs(directory, exist_ok=True)
|
|
conn = connect(path)
|
|
try:
|
|
conn.executescript(SCHEMA)
|
|
finally:
|
|
conn.close()
|
|
os.chmod(path, 0o600)
|
|
|
|
|
|
# --- hosts ------------------------------------------------------------------
|
|
|
|
def add_host(conn: sqlite3.Connection, name: str, token_hash: str) -> None:
|
|
conn.execute(
|
|
"INSERT INTO hosts (name, token_hash, created_at) VALUES (?, ?, ?)",
|
|
(name, token_hash, int(time.time())),
|
|
)
|
|
|
|
|
|
def set_host_token(conn: sqlite3.Connection, name: str, token_hash: str) -> bool:
|
|
cur = conn.execute("UPDATE hosts SET token_hash = ? WHERE name = ?", (token_hash, name))
|
|
return cur.rowcount == 1
|
|
|
|
|
|
def remove_host(conn: sqlite3.Connection, name: str) -> bool:
|
|
return conn.execute("DELETE FROM hosts WHERE name = ?", (name,)).rowcount == 1
|
|
|
|
|
|
def host_for_token(conn: sqlite3.Connection, token_hash: str) -> str | None:
|
|
row = conn.execute("SELECT name FROM hosts WHERE token_hash = ?", (token_hash,)).fetchone()
|
|
return row["name"] if row else None
|
|
|
|
|
|
def list_hosts(conn: sqlite3.Connection) -> list[sqlite3.Row]:
|
|
return conn.execute(
|
|
"""
|
|
SELECT h.name, h.created_at, MAX(r.received_at) AS last_seen
|
|
FROM hosts h LEFT JOIN reports r ON r.host = h.name
|
|
GROUP BY h.name ORDER BY h.name
|
|
"""
|
|
).fetchall()
|
|
|
|
|
|
# --- reports ----------------------------------------------------------------
|
|
|
|
def add_report(conn: sqlite3.Connection, host: str, payload: dict[str, Any],
|
|
retention_days: int) -> None:
|
|
now = int(time.time())
|
|
conn.execute("BEGIN IMMEDIATE")
|
|
try:
|
|
conn.execute(
|
|
"INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)",
|
|
(host, now, json.dumps(payload, separators=(",", ":"))),
|
|
)
|
|
conn.execute(
|
|
"DELETE FROM reports WHERE host = ? AND received_at < ?",
|
|
(host, now - retention_days * 86400),
|
|
)
|
|
conn.execute("COMMIT")
|
|
except BaseException:
|
|
conn.execute("ROLLBACK")
|
|
raise
|
|
|
|
|
|
def latest_reports(conn: sqlite3.Connection) -> list[dict[str, Any]]:
|
|
"""Every host with its most recent report (or None)."""
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT h.name, r.received_at, r.payload
|
|
FROM hosts h
|
|
LEFT JOIN reports r ON r.id = (
|
|
SELECT id FROM reports WHERE host = h.name ORDER BY received_at DESC, id DESC LIMIT 1
|
|
)
|
|
ORDER BY h.name
|
|
"""
|
|
).fetchall()
|
|
return [
|
|
{
|
|
"host": row["name"],
|
|
"received_at": row["received_at"],
|
|
"report": json.loads(row["payload"]) if row["payload"] else None,
|
|
}
|
|
for row in rows
|
|
]
|
|
|
|
|
|
def host_history(conn: sqlite3.Connection, host: str, limit: int = 50) -> list[dict[str, Any]]:
|
|
rows = conn.execute(
|
|
"SELECT received_at, payload FROM reports WHERE host = ? "
|
|
"ORDER BY received_at DESC, id DESC LIMIT ?",
|
|
(host, limit),
|
|
).fetchall()
|
|
return [{"received_at": r["received_at"], "report": json.loads(r["payload"])} for r in rows]
|
|
|
|
|
|
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:
|
|
conn.execute(
|
|
"INSERT INTO users (name, pw_hash) VALUES (?, ?) "
|
|
"ON CONFLICT(name) DO UPDATE SET pw_hash = excluded.pw_hash",
|
|
(name, pw_hash),
|
|
)
|
|
# A password change logs out existing sessions.
|
|
conn.execute("DELETE FROM sessions WHERE user = ?", (name,))
|
|
|
|
|
|
def remove_user(conn: sqlite3.Connection, name: str) -> bool:
|
|
return conn.execute("DELETE FROM users WHERE name = ?", (name,)).rowcount == 1
|
|
|
|
|
|
def user_pw_hash(conn: sqlite3.Connection, name: str) -> str | None:
|
|
row = conn.execute("SELECT pw_hash FROM users WHERE name = ?", (name,)).fetchone()
|
|
return row["pw_hash"] if row else None
|
|
|
|
|
|
def list_users(conn: sqlite3.Connection) -> list[str]:
|
|
return [r["name"] for r in conn.execute("SELECT name FROM users ORDER BY name")]
|
|
|
|
|
|
def create_session(conn: sqlite3.Connection, id_hash: str, user: str, ttl_seconds: int) -> None:
|
|
now = int(time.time())
|
|
conn.execute("DELETE FROM sessions WHERE expires_at < ?", (now,))
|
|
conn.execute(
|
|
"INSERT INTO sessions (id_hash, user, expires_at) VALUES (?, ?, ?)",
|
|
(id_hash, user, now + ttl_seconds),
|
|
)
|
|
|
|
|
|
def session_user(conn: sqlite3.Connection, id_hash: str) -> str | None:
|
|
row = conn.execute(
|
|
"SELECT user FROM sessions WHERE id_hash = ? AND expires_at >= ?",
|
|
(id_hash, int(time.time())),
|
|
).fetchone()
|
|
return row["user"] if row else None
|
|
|
|
|
|
def delete_session(conn: sqlite3.Connection, id_hash: str) -> None:
|
|
conn.execute("DELETE FROM sessions WHERE id_hash = ?", (id_hash,))
|