"""Probe management (UI) and the probe report endpoint (probes, token auth).""" import ipaddress import secrets import time from fastapi import APIRouter, Header, HTTPException, Request from pydantic import BaseModel, Field from app.hub import devices, settings from app.hub.db import db router = APIRouter() MAX_BATCH = 5000 class ProbeCreate(BaseModel): name: str = Field(min_length=1, max_length=60) class ProbeUpdate(BaseModel): name: str | None = Field(default=None, min_length=1, max_length=60) address: str | None = Field(default=None, max_length=255) # "" = detect again from reports port: int | None = Field(default=None, ge=1, le=65535) class Measurement(BaseModel): ts: float target: str = Field(max_length=300) label: str | None = Field(default=None, max_length=200) kind: str = Field(pattern="^(lan|wan)$") method: str = Field(pattern="^(icmp|http|dns|throughput)$") ok: bool latency: float | None = None loss: float | None = None mbps: float | None = None error: str | None = Field(default=None, max_length=300) class Neighbor(BaseModel): ip: str = Field(max_length=64) mac: str = Field(max_length=32) class Report(BaseModel): version: str | None = Field(default=None, max_length=40) hostname: str | None = Field(default=None, max_length=255) port: int = Field(default=8765, ge=1, le=65535) advertise_addr: str | None = Field(default=None, max_length=255) icmp: bool | None = None measurements: list[Measurement] = Field(default_factory=list, max_length=MAX_BATCH) neighbors: list[Neighbor] = Field(default_factory=list, max_length=4096) def is_online(row, now: float | None = None) -> bool: now = now or time.time() return bool(row["last_seen"]) and now - row["last_seen"] < settings.get().probe_interval * 3 + 10 def probe_out(row, *, with_token: bool = False) -> dict: out = {k: row[k] for k in ("id", "name", "address", "port", "hostname", "version", "created", "last_seen", "last_error")} out["address_locked"] = bool(row["address_locked"]) out["icmp"] = None if row["icmp"] is None else bool(row["icmp"]) out["online"] = is_online(row) if with_token: out["token"] = row["token"] return out @router.get("/probes") def list_probes() -> dict: with db() as con: rows = con.execute("SELECT * FROM probes ORDER BY name COLLATE NOCASE").fetchall() s = settings.get() return {"probes": [probe_out(r) for r in rows], "interval": s.probe_interval, "install_url": s.probe_install_url, "hub_url": s.hub_public_url} @router.post("/probes", status_code=201) def create_probe(body: ProbeCreate) -> dict: token = secrets.token_urlsafe(24) with db() as con: cur = con.execute("INSERT INTO probes(name, token, created) VALUES (?, ?, ?)", (body.name.strip(), token, time.time())) row = con.execute("SELECT * FROM probes WHERE id = ?", (cur.lastrowid,)).fetchone() return probe_out(row, with_token=True) def _get(con, probe_id: int): row = con.execute("SELECT * FROM probes WHERE id = ?", (probe_id,)).fetchone() if not row: raise HTTPException(404, "No probe with that id") return row @router.get("/probes/{probe_id}") def get_probe(probe_id: int) -> dict: with db() as con: return probe_out(_get(con, probe_id), with_token=True) @router.patch("/probes/{probe_id}") def update_probe(probe_id: int, body: ProbeUpdate) -> dict: with db() as con: _get(con, probe_id) if body.name is not None: con.execute("UPDATE probes SET name = ? WHERE id = ?", (body.name.strip(), probe_id)) if body.address is not None: addr = body.address.strip() con.execute("UPDATE probes SET address = ?, address_locked = ? WHERE id = ?", (addr or None, int(bool(addr)), probe_id)) if body.port is not None: con.execute("UPDATE probes SET port = ? WHERE id = ?", (body.port, probe_id)) return probe_out(_get(con, probe_id), with_token=True) @router.delete("/probes/{probe_id}", status_code=204) def delete_probe(probe_id: int, keep_history: bool = False) -> None: with db() as con: _get(con, probe_id) con.execute("DELETE FROM probes WHERE id = ?", (probe_id,)) if not keep_history: con.execute("DELETE FROM measurements WHERE probe_id = ?", (probe_id,)) def probe_config(con, row) -> dict: """What a probe should test, returned on every report.""" s = settings.get() peers = [ {"id": p["id"], "name": p["name"], "host": p["address"], "port": p["port"] or 8765} for p in con.execute("SELECT * FROM probes WHERE id != ? AND address IS NOT NULL ORDER BY id", (row["id"],)) ] dns = [{"server": d, "label": "LAN DNS" if len(s.lan_dns_servers) == 1 else f"LAN DNS {d}", "kind": "lan"} for d in s.lan_dns_servers] dns += [{"server": d, "label": f"DNS {d}", "kind": "wan"} for d in s.dns_servers] http = [{"url": u, "label": u.split("//", 1)[-1].split("/", 1)[0], "kind": "wan", "target": f"web:{u}"} for u in s.wan_http_urls] if s.vps_url: http.append({"url": f"{s.vps_url}/probe/ping", "label": "VPS", "kind": "wan", "target": "vps"}) return { "probe_id": row["id"], "name": row["name"], "interval": s.probe_interval, "peers": peers, "dns": dns, "dns_name": s.dns_query_name, "http": http, "throughput_every": s.throughput_every, "throughput_bytes": s.throughput_bytes, } def _client_ip(request: Request) -> str | None: host = request.client.host if request.client else None try: return str(ipaddress.ip_address(host)) if host else None except ValueError: return None @router.post("/probe/report") def report(body: Report, request: Request, authorization: str = Header(default="")) -> dict: token = authorization.removeprefix("Bearer ").strip() now = time.time() with db() as con: row = con.execute("SELECT * FROM probes WHERE token = ?", (token,)).fetchone() if token else None if not row: raise HTTPException(401, "Unknown probe token. Add the probe on the hub and use its install command.") address = row["address"] if not row["address_locked"]: address = (body.advertise_addr or "").strip() or _client_ip(request) or address con.execute( "UPDATE probes SET address = ?, port = ?, hostname = ?, version = ?, icmp = ?, last_seen = ?, last_error = NULL WHERE id = ?", (address, body.port, body.hostname, body.version, None if body.icmp is None else int(body.icmp), now, row["id"]), ) con.executemany( "INSERT INTO measurements(ts, probe_id, target, label, kind, method, ok, latency, loss, mbps, error) VALUES (?,?,?,?,?,?,?,?,?,?,?)", [(m.ts, row["id"], m.target, m.label, m.kind, m.method, int(m.ok), m.latency, m.loss, m.mbps, m.error) for m in body.measurements], ) for n in body.neighbors: devices.sighting(con, ip=n.ip, mac=n.mac, source="arp", seen=now) row = con.execute("SELECT * FROM probes WHERE id = ?", (row["id"],)).fetchone() return probe_config(con, row)