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:
+28
-55
@@ -1,36 +1,24 @@
|
||||
"""ACME certificate management API blueprint.
|
||||
|
||||
Exposed at /api/certs/* and delegates to lib.acme.
|
||||
Exposed at /api/certs/* and delegates to vacuum-walld.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from lib.acme import (
|
||||
get_cert_info,
|
||||
issue,
|
||||
list_certs,
|
||||
remove,
|
||||
renew,
|
||||
set_email,
|
||||
)
|
||||
from daemon.client import BadRequest, NotFound, delete, get, post
|
||||
from webui.api.common import _error, _ok
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("certs", __name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Certificate listing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/list", methods=["GET"])
|
||||
def list_certs_bp():
|
||||
try:
|
||||
return _ok(list_certs())
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
return _ok(get("/acme/list"))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list certificates: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
@@ -38,20 +26,15 @@ def list_certs_bp():
|
||||
@bp.route("/<domain>", methods=["GET"])
|
||||
def cert_details(domain: str):
|
||||
try:
|
||||
info = get_cert_info(domain)
|
||||
return _ok(info)
|
||||
except ValueError as exc:
|
||||
return _ok(get("/acme/info", {"domain": domain}))
|
||||
except NotFound as exc:
|
||||
logger.info("Cert for '%s' not found: %s", domain, exc)
|
||||
return _error(str(exc), 404)
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get cert info for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Issue
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/issue", methods=["POST"])
|
||||
def issue_bp():
|
||||
body = request.get_json(silent=True) or {}
|
||||
@@ -62,59 +45,46 @@ def issue_bp():
|
||||
email = body.get("email", "").strip() or None
|
||||
try:
|
||||
logger.info("Certificate issuance requested for '%s' via API", domain)
|
||||
issue(domain, webroot=webroot, email=email)
|
||||
post("/acme/issue", {"domain": domain, "webroot": webroot, "email": email})
|
||||
logger.info("Certificate issued for '%s'", domain)
|
||||
return _ok(None)
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
except BadRequest as exc:
|
||||
logger.info("Cert issue for '%s' rejected: %s", domain, exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to issue cert for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Renew
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/<domain>/renew", methods=["POST"])
|
||||
def renew_bp(domain: str):
|
||||
try:
|
||||
logger.info("Certificate renewal requested for '%s' via API", domain)
|
||||
renew(domain)
|
||||
post("/acme/renew", {"domain": domain})
|
||||
logger.info("Certificate renewed for '%s'", domain)
|
||||
return _ok(None)
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
except BadRequest as exc:
|
||||
logger.info("Cert renew for '%s' rejected: %s", domain, exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to renew cert for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Remove
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/<domain>", methods=["DELETE"])
|
||||
def remove_bp(domain: str):
|
||||
try:
|
||||
get_cert_info(domain)
|
||||
except ValueError as exc:
|
||||
return _error(str(exc), 404)
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
logger.error("Failed to verify cert '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
try:
|
||||
remove(domain)
|
||||
delete("/acme/remove", {"domain": domain})
|
||||
logger.info("Certificate removed for '%s' via API", domain)
|
||||
return _ok(None)
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
except NotFound as exc:
|
||||
logger.info("Cert '%s' not found: %s", domain, exc)
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove cert '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Contact email
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/email", methods=["POST"])
|
||||
def set_email_bp():
|
||||
body = request.get_json(silent=True) or {}
|
||||
@@ -122,9 +92,12 @@ def set_email_bp():
|
||||
if not email:
|
||||
return _error("'email' is required", 400)
|
||||
try:
|
||||
set_email(email)
|
||||
post("/acme/email", {"email": email})
|
||||
logger.info("ACME email set via API: %s", email)
|
||||
return _ok({"email": email})
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
except BadRequest as exc:
|
||||
logger.info("ACME email set rejected: %s", exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to set ACME email: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
+54
-53
@@ -1,29 +1,13 @@
|
||||
"""
|
||||
webui/api/dhcp.py - DHCP/DNS (dnsmasq) management API blueprint.
|
||||
"""DHCP/DNS (dnsmasq) management API blueprint.
|
||||
|
||||
Exposed at /api/dhcp/* and delegates all operations to lib.dnsmasq.
|
||||
Exposed at /api/dhcp/* and delegates all operations to vacuum-walld.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from lib.common import deep_merge
|
||||
from lib.dnsmasq import (
|
||||
add_dns_record,
|
||||
add_static_lease,
|
||||
apply_config,
|
||||
get_config,
|
||||
get_lease_table,
|
||||
remove_dhcp_range,
|
||||
remove_dns_record,
|
||||
remove_static_lease,
|
||||
save_config,
|
||||
set_dhcp_range,
|
||||
)
|
||||
from lib.dnsmasq import (
|
||||
get_status as dnsmasq_status,
|
||||
)
|
||||
from daemon.client import BadRequest, NotFound, delete, get, patch, post
|
||||
from webui.api.common import _error, _ok
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -38,7 +22,7 @@ bp = Blueprint("dhcp", __name__)
|
||||
@bp.route("/config", methods=["GET"])
|
||||
def get_config_bp():
|
||||
try:
|
||||
return _ok(get_config())
|
||||
return _ok(get("/dnsmasq/config"))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to read DHCP config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -50,8 +34,11 @@ def post_config():
|
||||
if not isinstance(body, dict):
|
||||
return _error("Request body must be a JSON object", 400)
|
||||
try:
|
||||
save_config(body)
|
||||
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)
|
||||
@@ -63,10 +50,11 @@ 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)
|
||||
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)
|
||||
@@ -75,7 +63,7 @@ def patch_config():
|
||||
@bp.route("/apply", methods=["POST"])
|
||||
def apply_bp():
|
||||
try:
|
||||
apply_config()
|
||||
post("/dnsmasq/apply")
|
||||
logger.info("dnsmasq config applied via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
@@ -91,7 +79,7 @@ def apply_bp():
|
||||
@bp.route("/status", methods=["GET"])
|
||||
def status_bp():
|
||||
try:
|
||||
return _ok(dnsmasq_status())
|
||||
return _ok(get("/dnsmasq/status"))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get DHCP status: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -112,14 +100,20 @@ def add_range_bp():
|
||||
if not start or not end:
|
||||
return _error("'start' and 'end' are required", 400)
|
||||
try:
|
||||
set_dhcp_range(
|
||||
iface if iface else "",
|
||||
start,
|
||||
end,
|
||||
lease_time=lease_time,
|
||||
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)
|
||||
@@ -134,23 +128,28 @@ def remove_range_bp():
|
||||
if not start or not end:
|
||||
return _error("'start' and 'end' are required", 400)
|
||||
try:
|
||||
remove_dhcp_range(iface, start, end)
|
||||
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)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Static leases
|
||||
# Leases
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/leases", methods=["GET"])
|
||||
def leases_bp():
|
||||
try:
|
||||
return _ok(get_lease_table())
|
||||
return _ok(get("/dnsmasq/leases"))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to read lease table: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -170,9 +169,12 @@ def add_static_lease_bp():
|
||||
if not mac or not ip:
|
||||
return _error("'mac' and 'ip' are required", 400)
|
||||
try:
|
||||
add_static_lease(mac, ip, hostname)
|
||||
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)
|
||||
@@ -180,19 +182,15 @@ def add_static_lease_bp():
|
||||
|
||||
@bp.route("/static-lease/<mac>", methods=["DELETE"])
|
||||
def remove_static_lease_bp(mac):
|
||||
current = get_config()
|
||||
found = any(
|
||||
lease["mac"].lower() == mac.lower()
|
||||
for lease in current.get("dhcp", {}).get("static_leases", [])
|
||||
)
|
||||
if not found:
|
||||
return _error(f"No static lease found for MAC '{mac}'", 404)
|
||||
try:
|
||||
remove_static_lease(mac)
|
||||
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", exc)
|
||||
logger.error("Failed to remove static lease '%s': %s", mac, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -210,9 +208,15 @@ def add_dns_record_bp():
|
||||
if not name or not address:
|
||||
return _error("'name' and 'address' are required", 400)
|
||||
try:
|
||||
add_dns_record(name, address, hostname)
|
||||
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)
|
||||
@@ -220,16 +224,13 @@ def add_dns_record_bp():
|
||||
|
||||
@bp.route("/dns-record/<name>", methods=["DELETE"])
|
||||
def remove_dns_record_bp(name):
|
||||
current = get_config()
|
||||
found = any(
|
||||
r["name"] == name for r in current.get("dns", {}).get("custom_records", [])
|
||||
)
|
||||
if not found:
|
||||
return _error(f"No DNS record found for '{name}'", 404)
|
||||
try:
|
||||
remove_dns_record(name)
|
||||
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", exc)
|
||||
logger.error("Failed to remove DNS record '%s': %s", name, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
+113
-83
@@ -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)
|
||||
|
||||
+29
-60
@@ -1,57 +1,17 @@
|
||||
"""
|
||||
webui/api/logs.py - Log viewing API blueprint.
|
||||
"""Log viewing API blueprint.
|
||||
|
||||
Serves log content to the /logs page via HTMX endpoints:
|
||||
/api/logs/journal — systemd journal for vacuum-wall
|
||||
/api/logs/nginx/access — nginx access log tail
|
||||
/api/logs/nginx/error — nginx error log tail
|
||||
/api/logs/dnsmasq — systemd journal for dnsmasq
|
||||
/api/logs/app — Vacuum Wall application log file
|
||||
Serves log content to the /logs page via HTMX endpoints through vacuum-walld.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, render_template_string
|
||||
|
||||
from daemon.client import get
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
bp = Blueprint("logs", __name__)
|
||||
|
||||
PROJECT_DIR = Path(__file__).resolve().parent.parent
|
||||
APP_LOG_FILE = PROJECT_DIR / "data" / "logs" / "vacuum-wall.log"
|
||||
|
||||
_MAX_LINES = 200
|
||||
|
||||
|
||||
def _tail_file(path: str, n: int = _MAX_LINES) -> str:
|
||||
"""Return the last *n* lines of a file."""
|
||||
try:
|
||||
with open(path) as f:
|
||||
lines = f.readlines()
|
||||
return "".join(lines[-n:])
|
||||
except FileNotFoundError:
|
||||
return "(log file not found)\n"
|
||||
except PermissionError:
|
||||
return "(permission denied)\n"
|
||||
|
||||
|
||||
def _sudo_journalctl(unit: str, n: int = _MAX_LINES) -> str:
|
||||
"""Run ``sudo journalctl -u <unit> --no-pager -n <n>`` and return output."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["sudo", "journalctl", "-u", unit, "--no-pager", "-n", str(n)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
)
|
||||
output = result.stdout.strip()
|
||||
return output if output else f"(no journal entries for {unit})\n"
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError) as exc:
|
||||
return f"(error reading journal: {exc})\n"
|
||||
|
||||
|
||||
_LOG_LINE_TEMPLATE = """\
|
||||
{% for line in lines %}
|
||||
<div class="log-line{% if 'ERROR' in line %} log-error{% elif 'WARN' in line %} log-warn{% endif %}">{{ line | e }}</div>
|
||||
@@ -59,41 +19,50 @@ _LOG_LINE_TEMPLATE = """\
|
||||
|
||||
|
||||
def _render_log_lines(text: str) -> str:
|
||||
"""Render raw log text into HTML fragment with line-by-line coloring."""
|
||||
lines = text.rstrip("\n").split("\n") if text.strip() else []
|
||||
return render_template_string(_LOG_LINE_TEMPLATE, lines=lines)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/journal")
|
||||
def journal():
|
||||
text = _sudo_journalctl("vacuum-wall")
|
||||
return _render_log_lines(text)
|
||||
try:
|
||||
text = get("/logs/journal")
|
||||
return _render_log_lines(text)
|
||||
except RuntimeError:
|
||||
return _render_log_lines("(error reading journal)\n")
|
||||
|
||||
|
||||
@bp.route("/nginx/access")
|
||||
def nginx_access():
|
||||
text = _tail_file("/var/log/nginx/access.log")
|
||||
return _render_log_lines(text)
|
||||
try:
|
||||
text = get("/logs/nginx/access")
|
||||
return _render_log_lines(text)
|
||||
except RuntimeError:
|
||||
return _render_log_lines("(log file not found)\n")
|
||||
|
||||
|
||||
@bp.route("/nginx/error")
|
||||
def nginx_error():
|
||||
text = _tail_file("/var/log/nginx/error.log")
|
||||
return _render_log_lines(text)
|
||||
try:
|
||||
text = get("/logs/nginx/error")
|
||||
return _render_log_lines(text)
|
||||
except RuntimeError:
|
||||
return _render_log_lines("(log file not found)\n")
|
||||
|
||||
|
||||
@bp.route("/dnsmasq")
|
||||
def dnsmasq():
|
||||
text = _sudo_journalctl("dnsmasq")
|
||||
return _render_log_lines(text)
|
||||
try:
|
||||
text = get("/logs/dnsmasq")
|
||||
return _render_log_lines(text)
|
||||
except RuntimeError:
|
||||
return _render_log_lines("(error reading journal)\n")
|
||||
|
||||
|
||||
@bp.route("/app")
|
||||
def app_log():
|
||||
text = _tail_file(str(APP_LOG_FILE))
|
||||
return _render_log_lines(text)
|
||||
try:
|
||||
text = get("/logs/app")
|
||||
return _render_log_lines(text)
|
||||
except RuntimeError:
|
||||
return _render_log_lines("(log file not found)\n")
|
||||
|
||||
+58
-75
@@ -1,26 +1,13 @@
|
||||
"""
|
||||
webui/api/proxy.py - Nginx proxy domain management API blueprint.
|
||||
"""Nginx proxy domain management API blueprint.
|
||||
|
||||
Exposed at /api/proxy/* and delegates to lib.nginx.
|
||||
Exposed at /api/proxy/* and delegates to vacuum-walld.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from lib.common import deep_merge
|
||||
from lib.nginx import (
|
||||
add_domain,
|
||||
apply,
|
||||
get_config,
|
||||
get_domains,
|
||||
remove_domain,
|
||||
save_config,
|
||||
set_management_proxy,
|
||||
test_config,
|
||||
update_domain,
|
||||
write_ssl_snippet,
|
||||
)
|
||||
from daemon.client import BadRequest, NotFound, delete, get, patch, post
|
||||
from webui.api.common import _error, _ok
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -29,9 +16,8 @@ bp = Blueprint("proxy", __name__)
|
||||
|
||||
@bp.route("/ssl-apply", methods=["POST"])
|
||||
def ssl_apply_bp():
|
||||
"""Apply (write) the global SSL snippet for all Nginx server blocks."""
|
||||
try:
|
||||
write_ssl_snippet()
|
||||
post("/nginx/ssl-apply")
|
||||
logger.info("SSL snippet written via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
@@ -39,15 +25,10 @@ def ssl_apply_bp():
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config (declarative)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/config", methods=["GET"])
|
||||
def get_config_bp():
|
||||
try:
|
||||
return _ok(get_config())
|
||||
return _ok(get("/nginx/config"))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to read proxy config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -59,9 +40,12 @@ def post_config():
|
||||
if not isinstance(body, dict):
|
||||
return _error("Request body must be a JSON object", 400)
|
||||
try:
|
||||
save_config(body)
|
||||
post("/nginx/config", body)
|
||||
logger.info("Proxy config saved: %s", sorted(body.keys()))
|
||||
return _ok(None)
|
||||
except BadRequest as exc:
|
||||
logger.info("Proxy config save rejected: %s", exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to save proxy config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -73,25 +57,21 @@ 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)
|
||||
patch("/nginx/config", body)
|
||||
logger.info("Proxy config patched: %s", sorted(body.keys()))
|
||||
return _ok(None)
|
||||
except BadRequest as exc:
|
||||
logger.info("Proxy config patch rejected: %s", exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to patch proxy config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Domains
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/domains", methods=["GET"])
|
||||
def list_domains():
|
||||
try:
|
||||
return _ok(get_domains())
|
||||
return _ok(get("/nginx/domains"))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list proxy domains: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -113,26 +93,24 @@ def add_domain_bp():
|
||||
if backend_port is None:
|
||||
return _error("'backend_port' is required", 400)
|
||||
try:
|
||||
add_domain(
|
||||
domain, backend_host, int(backend_port), backend_proto, cert, extra_headers
|
||||
post(
|
||||
"/nginx/domains/add",
|
||||
{
|
||||
"domain": domain,
|
||||
"backend_host": backend_host,
|
||||
"backend_port": int(backend_port),
|
||||
"backend_proto": backend_proto,
|
||||
"cert": cert,
|
||||
"extra_headers": extra_headers,
|
||||
},
|
||||
)
|
||||
logger.info("Proxy domain added via API: %s", domain)
|
||||
return _ok({"domain": domain})
|
||||
except (ValueError, RuntimeError) as exc:
|
||||
logger.error("Failed to add proxy domain '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/domains/<domain>", methods=["GET"])
|
||||
def domain_details(domain):
|
||||
try:
|
||||
cfg = get_config()
|
||||
entry = cfg.get("domains", {}).get(domain)
|
||||
if entry is None:
|
||||
return _error(f"Domain '{domain}' not found", 404)
|
||||
return _ok({"domain": domain, **entry})
|
||||
except BadRequest as exc:
|
||||
logger.info("Add proxy domain '%s' rejected: %s", domain, exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get domain details: %s", exc)
|
||||
logger.error("Failed to add proxy domain '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -142,10 +120,14 @@ def update_domain_bp(domain):
|
||||
if not body:
|
||||
return _error("Request body must be a JSON object with fields to update", 400)
|
||||
try:
|
||||
update_domain(domain, **body)
|
||||
post("/nginx/domains/update", {"domain": domain, **body})
|
||||
logger.info("Proxy domain '%s' updated via API", domain)
|
||||
return _ok({"domain": domain})
|
||||
except KeyError as exc:
|
||||
except BadRequest as exc:
|
||||
logger.info("Update domain '%s' rejected: %s", domain, exc)
|
||||
return _error(str(exc), 400)
|
||||
except NotFound as exc:
|
||||
logger.info("Domain '%s' not found: %s", domain, exc)
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to update domain '%s': %s", domain, exc)
|
||||
@@ -155,26 +137,21 @@ def update_domain_bp(domain):
|
||||
@bp.route("/domains/<domain>", methods=["DELETE"])
|
||||
def remove_domain_bp(domain):
|
||||
try:
|
||||
cfg = get_config()
|
||||
if domain not in cfg.get("domains", {}):
|
||||
return _error(f"Domain '{domain}' not found", 404)
|
||||
remove_domain(domain)
|
||||
delete("/nginx/domains/remove", {"domain": domain})
|
||||
logger.info("Proxy domain removed via API: %s", domain)
|
||||
return _ok({"domain": domain})
|
||||
except NotFound as exc:
|
||||
logger.info("Domain '%s' not found: %s", domain, exc)
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove domain '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Apply / test
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/apply", methods=["POST"])
|
||||
def apply_bp():
|
||||
try:
|
||||
apply()
|
||||
post("/nginx/apply")
|
||||
logger.info("nginx config applied via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
@@ -185,20 +162,15 @@ def apply_bp():
|
||||
@bp.route("/test", methods=["POST"])
|
||||
def test_bp():
|
||||
try:
|
||||
valid, output = test_config()
|
||||
if valid:
|
||||
return _ok({"valid": True, "output": output})
|
||||
return _error(output, 400)
|
||||
result = post("/nginx/test")
|
||||
if result.get("valid"):
|
||||
return _ok({"valid": True, "output": result.get("output", "")})
|
||||
return _error(result.get("output", "unknown error"), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("nginx config test failed: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Management proxy
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/management", methods=["POST"])
|
||||
def management_bp():
|
||||
body = request.get_json(silent=True) or {}
|
||||
@@ -210,10 +182,21 @@ def management_bp():
|
||||
auth_user = body.get("auth_user")
|
||||
auth_pass = body.get("auth_pass")
|
||||
try:
|
||||
set_management_proxy(domain, flask_host, int(flask_port), auth_user, auth_pass)
|
||||
post(
|
||||
"/nginx/management",
|
||||
{
|
||||
"domain": domain,
|
||||
"flask_host": flask_host,
|
||||
"flask_port": int(flask_port),
|
||||
"auth_user": auth_user,
|
||||
"auth_pass": auth_pass,
|
||||
},
|
||||
)
|
||||
logger.info("Management proxy configured via API: %s", domain)
|
||||
return _ok(None)
|
||||
except (ValueError, RuntimeError) as exc:
|
||||
code = 400 if isinstance(exc, ValueError) else 500
|
||||
except BadRequest as exc:
|
||||
logger.info("Management proxy config rejected: %s", exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to set management proxy: %s", exc)
|
||||
return _error(str(exc), code)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
+53
-96
@@ -1,47 +1,23 @@
|
||||
"""
|
||||
webui/api/wireguard.py - WireGuard tunnel management API blueprint.
|
||||
"""WireGuard tunnel management API blueprint.
|
||||
|
||||
Exposed at /api/wireguard/* and delegates to lib.wireguard.
|
||||
Exposed at /api/wireguard/* and delegates to vacuum-walld.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from lib.common import deep_merge
|
||||
from lib.wireguard import (
|
||||
add_peer,
|
||||
apply,
|
||||
down,
|
||||
generate_client_conf,
|
||||
get_config,
|
||||
get_peer_status,
|
||||
get_peers,
|
||||
initialize,
|
||||
remove_peer,
|
||||
save_config,
|
||||
status,
|
||||
)
|
||||
from daemon.client import BadRequest, NotFound, delete, get, patch, post
|
||||
from webui.api.common import _error, _ok
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("wireguard", __name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/config", methods=["GET"])
|
||||
def get_config_bp():
|
||||
try:
|
||||
cfg = get_config()
|
||||
safe = dict(cfg)
|
||||
if "interface" in safe:
|
||||
safe["interface"] = dict(safe["interface"])
|
||||
safe["interface"].pop("private_key", None)
|
||||
return _ok(safe)
|
||||
return _ok(get("/wireguard/config"))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to read WireGuard config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -53,19 +29,15 @@ def post_config():
|
||||
if not isinstance(body, dict):
|
||||
return _error("Request body must be a JSON object", 400)
|
||||
try:
|
||||
# Preserve existing server private key through full replacement
|
||||
current = get_config()
|
||||
current_key = current.get("interface", {}).get("private_key", "")
|
||||
|
||||
if "interface" in body:
|
||||
body = dict(body)
|
||||
body["interface"] = dict(body["interface"])
|
||||
body["interface"].pop("private_key", None)
|
||||
|
||||
if current_key:
|
||||
body.setdefault("interface", {})["private_key"] = current_key
|
||||
|
||||
save_config(body)
|
||||
post("/wireguard/config", body)
|
||||
return _ok(None)
|
||||
except BadRequest as exc:
|
||||
logger.info("WireGuard config save rejected: %s", exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to save WireGuard config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -78,27 +50,24 @@ def patch_config():
|
||||
return _error("Request body must be a JSON object", 400)
|
||||
try:
|
||||
if "interface" in body:
|
||||
body = dict(body)
|
||||
body["interface"] = dict(body["interface"])
|
||||
body["interface"].pop("private_key", None)
|
||||
current = get_config()
|
||||
merged = deep_merge(current, body)
|
||||
save_config(merged)
|
||||
patch("/wireguard/config", body)
|
||||
logger.info("WireGuard config patched: %s", sorted(body.keys()))
|
||||
return _ok(None)
|
||||
except BadRequest as exc:
|
||||
logger.info("WireGuard config patch rejected: %s", exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to patch WireGuard config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Apply / down
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/apply", methods=["POST"])
|
||||
def apply_bp():
|
||||
try:
|
||||
apply()
|
||||
post("/wireguard/apply")
|
||||
logger.info("WireGuard tunnel applied via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
@@ -109,7 +78,7 @@ def apply_bp():
|
||||
@bp.route("/up", methods=["POST"])
|
||||
def up_bp():
|
||||
try:
|
||||
apply()
|
||||
post("/wireguard/apply")
|
||||
logger.info("WireGuard tunnel started via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
@@ -120,7 +89,7 @@ def up_bp():
|
||||
@bp.route("/down", methods=["POST"])
|
||||
def down_bp():
|
||||
try:
|
||||
down()
|
||||
post("/wireguard/down")
|
||||
logger.info("WireGuard tunnel brought down via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
@@ -128,29 +97,19 @@ def down_bp():
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Status
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/status", methods=["GET"])
|
||||
def status_bp():
|
||||
try:
|
||||
return _ok(status())
|
||||
return _ok(get("/wireguard/status"))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get WireGuard status: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Initialize (first-time setup)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/initialize", methods=["POST"])
|
||||
def initialize_bp():
|
||||
try:
|
||||
initialize()
|
||||
post("/wireguard/initialize")
|
||||
logger.info("WireGuard initialized via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
@@ -158,11 +117,6 @@ def initialize_bp():
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Peer management
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/peers", methods=["POST"])
|
||||
def add_peer_bp():
|
||||
body = request.get_json(silent=True) or {}
|
||||
@@ -170,15 +124,21 @@ def add_peer_bp():
|
||||
if not name:
|
||||
return _error("'name' is required", 400)
|
||||
try:
|
||||
peer = add_peer(
|
||||
name=name,
|
||||
endpoint=body.get("endpoint"),
|
||||
allowed_ips=body.get("allowed_ips", []),
|
||||
persistent_keepalive=body.get("persistent_keepalive"),
|
||||
preshared_key=body.get("preshared_key"),
|
||||
peer = post(
|
||||
"/wireguard/peers/add",
|
||||
{
|
||||
"name": name,
|
||||
"endpoint": body.get("endpoint"),
|
||||
"allowed_ips": body.get("allowed_ips", []),
|
||||
"persistent_keepalive": body.get("persistent_keepalive"),
|
||||
"preshared_key": body.get("preshared_key"),
|
||||
},
|
||||
)
|
||||
logger.info("WireGuard peer '%s' added via API", name)
|
||||
return _ok(peer)
|
||||
except BadRequest as exc:
|
||||
logger.info("Add peer '%s' rejected: %s", name, exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to add peer '%s': %s", name, exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -187,12 +147,12 @@ def add_peer_bp():
|
||||
@bp.route("/peers/<name>", methods=["DELETE"])
|
||||
def remove_peer_bp(name):
|
||||
try:
|
||||
cfg = get_config()
|
||||
if name not in cfg.get("peers", {}):
|
||||
return _error(f"Peer '{name}' not found", 404)
|
||||
remove_peer(name)
|
||||
delete("/wireguard/peers/remove", {"name": name})
|
||||
logger.info("WireGuard peer '%s' removed via API", name)
|
||||
return _ok({"name": name})
|
||||
except NotFound as exc:
|
||||
logger.info("WireGuard peer '%s' not found: %s", name, exc)
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove peer '%s': %s", name, exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -201,7 +161,7 @@ def remove_peer_bp(name):
|
||||
@bp.route("/peers", methods=["GET"])
|
||||
def peers_bp():
|
||||
try:
|
||||
return _ok(get_peers())
|
||||
return _ok(get("/wireguard/peers"))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list WireGuard peers: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
@@ -210,37 +170,34 @@ def peers_bp():
|
||||
@bp.route("/peer-status", methods=["GET"])
|
||||
def peer_status_bp():
|
||||
try:
|
||||
return _ok(get_peer_status())
|
||||
return _ok(get("/wireguard/peer-status"))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get WireGuard peer status: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Client config generation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/generate-client", methods=["POST"])
|
||||
def generate_client_bp():
|
||||
body = request.get_json(silent=True) or {}
|
||||
name = body.get("name", "").strip()
|
||||
if not name:
|
||||
return _error("Field 'name' is required", 400)
|
||||
server_endpoint = body.get("server_endpoint", "")
|
||||
if not server_endpoint:
|
||||
return _error("Field 'server_endpoint' is required", 400)
|
||||
try:
|
||||
cfg = get_config()
|
||||
if name not in cfg.get("peers", {}):
|
||||
return _error(f"Peer '{name}' not found", 404)
|
||||
server_endpoint = body.get("server_endpoint", "")
|
||||
server_pubkey = cfg["interface"].get("public_key", "")
|
||||
if not server_endpoint:
|
||||
return _error(
|
||||
"Field 'server_endpoint' is required (e.g., '203.0.113.1:51820')", 400
|
||||
)
|
||||
conf_text = generate_client_conf(name, server_endpoint, server_pubkey)
|
||||
result = post(
|
||||
"/wireguard/generate-client",
|
||||
{
|
||||
"name": name,
|
||||
"server_endpoint": server_endpoint,
|
||||
},
|
||||
)
|
||||
logger.info("Client config generated for peer '%s' via API", name)
|
||||
return _ok({"config": conf_text})
|
||||
except (KeyError, ValueError, RuntimeError) as exc:
|
||||
code = 404 if isinstance(exc, (KeyError, ValueError)) else 500
|
||||
return _ok({"config": result.get("config", "")})
|
||||
except NotFound as exc:
|
||||
logger.info("Peer '%s' not found for client config: %s", name, exc)
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to generate client config for '%s': %s", name, exc)
|
||||
return _error(str(exc), code)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
Reference in New Issue
Block a user