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
+45 -130
View File
@@ -4,11 +4,14 @@ Exposes /api/network/* and delegates to vacuum-walld for interface
IP configuration via systemd-networkd.
"""
import logging
from typing import Any
from flask import Blueprint, request
from flask import Blueprint
from daemon.client import NotFound, get, post
from daemon.client import ( # noqa: F401 (resolved via module globals at dispatch)
get,
post,
)
from daemon.iface import (
GET_NETWORK_INFER_DHCP_RANGES,
GET_NETWORK_INFER_ZONES,
@@ -19,150 +22,62 @@ from daemon.iface import (
POST_NETWORK_INTERFACE_RELOAD,
)
from lib.common import validate_interface_name
from webui.api.common import _error, _ok
from webui.api.common import daemon_route
logger = logging.getLogger(__name__)
bp = Blueprint("network", __name__)
@bp.route("/interfaces", methods=["GET"])
def _check_iface(_json: Any, view_args: dict[str, Any]) -> None:
"""Validate the interface name path param (400 on a bad name)."""
validate_interface_name(view_args["name"])
def _applied(_data: Any, view_args: dict[str, Any], _sent: Any) -> Any:
return {"name": view_args["name"], "applied": True}
def _reloaded(_data: Any, view_args: dict[str, Any], _sent: Any) -> Any:
return {"name": view_args["name"], "reloaded": True}
@daemon_route(GET_NETWORK_INTERFACES, bp)
def list_interfaces():
"""List all interfaces with their network config and runtime state.
Endpoint:
GET /api/network/interfaces
Returns:
JSON with interface config + runtime state.
"""
try:
return _ok(get(GET_NETWORK_INTERFACES))
except RuntimeError as exc:
logger.error("Failed to list network interfaces: %s", exc)
return _error(str(exc), 500)
"""GET /api/network/interfaces — List interfaces with config + runtime state."""
@bp.route("/interfaces/<name>", methods=["GET"])
def get_interface(name: str):
"""Get config + runtime state for a specific interface.
Endpoint:
GET /api/network/interfaces/<name>
Returns:
JSON with interface config and runtime state.
"""
try:
validate_interface_name(name)
return _ok(get(GET_NETWORK_INTERFACE_NAME, {"name": name}))
except ValueError as exc:
return _error(str(exc), 400)
except NotFound as exc:
logger.info("Interface '%s' not found: %s", name, exc)
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to get interface '%s': %s", name, exc)
return _error(str(exc), 500)
@daemon_route(GET_NETWORK_INTERFACE_NAME, bp, precheck=_check_iface)
def get_interface():
"""GET /api/network/interfaces/<name> — Config + runtime state for one interface."""
@bp.route("/interfaces/<name>", methods=["POST"])
def save_interface(name: str):
"""Save and apply network config for an interface.
Endpoint:
POST /api/network/interfaces/<name>
Args:
body: JSON with addresses, gateway, dns, routes.
Returns:
JSON confirmation.
"""
body = {**(request.get_json(silent=True) or {}), "name": name}
try:
validate_interface_name(name)
post(POST_NETWORK_INTERFACE_NAME, body)
logger.info("Interface '%s' config saved", name)
return _ok({"name": name, "applied": True})
except ValueError as exc:
return _error(str(exc), 400)
except NotFound as exc:
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to save interface '%s': %s", name, exc)
return _error(str(exc), 500)
@daemon_route(
POST_NETWORK_INTERFACE_NAME, bp, precheck=_check_iface, transform=_applied
)
def save_interface():
"""POST /api/network/interfaces/<name> — Save and apply an interface's config."""
@bp.route("/interfaces/<name>/reload", methods=["POST"])
def reload_interface(name: str):
"""Reload networkd for a single interface.
Endpoint:
POST /api/network/interfaces/<name>/reload
Returns:
JSON confirmation.
"""
try:
validate_interface_name(name)
post(POST_NETWORK_INTERFACE_RELOAD, {"name": name})
logger.info("Interface '%s' reloaded", name)
return _ok({"name": name, "reloaded": True})
except ValueError as exc:
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to reload interface '%s': %s", name, exc)
return _error(str(exc), 500)
@daemon_route(
POST_NETWORK_INTERFACE_RELOAD,
bp,
precheck=_check_iface,
body={},
transform=_reloaded,
)
def reload_interface():
"""POST /api/network/interfaces/<name>/reload — Reload networkd for one interface."""
@bp.route("/apply", methods=["POST"])
@daemon_route(POST_NETWORK_APPLY, bp)
def apply_all():
"""Apply network config for ALL interfaces (full sync).
Endpoint:
POST /api/network/apply
Returns:
JSON with number of interfaces applied.
"""
try:
result = post(POST_NETWORK_APPLY, {})
logger.info("Network config applied: %d interfaces", result.get("applied", 0))
return _ok(result)
except RuntimeError as exc:
logger.error("Failed to apply network config: %s", exc)
return _error(str(exc), 500)
"""POST /api/network/apply — Apply network config for ALL interfaces."""
@bp.route("/infer-dhcp-ranges", methods=["GET"])
@daemon_route(GET_NETWORK_INFER_DHCP_RANGES, bp)
def infer_dhcp_ranges():
"""Suggest candidate DHCP ranges based on static interface IPs.
Endpoint:
GET /api/network/infer-dhcp-ranges
Returns:
JSON with per-interface suggested DHCP ranges.
"""
try:
return _ok(get(GET_NETWORK_INFER_DHCP_RANGES))
except RuntimeError as exc:
logger.error("Failed to infer DHCP ranges: %s", exc)
return _error(str(exc), 500)
"""GET /api/network/infer-dhcp-ranges — Suggest candidate DHCP ranges."""
@bp.route("/infer-zones", methods=["GET"])
@daemon_route(GET_NETWORK_INFER_ZONES, bp)
def infer_zones():
"""Suggest firewalld zone assignments for configured interfaces.
Endpoint:
GET /api/network/infer-zones
Returns:
JSON with per-interface suggested zone names.
"""
try:
return _ok(get(GET_NETWORK_INFER_ZONES))
except RuntimeError as exc:
logger.error("Failed to infer zones: %s", exc)
return _error(str(exc), 500)
"""GET /api/network/infer-zones — Suggest firewalld zone assignments."""