refactor: introduce two-user daemon architecture with socket-based communication

- Add daemon/ module with aiohttp server, sync client, and handler registry
- Add daemon/handlers/ for privileged operations (acme, dnsmasq, firewall, logs, nginx, wireguard)
- Add system/acme-deploy.py, vacuum-walld sudoers and systemd service
- Update API routes to use daemon client instead of lib/ directly
- Update lib/, tests/, and webui/ for new architecture
- Update docs and deployment scripts
This commit is contained in:
2026-05-27 23:38:23 +00:00
parent 5ac69dfa7e
commit 200e078bc5
39 changed files with 4671 additions and 1810 deletions
+113 -83
View File
@@ -1,34 +1,13 @@
"""Firewall (firewalld) management API blueprint.
Exposed at /api/firewall/* and delegates all mutations to lib.firewall.
Exposed at /api/firewall/* and delegates all operations to vacuum-walld.
"""
import logging
from flask import Blueprint, request
from lib.common import deep_merge
from lib.firewall import (
add_forward_port,
add_rich_rule,
config_apply,
config_pending,
create_zone,
delete_zone,
get_active_zones,
get_available_zones,
get_config,
get_interfaces,
get_rich_rules,
get_services,
get_zone_info,
remove_forward_port_by_id,
remove_rich_rule_by_id,
save_config,
set_masquerade,
set_zone_interfaces,
set_zone_services,
)
from daemon.client import BadRequest, NotFound, delete, get, patch, post
from webui.api.common import _error, _ok
logger = logging.getLogger(__name__)
@@ -43,7 +22,7 @@ bp = Blueprint("firewall", __name__)
@bp.route("/config", methods=["GET"])
def config_list():
try:
return _ok(get_config())
return _ok(get("/firewall/config"))
except RuntimeError as exc:
logger.error("Failed to read firewall config: %s", exc)
return _error(str(exc), 500)
@@ -57,17 +36,27 @@ def config_save():
if not isinstance(body["zones"], dict):
return _error("'zones' must be a dict", 400)
try:
save_config(body)
pending_info = config_pending()
post("/firewall/config", body)
try:
pending = get("/firewall/config/pending")
pending_data = {
"pending": pending.get("pending", []),
"needs_apply": pending.get("needs_apply", False),
"unmanaged_zones": pending.get("unmanaged_zones", {}),
}
except RuntimeError as exc:
pending_data = None
logger.warning("Failed to read pending state after config save: %s", exc)
logger.info("Firewall config saved (%d zones)", len(body["zones"]))
return _ok(
{
"config_saved": True,
"pending": pending_info["pending"],
"needs_apply": pending_info["needs_apply"],
"unmanaged_zones": pending_info.get("unmanaged_zones", {}),
**(pending_data or {}),
}
)
except BadRequest as exc:
logger.info("Firewall config save rejected: %s", exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to save firewall config: %s", exc)
return _error(str(exc), 500)
@@ -79,19 +68,26 @@ def patch_config():
if not isinstance(body, dict):
return _error("Request body must be a JSON object", 400)
try:
current = get_config()
merged = deep_merge(current, body)
save_config(merged)
pending_info = config_pending()
logger.info("Firewall config patched: %s", sorted(body.keys()))
patch("/firewall/config", body)
try:
pending = get("/firewall/config/pending")
pending_data = {
"pending": pending.get("pending", []),
"needs_apply": pending.get("needs_apply", False),
"unmanaged_zones": pending.get("unmanaged_zones", {}),
}
except RuntimeError as exc:
pending_data = None
logger.warning("Failed to read pending state after config patch: %s", exc)
return _ok(
{
"config_saved": True,
"pending": pending_info["pending"],
"needs_apply": pending_info["needs_apply"],
"unmanaged_zones": pending_info.get("unmanaged_zones", {}),
**(pending_data or {}),
}
)
except BadRequest as exc:
logger.info("Firewall config patch rejected: %s", exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to patch firewall config: %s", exc)
return _error(str(exc), 500)
@@ -100,7 +96,7 @@ def patch_config():
@bp.route("/config/apply", methods=["POST"])
def config_apply_bp():
try:
result = config_apply()
result = post("/firewall/config/apply")
logger.info("Firewall config applied: %s", result.get("applied_zones", []))
return _ok(result)
except RuntimeError as exc:
@@ -111,7 +107,7 @@ def config_apply_bp():
@bp.route("/config/pending", methods=["GET"])
def config_pending_bp():
try:
return _ok(config_pending())
return _ok(get("/firewall/config/pending"))
except RuntimeError as exc:
logger.error("Failed to check pending config: %s", exc)
return _error(str(exc), 500)
@@ -125,9 +121,10 @@ def config_pending_bp():
@bp.route("/zones", methods=["GET"])
def list_zones():
try:
active = get_active_zones()
available = get_available_zones()
return _ok({"active": active, "available": available})
data = get("/firewall/zones")
return _ok(
{"active": data.get("active", {}), "available": data.get("available", [])}
)
except RuntimeError as exc:
logger.error("Failed to list zones: %s", exc)
return _error(str(exc), 500)
@@ -136,10 +133,11 @@ def list_zones():
@bp.route("/zones/<name>", methods=["GET"])
def zone_details(name: str):
try:
if name not in get_available_zones():
return _error(f"Zone '{name}' does not exist", 404)
info = get_zone_info(name)
info = get("/firewall/zones/info", {"zone": name})
return _ok(info)
except NotFound as exc:
logger.info("Zone '%s' not found: %s", name, exc)
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to get zone '%s' info: %s", name, exc)
return _error(str(exc), 500)
@@ -153,11 +151,12 @@ def create_zone_bp():
if not zone_name:
return _error("Zone name is required", 400)
try:
if zone_name in get_available_zones():
return _error(f"Zone '{zone_name}' already exists", 400)
create_zone(zone_name, target)
post("/firewall/zones/create", {"name": zone_name, "target": target})
logger.info("Zone '%s' created via API", zone_name)
return _ok(None)
except BadRequest as exc:
logger.info("Zone '%s' creation rejected: %s", zone_name, exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to create zone '%s': %s", zone_name, exc)
return _error(str(exc), 500)
@@ -166,12 +165,12 @@ def create_zone_bp():
@bp.route("/zones/<name>", methods=["DELETE"])
def delete_zone_bp(name: str):
try:
available = get_available_zones()
if name not in available:
return _error(f"Zone '{name}' does not exist", 404)
delete_zone(name)
delete("/firewall/zones/delete", {"zone": name})
logger.info("Zone '%s' deleted via API", name)
return _ok(None)
except NotFound as exc:
logger.info("Zone '%s' not found: %s", name, exc)
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to delete zone '%s': %s", name, exc)
return _error(str(exc), 500)
@@ -189,9 +188,15 @@ def set_zone_interfaces_bp(name: str):
if not isinstance(interfaces, list):
return _error("'interfaces' must be a list", 400)
try:
set_zone_interfaces(name, interfaces)
post("/firewall/zones/interfaces", {"zone": name, "interfaces": interfaces})
logger.info("Zone '%s' interfaces updated: %s", name, interfaces)
return _ok({"zone": name, "interfaces": interfaces})
except BadRequest as exc:
logger.info("Set interfaces for zone '%s' rejected: %s", name, exc)
return _error(str(exc), 400)
except NotFound as exc:
logger.info("Zone '%s' not found: %s", name, exc)
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to set interfaces for zone '%s': %s", name, exc)
return _error(str(exc), 500)
@@ -209,8 +214,14 @@ def set_zone_services_bp(name: str):
if not isinstance(services, list):
return _error("'services' must be a list", 400)
try:
set_zone_services(name, services)
post("/firewall/zones/services", {"zone": name, "services": services})
return _ok({"zone": name, "services": services})
except BadRequest as exc:
logger.info("Set services for zone '%s' rejected: %s", name, exc)
return _error(str(exc), 400)
except NotFound as exc:
logger.info("Zone '%s' not found: %s", name, exc)
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to set services for zone '%s': %s", name, exc)
return _error(str(exc), 500)
@@ -224,7 +235,7 @@ def set_zone_services_bp(name: str):
@bp.route("/services", methods=["GET"])
def list_services():
try:
return _ok(get_services())
return _ok(get("/firewall/services"))
except RuntimeError as exc:
logger.error("Failed to list services: %s", exc)
return _error(str(exc), 500)
@@ -233,7 +244,7 @@ def list_services():
@bp.route("/interfaces", methods=["GET"])
def list_interfaces():
try:
return _ok(get_interfaces())
return _ok(get("/firewall/interfaces"))
except RuntimeError as exc:
logger.error("Failed to list interfaces: %s", exc)
return _error(str(exc), 500)
@@ -252,9 +263,12 @@ def add_rich_rule_bp():
if not zone or not rule:
return _error("Both 'zone' and 'rule' are required", 400)
try:
entry = add_rich_rule(zone, rule)
entry = post("/firewall/rich-rules/add", {"zone": zone, "rule": rule})
logger.info("Rich rule added to zone '%s': %s", zone, rule[:80])
return _ok({"zone": zone, "id": entry["id"], "rule": rule})
except BadRequest as exc:
logger.info("Add rich rule for zone '%s' rejected: %s", zone, exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to add rich rule to zone '%s': %s", zone, exc)
return _error(str(exc), 500)
@@ -263,17 +277,7 @@ def add_rich_rule_bp():
@bp.route("/rich-rules/<zone>", methods=["GET"])
def list_rich_rules(zone: str):
try:
rules = get_rich_rules(zone)
cfg = get_config()
cfg_entries = cfg.get("zones", {}).get(zone, {}).get("rich_rules", [])
result = []
for rule_str in rules:
matched = next((e for e in cfg_entries if e.get("rule") == rule_str), None)
if matched:
result.append({"id": matched["id"], "rule": rule_str})
else:
result.append({"rule": rule_str})
return _ok(result)
return _ok(get("/firewall/rich-rules", {"zone": zone}))
except RuntimeError as exc:
logger.error("Failed to get rich rules for zone '%s': %s", zone, exc)
return _error(str(exc), 500)
@@ -282,10 +286,11 @@ def list_rich_rules(zone: str):
@bp.route("/rich-rules/<zone>/<rule_id>", methods=["DELETE"])
def remove_rich_rule_bp(zone: str, rule_id: str):
try:
remove_rich_rule_by_id(zone, rule_id)
delete("/firewall/rich-rules/remove", {"zone": zone, "id": rule_id})
logger.info("Rich rule '%s' removed from zone '%s'", rule_id, zone)
return _ok({"zone": zone, "id": rule_id})
except ValueError as exc:
except NotFound as exc:
logger.info("Rich rule '%s' not found in zone '%s': %s", rule_id, zone, exc)
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to remove rich rule from zone '%s': %s", zone, exc)
@@ -305,13 +310,16 @@ def set_masquerade_bp():
if not zone or enable is None:
return _error("'zone' and 'enable' (bool) are required", 400)
try:
set_masquerade(zone, bool(enable))
post("/firewall/masquerade", {"zone": zone, "enable": bool(enable)})
logger.info(
"Masquerade %s on zone '%s' via API",
"enabled" if enable else "disabled",
zone,
)
return _ok({"zone": zone, "masquerade": bool(enable)})
except BadRequest as exc:
logger.info("Set masquerade for zone '%s' rejected: %s", zone, exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to set masquerade on zone '%s': %s", zone, exc)
return _error(str(exc), 500)
@@ -333,27 +341,49 @@ def add_forward_port_bp():
if not zone or port is None or not proto:
return _error("'zone', 'port', and 'proto' are required", 400)
try:
entry = add_forward_port(
zone,
int(port),
proto,
toaddr=str(toaddr) if toaddr else None,
toport=int(toport) if toport else None,
port_int = int(port)
except ValueError:
return _error("'port' must be an integer", 400)
toport_int = None
if toport is not None:
try:
toport_int = int(toport)
except ValueError:
return _error("'toport' must be an integer", 400)
toaddr_str = str(toaddr) if toaddr else None
try:
entry = post(
"/firewall/forward-port/add",
{
"zone": zone,
"port": port_int,
"proto": proto,
"toaddr": toaddr_str,
"toport": toport_int,
},
)
return _ok({"zone": zone, "id": entry["id"], "port": int(port), "proto": proto})
except (ValueError, RuntimeError) as exc:
code = 400 if isinstance(exc, ValueError) else 500
return _ok({"zone": zone, "id": entry["id"], "port": port_int, "proto": proto})
except BadRequest as exc:
logger.info("Add forward port rejected: %s", exc)
return _error(str(exc), 400)
except RuntimeError as exc:
logger.error("Failed to add forward port: %s", exc)
return _error(str(exc), code)
return _error(str(exc), 500)
@bp.route("/forward-port/<zone>/<int:port>/<proto>", methods=["DELETE"])
def remove_forward_port_bp(zone: str, port: int, proto: str):
try:
remove_forward_port_by_id(zone, port, proto)
delete(
"/firewall/forward-port/remove",
{"zone": zone, "port": port, "proto": proto},
)
logger.info("Forward port %s/%s removed from zone '%s'", port, proto, zone)
return _ok({"zone": zone, "port": port, "proto": proto})
except ValueError as exc:
except NotFound as exc:
logger.info(
"Forward port %s/%s not found in zone '%s': %s", port, proto, zone, exc
)
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to remove forward port from zone '%s': %s", zone, exc)