refactor: daemon collectors, thin webui proxies, pure config reads

- move state collectors from lib/state.py to daemon/collectors/ (7
  modules, registration side-effect; daemon/server.py imports the
  package before the first populate())
- webui/api: new daemon_route() decorator factory in common.py
  collapses the try/except daemon-proxy boilerplate in all 8
  blueprints (rules/params/body/transform keep responses identical)
- firewall: interface-coverage invariant — config is the source of
  truth for zone interfaces (absent key = empty, no hands-off
  zones); pure validate_coverage() enforced at save (400) and apply
  (409, force: true overrides), top-level `unmanaged` exemption
- lib: get_config() reads are now pure (no dir creation or writes);
  new lib/bootstrap.py creates runtime dirs and persists the
  one-shot nginx legacy migration at daemon start, after
  system_import (lib.nginx.migrate_config_file)
- lib/common: compute_pending() apply-bookkeeping helper
- daemon: emit_and_refresh() handler helper; refresh_state(bump=) so
  /status/refresh no longer bumps versions (poll/mutation only)
- acme: move --log last so acme.sh never treats a real arg as the
  log-file argument
- docs: AGENTS.md, config.md, state-model.md, api.md updated;
  HARDEN.md dropped (plan implemented); apply-confirm force wording

Tests: 917 passed; ruff check + format clean.
This commit is contained in:
2026-09-03 00:40:56 +00:00
parent 89b64960f3
commit faa076370d
49 changed files with 2834 additions and 3821 deletions
+137 -270
View File
@@ -3,11 +3,16 @@
Exposed at /api/dhcp/* and delegates all operations to vacuum-walld.
"""
import logging
from typing import Any
from flask import Blueprint, request
from flask import Blueprint
from daemon.client import BadRequest, NotFound, delete, get, patch, post
from daemon.client import ( # noqa: F401 (resolved via module globals)
delete,
get,
patch,
post,
)
from daemon.iface import (
DELETE_DNSMASQ_DNS_RECORD_REMOVE,
DELETE_DNSMASQ_RANGES_REMOVE,
@@ -23,252 +28,139 @@ from daemon.iface import (
POST_DNSMASQ_RANGES_ADD,
POST_DNSMASQ_STATIC_LEASE_ADD,
)
from webui.api.common import _error, _ok
from webui.api.common import NO_BODY, daemon_route, require_dict_body, void_transform
logger = logging.getLogger(__name__)
bp = Blueprint("dhcp", __name__)
# ---------------------------------------------------------------------------
# Config
# Config / status
# ---------------------------------------------------------------------------
@bp.route("/config", methods=["GET"])
@daemon_route(GET_DNSMASQ_CONFIG, bp)
def get_config_bp():
"""GET /api/dhcp/config — Retrieve the current dnsmasq configuration.
Returns:
JSON response with the config or an error.
"""
try:
return _ok(get(GET_DNSMASQ_CONFIG))
except RuntimeError as exc:
logger.error("Failed to read DHCP config: %s", exc)
return _error(str(exc), 500)
"""GET /api/dhcp/config — Retrieve the current dnsmasq configuration."""
@bp.route("/config", methods=["POST"])
@daemon_route(
POST_DNSMASQ_CONFIG, bp, precheck=require_dict_body, transform=void_transform
)
def post_config():
"""POST /api/dhcp/config — Save a full replacement dnsmasq configuration.
Args:
request: JSON body containing the complete config object.
Returns:
JSON response with success status or an error.
"""
body = request.get_json(silent=True) or {}
if not isinstance(body, dict):
return _error("Request body must be a JSON object", 400)
try:
post(POST_DNSMASQ_CONFIG, body)
return _ok(None)
except BadRequest as exc:
logger.info("DHCP config save rejected: %s", exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to save DHCP config: %s", exc)
return _error(str(exc), 500)
"""POST /api/dhcp/config — Save a full replacement dnsmasq configuration."""
@bp.route("/config", methods=["PATCH"])
@daemon_route(
PATCH_DNSMASQ_CONFIG, bp, precheck=require_dict_body, transform=void_transform
)
def patch_config():
"""PATCH /api/dhcp/config — Partially update the dnsmasq configuration.
Args:
request: JSON body containing the fields to update.
Returns:
JSON response with success status or an error.
"""
body = request.get_json(silent=True) or {}
if not isinstance(body, dict):
return _error("Request body must be a JSON object", 400)
try:
patch(PATCH_DNSMASQ_CONFIG, body)
return _ok(None)
except BadRequest as exc:
logger.info("DHCP config patch rejected: %s", exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to patch DHCP config: %s", exc)
return _error(str(exc), 500)
"""PATCH /api/dhcp/config — Partially update the dnsmasq configuration."""
@bp.route("/apply", methods=["POST"])
@daemon_route(POST_DNSMASQ_APPLY, bp, body=NO_BODY, transform=void_transform)
def apply_bp():
"""POST /api/dhcp/apply — Apply the current dnsmasq configuration to the running service."""
try:
post(POST_DNSMASQ_APPLY)
logger.info("dnsmasq config applied via API")
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to apply dnsmasq config: %s", exc)
return _error(str(exc), 500)
"""POST /api/dhcp/apply — Apply the current dnsmasq configuration."""
# ---------------------------------------------------------------------------
# Status
# ---------------------------------------------------------------------------
@bp.route("/status", methods=["GET"])
@daemon_route(GET_DNSMASQ_STATUS, bp)
def status_bp():
"""GET /api/dhcp/status — Retrieve dnsmasq service status."""
try:
return _ok(get(GET_DNSMASQ_STATUS))
except RuntimeError as exc:
logger.error("Failed to get DHCP status: %s", exc)
return _error(str(exc), 500)
# ---------------------------------------------------------------------------
# DHCP ranges
# ---------------------------------------------------------------------------
@bp.route("/ranges", methods=["POST"])
def _add_range_body(request: Any, _va: Any) -> dict[str, Any]:
body = request.get_json(silent=True) or {}
iface = (body.get("interface") or "").strip() or None
start = (body.get("start") or "").strip()
end = (body.get("end") or "").strip()
if not start or not end:
raise ValueError("'start' and 'end' are required")
return {
"interface": iface or "",
"start": start,
"end": end,
"lease_time": body.get("lease_time", "12h"),
}
def _remove_range_body(request: Any, _va: Any) -> dict[str, Any]:
body = request.get_json(silent=True) or {}
iface = (body.get("interface") or "").strip() or ""
start = (body.get("start") or "").strip()
end = (body.get("end") or "").strip()
if not start or not end:
raise ValueError("'start' and 'end' are required")
return {"interface": iface, "start": start, "end": end}
@daemon_route(
POST_DNSMASQ_RANGES_ADD,
bp,
rule="/ranges",
body=_add_range_body,
transform=void_transform,
)
def add_range_bp():
"""POST /api/dhcp/ranges — Add a DHCP address range for an interface.
Args:
request: JSON body with `interface`, `start`, `end`, and optional `lease_time`.
Returns:
JSON response with success status or an error.
"""
body = request.get_json(silent=True) or {}
iface = body.get("interface", "").strip() or None
start = body.get("start", "").strip()
end = body.get("end", "").strip()
lease_time = body.get("lease_time", "12h")
if not start or not end:
return _error("'start' and 'end' are required", 400)
try:
post(
POST_DNSMASQ_RANGES_ADD,
{
"interface": iface or "",
"start": start,
"end": end,
"lease_time": lease_time,
},
)
logger.info("DHCP range added via API: %s-%s", start, end)
return _ok(None)
except BadRequest as exc:
logger.info("Add DHCP range rejected: %s", exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to add DHCP range: %s", exc)
return _error(str(exc), 500)
"""POST /api/dhcp/ranges — Add a DHCP address range for an interface."""
@bp.route("/ranges", methods=["DELETE"])
@daemon_route(
DELETE_DNSMASQ_RANGES_REMOVE,
bp,
rule="/ranges",
body=_remove_range_body,
transform=void_transform,
)
def remove_range_bp():
"""DELETE /api/dhcp/ranges — Remove a DHCP address range.
Args:
request: JSON body with `interface`, `start`, and `end`.
Returns:
JSON response with success status or an error.
"""
body = request.get_json(silent=True) or {}
iface = body.get("interface", "").strip() or ""
start = body.get("start", "").strip()
end = body.get("end", "").strip()
if not start or not end:
return _error("'start' and 'end' are required", 400)
try:
delete(
DELETE_DNSMASQ_RANGES_REMOVE,
{"interface": iface, "start": start, "end": end},
)
logger.info("DHCP range removed via API: %s-%s", start, end)
return _ok(None)
except NotFound as exc:
logger.info("Remove DHCP range not found: %s", exc)
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to remove DHCP range: %s", exc)
return _error(str(exc), 500)
"""DELETE /api/dhcp/ranges — Remove a DHCP address range."""
# ---------------------------------------------------------------------------
# Leases
# ---------------------------------------------------------------------------
@bp.route("/leases", methods=["GET"])
@daemon_route(GET_DNSMASQ_LEASES, bp)
def leases_bp():
"""GET /api/dhcp/leases — Retrieve the current DHCP lease table."""
try:
return _ok(get(GET_DNSMASQ_LEASES))
except RuntimeError as exc:
logger.error("Failed to read lease table: %s", exc)
return _error(str(exc), 500)
# ---------------------------------------------------------------------------
# Static leases
# ---------------------------------------------------------------------------
@bp.route("/static-lease", methods=["POST"])
def add_static_lease_bp():
"""POST /api/dhcp/static-lease — Add a static DHCP lease by MAC address.
Args:
request: JSON body with `mac`, `ip`, and optional `hostname`.
Returns:
JSON response with lease details or an error.
"""
def _add_static_lease_body(request: Any, _va: Any) -> dict[str, Any]:
body = request.get_json(silent=True) or {}
mac = body.get("mac", "").strip()
ip = body.get("ip", "").strip()
hostname = body.get("hostname")
mac = (body.get("mac") or "").strip()
ip = (body.get("ip") or "").strip()
if not mac or not ip:
return _error("'mac' and 'ip' are required", 400)
try:
post(
POST_DNSMASQ_STATIC_LEASE_ADD, {"mac": mac, "ip": ip, "hostname": hostname}
)
logger.info("Static lease added via API: %s -> %s", mac, ip)
return _ok({"mac": mac, "ip": ip, "hostname": hostname})
except BadRequest as exc:
logger.info("Add static lease rejected: %s", exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to add static lease: %s", exc)
return _error(str(exc), 500)
raise ValueError("'mac' and 'ip' are required")
return {"mac": mac, "ip": ip, "hostname": body.get("hostname")}
@bp.route("/static-lease/<mac>", methods=["DELETE"])
def remove_static_lease_bp(mac):
"""DELETE /api/dhcp/static-lease/<mac> — Remove a static DHCP lease by MAC address.
def _static_lease_echo(_data: Any, _va: Any, sent: Any) -> Any:
return {"mac": sent["mac"], "ip": sent["ip"], "hostname": sent["hostname"]}
Args:
mac: MAC address of the static lease to remove.
Returns:
JSON response with success status or an error.
"""
try:
delete(DELETE_DNSMASQ_STATIC_LEASE_REMOVE, {"mac": mac})
logger.info("Static lease removed via API: %s", mac)
return _ok(None)
except NotFound as exc:
logger.info("Static lease '%s' not found: %s", mac, exc)
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to remove static lease '%s': %s", mac, exc)
return _error(str(exc), 500)
@daemon_route(
POST_DNSMASQ_STATIC_LEASE_ADD,
bp,
rule="/static-lease",
body=_add_static_lease_body,
transform=_static_lease_echo,
)
def add_static_lease_bp():
"""POST /api/dhcp/static-lease — Add a static DHCP lease by MAC address."""
@daemon_route(
DELETE_DNSMASQ_STATIC_LEASE_REMOVE,
bp,
rule="/static-lease/<mac>",
transform=void_transform,
)
def remove_static_lease_bp():
"""DELETE /api/dhcp/static-lease/<mac> — Remove a static DHCP lease by MAC."""
# ---------------------------------------------------------------------------
@@ -276,35 +168,42 @@ def remove_static_lease_bp(mac):
# ---------------------------------------------------------------------------
@bp.route("/dns-record", methods=["POST"])
def add_dns_record_bp():
"""POST /api/dhcp/dns-record — Add a DNS record.
Args:
request: JSON body with `name`, `address`, and optional `hostname`.
Returns:
JSON response with record details or an error.
"""
def _add_dns_record_body(request: Any, _va: Any) -> dict[str, Any]:
body = request.get_json(silent=True) or {}
name = body.get("name", "").strip()
address = body.get("address", "").strip()
hostname = body.get("hostname")
name = (body.get("name") or "").strip()
address = (body.get("address") or "").strip()
if not name or not address:
return _error("'name' and 'address' are required", 400)
try:
post(
POST_DNSMASQ_DNS_RECORD_ADD,
{"name": name, "address": address, "hostname": hostname},
)
logger.info("DNS record added via API: %s -> %s", name, address)
return _ok({"name": name, "address": address, "hostname": hostname})
except BadRequest as exc:
logger.info("Add DNS record rejected: %s", exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to add DNS record: %s", exc)
return _error(str(exc), 500)
raise ValueError("'name' and 'address' are required")
return {"name": name, "address": address, "hostname": body.get("hostname")}
def _dns_record_echo(_data: Any, _va: Any, sent: Any) -> Any:
return {
"name": sent["name"],
"address": sent["address"],
"hostname": sent["hostname"],
}
@daemon_route(
POST_DNSMASQ_DNS_RECORD_ADD,
bp,
rule="/dns-record",
body=_add_dns_record_body,
transform=_dns_record_echo,
)
def add_dns_record_bp():
"""POST /api/dhcp/dns-record — Add a DNS record."""
@daemon_route(
DELETE_DNSMASQ_DNS_RECORD_REMOVE,
bp,
rule="/dns-record/<name>",
transform=void_transform,
)
def remove_dns_record_bp():
"""DELETE /api/dhcp/dns-record/<name> — Remove a DNS record by name."""
# ---------------------------------------------------------------------------
@@ -312,48 +211,16 @@ def add_dns_record_bp():
# ---------------------------------------------------------------------------
@bp.route("/domain", methods=["POST"])
def _set_domain_body(request: Any, _va: Any) -> dict[str, Any]:
return {"domain": (request.get_json(silent=True) or {}).get("domain")}
@daemon_route(
POST_DNSMASQ_DOMAIN,
bp,
precheck=require_dict_body,
body=_set_domain_body,
transform=void_transform,
)
def set_domain_bp():
"""POST /api/dhcp/domain — Set or clear the DNS search domain.
Args:
request: JSON body with `domain` field (string or null to clear).
Returns:
JSON response with success status or an error.
"""
body = request.get_json(silent=True) or {}
if not isinstance(body, dict):
return _error("Request body must be a JSON object", 400)
try:
post(POST_DNSMASQ_DOMAIN, {"domain": body.get("domain")})
logger.info("DNS domain updated via API: %s", body.get("domain"))
return _ok(None)
except BadRequest as exc:
logger.info("Set DNS domain rejected: %s", exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to set DNS domain: %s", exc)
return _error(str(exc), 500)
@bp.route("/dns-record/<name>", methods=["DELETE"])
def remove_dns_record_bp(name):
"""DELETE /api/dhcp/dns-record/<name> — Remove a DNS record by name.
Args:
name: Name of the DNS record to remove.
Returns:
JSON response with success status or an error.
"""
try:
delete(DELETE_DNSMASQ_DNS_RECORD_REMOVE, {"name": name})
logger.info("DNS record removed via API: %s", name)
return _ok(None)
except NotFound as exc:
logger.info("DNS record '%s' not found: %s", name, exc)
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to remove DNS record '%s': %s", name, exc)
return _error(str(exc), 500)
"""POST /api/dhcp/domain — Set or clear the DNS search domain."""