fix htmx refactor route mismatches and remaining TODO items
- wireguard: POST /peers with JSON encoding (was /add-peer) - rules: delete by rule_id in URL path (was JSON body); pass rule objects with id from server; add hx-disable to initial render - nat: port forward delete uses URL path params to match blueprint - nat: masquerade toggle uses native hx-post/hx-vals (was inline fetch) - app.js renderers updated to use URL path deletes for rules and forwards - remove TODO.md
This commit is contained in:
@@ -4,6 +4,8 @@ webui/api/certs.py - ACME certificate management API blueprint.
|
||||
Exposed at /api/certs/* and delegates to lib.acme.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from lib.acme import (
|
||||
@@ -15,6 +17,7 @@ from lib.acme import (
|
||||
set_email,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("certs", __name__)
|
||||
|
||||
|
||||
@@ -41,6 +44,7 @@ def list_certs_bp():
|
||||
try:
|
||||
return _ok(list_certs())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list certificates: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -52,6 +56,7 @@ def cert_details(domain):
|
||||
except ValueError as exc:
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get cert info for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -68,11 +73,17 @@ def issue_bp():
|
||||
return _error("'domain' is required", 400)
|
||||
webroot = body.get("webroot")
|
||||
try:
|
||||
logger.info("Certificate issuance requested for '%s' via API", domain)
|
||||
result = issue(domain, webroot=webroot)
|
||||
if result.get("success"):
|
||||
logger.info("Certificate issued for '%s'", domain)
|
||||
return _ok(None)
|
||||
logger.error(
|
||||
"Certificate issuance failed for '%s': %s", domain, result.get("error")
|
||||
)
|
||||
return _error(result.get("error", "Unknown error"), 500)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Exception issuing cert for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -84,11 +95,17 @@ def issue_bp():
|
||||
@bp.route("/<domain>/renew", methods=["POST"])
|
||||
def renew_bp(domain):
|
||||
try:
|
||||
logger.info("Certificate renewal requested for '%s' via API", domain)
|
||||
result = renew(domain)
|
||||
if result.get("success"):
|
||||
logger.info("Certificate renewed for '%s'", domain)
|
||||
return _ok(None)
|
||||
logger.error(
|
||||
"Certificate renewal failed for '%s': %s", domain, result.get("error")
|
||||
)
|
||||
return _error(result.get("error", "Unknown error"), 500)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Exception renewing cert for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -104,11 +121,14 @@ def remove_bp(domain):
|
||||
except ValueError as exc:
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to verify cert '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
try:
|
||||
remove(domain)
|
||||
logger.info("Certificate removed for '%s' via API", domain)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove cert '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -125,6 +145,8 @@ def set_email_bp():
|
||||
return _error("'email' is required", 400)
|
||||
try:
|
||||
set_email(email)
|
||||
logger.info("ACME email set via API: %s", email)
|
||||
return _ok({"email": email})
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to set ACME email: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
+85
-11
@@ -4,6 +4,8 @@ webui/api/dhcp.py - DHCP/DNS (dnsmasq) management API blueprint.
|
||||
Exposed at /api/dhcp/* and delegates all operations to lib.dnsmasq.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from lib.dnsmasq import (
|
||||
@@ -12,11 +14,14 @@ from lib.dnsmasq import (
|
||||
apply_config,
|
||||
get_config,
|
||||
get_lease_table,
|
||||
remove_dhcp_range,
|
||||
remove_dns_record,
|
||||
remove_static_lease,
|
||||
save_config,
|
||||
set_dhcp_range,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("dhcp", __name__)
|
||||
|
||||
|
||||
@@ -53,6 +58,7 @@ def get_config_bp():
|
||||
try:
|
||||
return _ok(get_config())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to read DHCP config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -65,6 +71,7 @@ def post_config():
|
||||
save_config(body)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to save DHCP config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -79,6 +86,7 @@ def patch_config():
|
||||
save_config(merged)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to patch DHCP config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -86,13 +94,76 @@ def patch_config():
|
||||
def apply_bp():
|
||||
try:
|
||||
apply_config()
|
||||
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)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Leases
|
||||
# Status
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/status", methods=["GET"])
|
||||
def status_bp():
|
||||
try:
|
||||
from lib.dnsmasq import get_status as dnsmasq_status
|
||||
|
||||
return _ok(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_bp():
|
||||
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:
|
||||
set_dhcp_range(
|
||||
iface if iface else "",
|
||||
start,
|
||||
end,
|
||||
lease_time=lease_time,
|
||||
)
|
||||
logger.info("DHCP range added via API: %s-%s", start, end)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to add DHCP range: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/ranges", methods=["DELETE"])
|
||||
def remove_range_bp():
|
||||
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:
|
||||
remove_dhcp_range(iface, start, end)
|
||||
logger.info("DHCP range removed via API: %s-%s", start, end)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove DHCP range: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Static leases
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -101,6 +172,7 @@ def leases_bp():
|
||||
try:
|
||||
return _ok(get_lease_table())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to read lease table: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -119,16 +191,15 @@ def add_static_lease_bp():
|
||||
return _error("'mac' and 'ip' are required", 400)
|
||||
try:
|
||||
add_static_lease(mac, ip, hostname)
|
||||
logger.info("Static lease added via API: %s -> %s", mac, ip)
|
||||
return _ok({"mac": mac, "ip": ip, "hostname": hostname})
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to add static lease: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/static-lease", methods=["DELETE"])
|
||||
def remove_static_lease_bp():
|
||||
mac = request.args.get("mac", "").strip()
|
||||
if not mac:
|
||||
return _error("Query parameter 'mac' is required", 400)
|
||||
@bp.route("/static-lease/<mac>", methods=["DELETE"])
|
||||
def remove_static_lease_bp(mac):
|
||||
current = get_config()
|
||||
found = any(
|
||||
lease["mac"].lower() == mac.lower()
|
||||
@@ -138,8 +209,10 @@ def remove_static_lease_bp():
|
||||
return _error(f"No static lease found for MAC '{mac}'", 404)
|
||||
try:
|
||||
remove_static_lease(mac)
|
||||
logger.info("Static lease removed via API: %s", mac)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove static lease: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -158,16 +231,15 @@ def add_dns_record_bp():
|
||||
return _error("'name' and 'address' are required", 400)
|
||||
try:
|
||||
add_dns_record(name, address, hostname)
|
||||
logger.info("DNS record added via API: %s -> %s", name, address)
|
||||
return _ok({"name": name, "address": address, "hostname": hostname})
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to add DNS record: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/dns-record", methods=["DELETE"])
|
||||
def remove_dns_record_bp():
|
||||
name = request.args.get("name", "").strip()
|
||||
if not name:
|
||||
return _error("Query parameter 'name' is required", 400)
|
||||
@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", [])
|
||||
@@ -176,6 +248,8 @@ def remove_dns_record_bp():
|
||||
return _error(f"No DNS record found for '{name}'", 404)
|
||||
try:
|
||||
remove_dns_record(name)
|
||||
logger.info("DNS record removed via API: %s", name)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove DNS record: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
+77
-52
@@ -4,6 +4,8 @@ webui/api/firewall.py - Firewall (firewalld) management API blueprint.
|
||||
Exposed at /api/firewall/* and delegates all mutations to lib.firewall.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from lib.firewall import (
|
||||
@@ -20,13 +22,14 @@ from lib.firewall import (
|
||||
get_rich_rules,
|
||||
get_services,
|
||||
get_zone_info,
|
||||
remove_forward_port,
|
||||
remove_rich_rule,
|
||||
remove_forward_port_by_id,
|
||||
remove_rich_rule_by_id,
|
||||
set_masquerade,
|
||||
set_zone_interfaces,
|
||||
set_zone_services,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("firewall", __name__)
|
||||
|
||||
|
||||
@@ -53,6 +56,7 @@ def config_get_bp():
|
||||
try:
|
||||
return _ok(config_get())
|
||||
except Exception as exc:
|
||||
logger.error("Failed to read firewall config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -66,6 +70,7 @@ def config_set_bp():
|
||||
try:
|
||||
config_set(body)
|
||||
pending_info = config_pending()
|
||||
logger.info("Firewall config saved (%d zones)", len(body["zones"]))
|
||||
return _ok(
|
||||
{
|
||||
"config_saved": True,
|
||||
@@ -75,6 +80,7 @@ def config_set_bp():
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to save firewall config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -84,8 +90,10 @@ def config_apply_bp():
|
||||
from lib.firewall import config_apply as _config_apply
|
||||
|
||||
result = _config_apply()
|
||||
logger.info("Firewall config applied: %s", result.get("applied_zones", []))
|
||||
return _ok(result)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to apply firewall config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -94,6 +102,7 @@ def config_pending_bp():
|
||||
try:
|
||||
return _ok(config_pending())
|
||||
except Exception as exc:
|
||||
logger.error("Failed to check pending config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -107,16 +116,9 @@ def list_zones():
|
||||
try:
|
||||
active = get_active_zones()
|
||||
available = get_available_zones()
|
||||
return jsonify(
|
||||
{
|
||||
"ok": True,
|
||||
"data": {
|
||||
"active": active,
|
||||
"available": available,
|
||||
},
|
||||
}
|
||||
)
|
||||
return _ok({"active": active, "available": available})
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list zones: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -126,8 +128,9 @@ def zone_details(name):
|
||||
if name not in get_available_zones():
|
||||
return _error(f"Zone '{name}' does not exist", 404)
|
||||
info = get_zone_info(name)
|
||||
return jsonify({"ok": True, "data": info})
|
||||
return _ok(info)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get zone '%s' info: %s", name, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -142,8 +145,10 @@ def create_zone_bp():
|
||||
if zone_name in get_available_zones():
|
||||
return _error(f"Zone '{zone_name}' already exists", 400)
|
||||
create_zone(zone_name, target)
|
||||
logger.info("Zone '%s' created via API", zone_name)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to create zone '%s': %s", zone_name, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -154,8 +159,10 @@ def delete_zone_bp(name):
|
||||
if name not in available:
|
||||
return _error(f"Zone '{name}' does not exist", 404)
|
||||
delete_zone(name)
|
||||
logger.info("Zone '%s' deleted via API", name)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to delete zone '%s': %s", name, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -172,8 +179,10 @@ def set_zone_interfaces_bp(name):
|
||||
return _error("'interfaces' must be a list", 400)
|
||||
try:
|
||||
set_zone_interfaces(name, interfaces)
|
||||
logger.info("Zone '%s' interfaces updated: %s", name, interfaces)
|
||||
return _ok({"zone": name, "interfaces": interfaces})
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to set interfaces for zone '%s': %s", name, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -192,6 +201,7 @@ def set_zone_services_bp(name):
|
||||
set_zone_services(name, services)
|
||||
return _ok({"zone": name, "services": services})
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to set services for zone '%s': %s", name, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -205,6 +215,7 @@ def list_services():
|
||||
try:
|
||||
return _ok(get_services())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list services: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -213,6 +224,7 @@ def list_interfaces():
|
||||
try:
|
||||
return _ok(get_interfaces())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list interfaces: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -229,23 +241,11 @@ def add_rich_rule_bp():
|
||||
if not zone or not rule:
|
||||
return _error("Both 'zone' and 'rule' are required", 400)
|
||||
try:
|
||||
add_rich_rule(zone, rule)
|
||||
return _ok({"zone": zone, "rule": rule})
|
||||
except RuntimeError as exc:
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/rich-rules", methods=["DELETE"])
|
||||
def remove_rich_rule_bp():
|
||||
body = request.get_json(silent=True) or {}
|
||||
zone = body.get("zone", "").strip()
|
||||
rule = body.get("rule", "").strip()
|
||||
if not zone or not rule:
|
||||
return _error("Both 'zone' and 'rule' are required", 400)
|
||||
try:
|
||||
remove_rich_rule(zone, rule)
|
||||
return _ok({"zone": zone, "rule": rule})
|
||||
entry = add_rich_rule(zone, rule)
|
||||
logger.info("Rich rule added to zone '%s': %s", zone, rule[:80])
|
||||
return _ok({"zone": zone, "id": entry["id"], "rule": rule})
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to add rich rule to zone '%s': %s", zone, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -253,8 +253,35 @@ def remove_rich_rule_bp():
|
||||
def list_rich_rules(zone):
|
||||
try:
|
||||
rules = get_rich_rules(zone)
|
||||
return _ok(rules)
|
||||
from lib.firewall import config_get as firewall_config_get
|
||||
|
||||
cfg = firewall_config_get()
|
||||
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)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get rich rules for zone '%s': %s", zone, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/rich-rules/<zone>/<rule_id>", methods=["DELETE"])
|
||||
def remove_rich_rule_bp(zone, rule_id):
|
||||
try:
|
||||
remove_rich_rule_by_id(zone, 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:
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove rich rule from zone '%s': %s", zone, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -272,8 +299,14 @@ def set_masquerade_bp():
|
||||
return _error("'zone' and 'enable' (bool) are required", 400)
|
||||
try:
|
||||
set_masquerade(zone, 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 RuntimeError as exc:
|
||||
logger.error("Failed to set masquerade on zone '%s': %s", zone, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -293,38 +326,30 @@ 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:
|
||||
add_forward_port(
|
||||
entry = add_forward_port(
|
||||
zone,
|
||||
int(port),
|
||||
proto,
|
||||
toaddr=str(toaddr) if toaddr else None,
|
||||
toport=int(toport) if toport else None,
|
||||
)
|
||||
return _ok({"zone": zone, "port": int(port), "proto": proto})
|
||||
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
|
||||
logger.error("Failed to add forward port: %s", exc)
|
||||
return _error(str(exc), code)
|
||||
|
||||
|
||||
@bp.route("/forward-port", methods=["DELETE"])
|
||||
def remove_forward_port_bp():
|
||||
body = request.get_json(silent=True) or {}
|
||||
zone = body.get("zone", "").strip()
|
||||
port = body.get("port")
|
||||
proto = body.get("proto", "").strip()
|
||||
toaddr = body.get("toaddr")
|
||||
toport = body.get("toport")
|
||||
if not zone or port is None or not proto:
|
||||
return _error("'zone', 'port', and 'proto' are required", 400)
|
||||
@bp.route("/forward-port/<zone>/<int:port>/<proto>", methods=["DELETE"])
|
||||
def remove_forward_port_bp(zone, port, proto):
|
||||
try:
|
||||
remove_forward_port(
|
||||
zone,
|
||||
int(port),
|
||||
proto,
|
||||
toaddr=str(toaddr) if toaddr else None,
|
||||
toport=int(toport) if toport else None,
|
||||
)
|
||||
return _ok({"zone": zone, "port": int(port), "proto": proto})
|
||||
except (ValueError, RuntimeError) as exc:
|
||||
code = 400 if isinstance(exc, ValueError) else 500
|
||||
return _error(str(exc), code)
|
||||
remove_forward_port_by_id(zone, port, 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:
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove forward port from zone '%s': %s", zone, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
webui/api/logs.py - 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
|
||||
"""
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, render_template_string
|
||||
|
||||
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>
|
||||
{% endfor %}"""
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@bp.route("/nginx/access")
|
||||
def nginx_access():
|
||||
text = _tail_file("/var/log/nginx/access.log")
|
||||
return _render_log_lines(text)
|
||||
|
||||
|
||||
@bp.route("/nginx/error")
|
||||
def nginx_error():
|
||||
text = _tail_file("/var/log/nginx/error.log")
|
||||
return _render_log_lines(text)
|
||||
|
||||
|
||||
@bp.route("/dnsmasq")
|
||||
def dnsmasq():
|
||||
text = _sudo_journalctl("dnsmasq")
|
||||
return _render_log_lines(text)
|
||||
|
||||
|
||||
@bp.route("/app")
|
||||
def app_log():
|
||||
text = _tail_file(str(APP_LOG_FILE))
|
||||
return _render_log_lines(text)
|
||||
+17
-1
@@ -4,6 +4,8 @@ webui/api/proxy.py - Nginx proxy domain management API blueprint.
|
||||
Exposed at /api/proxy/* and delegates to lib.nginx.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from lib.nginx import (
|
||||
@@ -17,6 +19,7 @@ from lib.nginx import (
|
||||
update_domain,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("proxy", __name__)
|
||||
|
||||
|
||||
@@ -43,6 +46,7 @@ def list_domains():
|
||||
try:
|
||||
return _ok(get_domains())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list proxy domains: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -65,8 +69,10 @@ def add_domain_bp():
|
||||
add_domain(
|
||||
domain, backend_host, int(backend_port), backend_proto, cert, 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)
|
||||
|
||||
|
||||
@@ -79,6 +85,7 @@ def domain_details(domain):
|
||||
return _error(f"Domain '{domain}' not found", 404)
|
||||
return _ok({"domain": domain, **entry})
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get domain details: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -89,10 +96,12 @@ def update_domain_bp(domain):
|
||||
return _error("Request body must be a JSON object with fields to update", 400)
|
||||
try:
|
||||
update_domain(domain, **body)
|
||||
logger.info("Proxy domain '%s' updated via API", domain)
|
||||
return _ok({"domain": domain})
|
||||
except KeyError as exc:
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to update domain '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -103,8 +112,10 @@ def remove_domain_bp(domain):
|
||||
if domain not in cfg.get("domains", {}):
|
||||
return _error(f"Domain '{domain}' not found", 404)
|
||||
remove_domain(domain)
|
||||
logger.info("Proxy domain removed via API: %s", domain)
|
||||
return _ok({"domain": domain})
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove domain '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -117,8 +128,10 @@ def remove_domain_bp(domain):
|
||||
def apply_bp():
|
||||
try:
|
||||
apply()
|
||||
logger.info("nginx config applied via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to apply nginx config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -128,8 +141,9 @@ def test_bp():
|
||||
valid, output = test_config()
|
||||
if valid:
|
||||
return _ok({"valid": True, "output": output})
|
||||
return jsonify({"ok": False, "error": output, "valid": False}), 400
|
||||
return _error(output, 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("nginx config test failed: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -150,7 +164,9 @@ def management_bp():
|
||||
auth_pass = body.get("auth_pass")
|
||||
try:
|
||||
set_management_proxy(domain, flask_host, int(flask_port), auth_user, 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
|
||||
logger.error("Failed to set management proxy: %s", exc)
|
||||
return _error(str(exc), code)
|
||||
|
||||
+34
-7
@@ -4,6 +4,8 @@ webui/api/wireguard.py - WireGuard tunnel management API blueprint.
|
||||
Exposed at /api/wireguard/* and delegates to lib.wireguard.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from lib.wireguard import (
|
||||
@@ -20,6 +22,7 @@ from lib.wireguard import (
|
||||
status,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("wireguard", __name__)
|
||||
|
||||
|
||||
@@ -51,6 +54,7 @@ def get_config_bp():
|
||||
safe["interface"].pop("private_key", None)
|
||||
return _ok(safe)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to read WireGuard config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -67,6 +71,7 @@ def post_config():
|
||||
safe["interface"].pop("private_key", None)
|
||||
return _ok(safe)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to save WireGuard config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -79,8 +84,21 @@ def post_config():
|
||||
def apply_bp():
|
||||
try:
|
||||
apply()
|
||||
logger.info("WireGuard tunnel applied via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to apply WireGuard config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/up", methods=["POST"])
|
||||
def up_bp():
|
||||
try:
|
||||
apply()
|
||||
logger.info("WireGuard tunnel started via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to start WireGuard tunnel: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -88,8 +106,10 @@ def apply_bp():
|
||||
def down_bp():
|
||||
try:
|
||||
down()
|
||||
logger.info("WireGuard tunnel brought down via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to bring down WireGuard tunnel: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -103,6 +123,7 @@ def status_bp():
|
||||
try:
|
||||
return _ok(status())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get WireGuard status: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -115,8 +136,10 @@ def status_bp():
|
||||
def initialize_bp():
|
||||
try:
|
||||
initialize()
|
||||
logger.info("WireGuard initialized via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to initialize WireGuard: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -125,7 +148,7 @@ def initialize_bp():
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/add-peer", methods=["POST"])
|
||||
@bp.route("/peers", methods=["POST"])
|
||||
def add_peer_bp():
|
||||
body = request.get_json(silent=True) or {}
|
||||
name = body.get("name", "").strip()
|
||||
@@ -141,23 +164,24 @@ def add_peer_bp():
|
||||
)
|
||||
safe = dict(peer)
|
||||
safe.pop("private_key", None)
|
||||
logger.info("WireGuard peer '%s' added via API", name)
|
||||
return _ok(safe)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to add peer '%s': %s", name, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/remove-peer", methods=["DELETE"])
|
||||
def remove_peer_bp():
|
||||
name = request.args.get("name", "").strip()
|
||||
if not name:
|
||||
return _error("Query parameter 'name' is required", 400)
|
||||
@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)
|
||||
logger.info("WireGuard peer '%s' removed via API", name)
|
||||
return _ok({"name": name})
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to remove peer '%s': %s", name, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -166,6 +190,7 @@ def peers_bp():
|
||||
try:
|
||||
return _ok(get_peers())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list WireGuard peers: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -174,6 +199,7 @@ def peer_status_bp():
|
||||
try:
|
||||
return _ok(get_peer_status())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get WireGuard peer status: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -196,12 +222,13 @@ def generate_client_bp():
|
||||
server_pubkey = cfg["interface"].get("public_key", "")
|
||||
if not server_endpoint:
|
||||
_ = cfg["interface"].get("listen_port", 51820)
|
||||
# Can't auto-derive public IP; ask user to provide it
|
||||
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)
|
||||
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
|
||||
logger.error("Failed to generate client config for '%s': %s", name, exc)
|
||||
return _error(str(exc), code)
|
||||
|
||||
Reference in New Issue
Block a user