refactor: unify project structure, improve security, and enhance deployment
- Fix WireGuard private key leak in API responses and config updates - Update systemd service to serve from repo root with adjusted sandbox - Add CLI flags, idempotency, and dev mode to install.sh - Extract common utilities to lib/common.py and webui/api/common.py - Migrate frontend to htmx for simpler, more maintainable UI - Update docs to reflect current architecture and deployment model - Vendor htmx dependencies per project requirements
This commit is contained in:
+22
-44
@@ -1,12 +1,11 @@
|
||||
"""
|
||||
webui/api/certs.py - ACME certificate management API blueprint.
|
||||
"""ACME certificate management API blueprint.
|
||||
|
||||
Exposed at /api/certs/* and delegates to lib.acme.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint, request
|
||||
|
||||
from lib.acme import (
|
||||
get_cert_info,
|
||||
@@ -16,24 +15,12 @@ from lib.acme import (
|
||||
renew,
|
||||
set_email,
|
||||
)
|
||||
from webui.api.common import _error, _ok
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("certs", __name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _error(msg, code=400):
|
||||
return jsonify({"ok": False, "error": msg}), code
|
||||
|
||||
|
||||
def _ok(data=None):
|
||||
return jsonify({"ok": True, "data": data})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Certificate listing
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -43,19 +30,19 @@ def _ok(data=None):
|
||||
def list_certs_bp():
|
||||
try:
|
||||
return _ok(list_certs())
|
||||
except RuntimeError as exc:
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
logger.error("Failed to list certificates: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/<domain>", methods=["GET"])
|
||||
def cert_details(domain):
|
||||
def cert_details(domain: str):
|
||||
try:
|
||||
info = get_cert_info(domain)
|
||||
return _ok(info)
|
||||
except ValueError as exc:
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
logger.error("Failed to get cert info for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
@@ -72,18 +59,14 @@ def issue_bp():
|
||||
if not domain:
|
||||
return _error("'domain' is required", 400)
|
||||
webroot = body.get("webroot")
|
||||
email = body.get("email", "").strip() or None
|
||||
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)
|
||||
issue(domain, webroot=webroot, email=email)
|
||||
logger.info("Certificate issued for '%s'", domain)
|
||||
return _ok(None)
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
logger.error("Failed to issue cert for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -93,19 +76,14 @@ def issue_bp():
|
||||
|
||||
|
||||
@bp.route("/<domain>/renew", methods=["POST"])
|
||||
def renew_bp(domain):
|
||||
def renew_bp(domain: str):
|
||||
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)
|
||||
renew(domain)
|
||||
logger.info("Certificate renewed for '%s'", domain)
|
||||
return _ok(None)
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
logger.error("Failed to renew cert for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@@ -115,19 +93,19 @@ def renew_bp(domain):
|
||||
|
||||
|
||||
@bp.route("/<domain>", methods=["DELETE"])
|
||||
def remove_bp(domain):
|
||||
def remove_bp(domain: str):
|
||||
try:
|
||||
get_cert_info(domain)
|
||||
except ValueError as exc:
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
except (RuntimeError, FileNotFoundError) 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:
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
logger.error("Failed to remove cert '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
@@ -147,6 +125,6 @@ def set_email_bp():
|
||||
set_email(email)
|
||||
logger.info("ACME email set via API: %s", email)
|
||||
return _ok({"email": email})
|
||||
except RuntimeError as exc:
|
||||
except (RuntimeError, FileNotFoundError) as exc:
|
||||
logger.error("Failed to set ACME email: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
+7
-27
@@ -6,8 +6,9 @@ Exposed at /api/dhcp/* and delegates all operations to lib.dnsmasq.
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint, request
|
||||
|
||||
from lib.common import deep_merge
|
||||
from lib.dnsmasq import (
|
||||
add_dns_record,
|
||||
add_static_lease,
|
||||
@@ -20,34 +21,15 @@ from lib.dnsmasq import (
|
||||
save_config,
|
||||
set_dhcp_range,
|
||||
)
|
||||
from lib.dnsmasq import (
|
||||
get_status as dnsmasq_status,
|
||||
)
|
||||
from webui.api.common import _error, _ok
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("dhcp", __name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _error(msg, code=400):
|
||||
return jsonify({"ok": False, "error": msg}), code
|
||||
|
||||
|
||||
def _ok(data=None):
|
||||
return jsonify({"ok": True, "data": data})
|
||||
|
||||
|
||||
def _deep_merge(base, overrides):
|
||||
result = dict(base)
|
||||
for k, v in overrides.items():
|
||||
if k in result and isinstance(result[k], dict) and isinstance(v, dict):
|
||||
result[k] = _deep_merge(result[k], v)
|
||||
else:
|
||||
result[k] = v
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -82,7 +64,7 @@ def patch_config():
|
||||
return _error("Request body must be a JSON object", 400)
|
||||
try:
|
||||
current = get_config()
|
||||
merged = _deep_merge(current, body)
|
||||
merged = deep_merge(current, body)
|
||||
save_config(merged)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
@@ -109,8 +91,6 @@ def apply_bp():
|
||||
@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)
|
||||
|
||||
+51
-46
@@ -1,74 +1,63 @@
|
||||
"""
|
||||
webui/api/firewall.py - Firewall (firewalld) management API blueprint.
|
||||
"""Firewall (firewalld) management API blueprint.
|
||||
|
||||
Exposed at /api/firewall/* and delegates all mutations to lib.firewall.
|
||||
Exposed at /api/firewall/* and delegates all mutations to lib.firewall.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint, request
|
||||
|
||||
from lib.common import deep_merge
|
||||
from lib.firewall import (
|
||||
add_forward_port,
|
||||
add_rich_rule,
|
||||
config_get,
|
||||
config_apply,
|
||||
config_pending,
|
||||
config_set,
|
||||
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 webui.api.common import _error, _ok
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("firewall", __name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Error helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _error(msg, code=400):
|
||||
return jsonify({"ok": False, "error": msg}), code
|
||||
|
||||
|
||||
def _ok(data=None):
|
||||
return jsonify({"ok": True, "data": data})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Declarative config (two-step: save -> apply)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/config", methods=["GET"])
|
||||
def config_get_bp():
|
||||
def config_list():
|
||||
try:
|
||||
return _ok(config_get())
|
||||
except Exception as exc:
|
||||
return _ok(get_config())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to read firewall config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/config", methods=["POST"])
|
||||
def config_set_bp():
|
||||
def config_save():
|
||||
body = request.get_json(silent=True) or {}
|
||||
if "zones" not in body:
|
||||
return _error("'zones' key is required", 400)
|
||||
if not isinstance(body["zones"], dict):
|
||||
return _error("'zones' must be a dict", 400)
|
||||
try:
|
||||
config_set(body)
|
||||
save_config(body)
|
||||
pending_info = config_pending()
|
||||
logger.info("Firewall config saved (%d zones)", len(body["zones"]))
|
||||
return _ok(
|
||||
@@ -79,20 +68,42 @@ def config_set_bp():
|
||||
"unmanaged_zones": pending_info.get("unmanaged_zones", {}),
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to save firewall config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/config", methods=["PATCH"])
|
||||
def patch_config():
|
||||
body = request.get_json(silent=True) or {}
|
||||
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()))
|
||||
return _ok(
|
||||
{
|
||||
"config_saved": True,
|
||||
"pending": pending_info["pending"],
|
||||
"needs_apply": pending_info["needs_apply"],
|
||||
"unmanaged_zones": pending_info.get("unmanaged_zones", {}),
|
||||
}
|
||||
)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to patch firewall config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/config/apply", methods=["POST"])
|
||||
def config_apply_bp():
|
||||
try:
|
||||
from lib.firewall import config_apply as _config_apply
|
||||
|
||||
result = _config_apply()
|
||||
result = config_apply()
|
||||
logger.info("Firewall config applied: %s", result.get("applied_zones", []))
|
||||
return _ok(result)
|
||||
except Exception as exc:
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to apply firewall config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
@@ -101,7 +112,7 @@ def config_apply_bp():
|
||||
def config_pending_bp():
|
||||
try:
|
||||
return _ok(config_pending())
|
||||
except Exception as exc:
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to check pending config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
@@ -123,7 +134,7 @@ def list_zones():
|
||||
|
||||
|
||||
@bp.route("/zones/<name>", methods=["GET"])
|
||||
def zone_details(name):
|
||||
def zone_details(name: str):
|
||||
try:
|
||||
if name not in get_available_zones():
|
||||
return _error(f"Zone '{name}' does not exist", 404)
|
||||
@@ -153,7 +164,7 @@ def create_zone_bp():
|
||||
|
||||
|
||||
@bp.route("/zones/<name>", methods=["DELETE"])
|
||||
def delete_zone_bp(name):
|
||||
def delete_zone_bp(name: str):
|
||||
try:
|
||||
available = get_available_zones()
|
||||
if name not in available:
|
||||
@@ -172,7 +183,7 @@ def delete_zone_bp(name):
|
||||
|
||||
|
||||
@bp.route("/zones/<name>/interfaces", methods=["POST"])
|
||||
def set_zone_interfaces_bp(name):
|
||||
def set_zone_interfaces_bp(name: str):
|
||||
body = request.get_json(silent=True) or {}
|
||||
interfaces = body.get("interfaces", [])
|
||||
if not isinstance(interfaces, list):
|
||||
@@ -192,7 +203,7 @@ def set_zone_interfaces_bp(name):
|
||||
|
||||
|
||||
@bp.route("/zones/<name>/services", methods=["POST"])
|
||||
def set_zone_services_bp(name):
|
||||
def set_zone_services_bp(name: str):
|
||||
body = request.get_json(silent=True) or {}
|
||||
services = body.get("services", [])
|
||||
if not isinstance(services, list):
|
||||
@@ -250,18 +261,14 @@ def add_rich_rule_bp():
|
||||
|
||||
|
||||
@bp.route("/rich-rules/<zone>", methods=["GET"])
|
||||
def list_rich_rules(zone):
|
||||
def list_rich_rules(zone: str):
|
||||
try:
|
||||
rules = get_rich_rules(zone)
|
||||
from lib.firewall import config_get as firewall_config_get
|
||||
|
||||
cfg = firewall_config_get()
|
||||
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
|
||||
)
|
||||
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:
|
||||
@@ -273,7 +280,7 @@ def list_rich_rules(zone):
|
||||
|
||||
|
||||
@bp.route("/rich-rules/<zone>/<rule_id>", methods=["DELETE"])
|
||||
def remove_rich_rule_bp(zone, rule_id):
|
||||
def remove_rich_rule_bp(zone: str, rule_id: str):
|
||||
try:
|
||||
remove_rich_rule_by_id(zone, rule_id)
|
||||
logger.info("Rich rule '%s' removed from zone '%s'", rule_id, zone)
|
||||
@@ -333,9 +340,7 @@ def add_forward_port_bp():
|
||||
toaddr=str(toaddr) if toaddr else None,
|
||||
toport=int(toport) if toport else None,
|
||||
)
|
||||
return _ok(
|
||||
{"zone": zone, "id": entry["id"], "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)
|
||||
@@ -343,7 +348,7 @@ def add_forward_port_bp():
|
||||
|
||||
|
||||
@bp.route("/forward-port/<zone>/<int:port>/<proto>", methods=["DELETE"])
|
||||
def remove_forward_port_bp(zone, port, proto):
|
||||
def remove_forward_port_bp(zone: str, port: int, proto: str):
|
||||
try:
|
||||
remove_forward_port_by_id(zone, port, proto)
|
||||
logger.info("Forward port %s/%s removed from zone '%s'", port, proto, zone)
|
||||
|
||||
+53
-6
@@ -6,34 +6,81 @@ Exposed at /api/proxy/* and delegates to lib.nginx.
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
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 webui.api.common import _error, _ok
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
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()
|
||||
logger.info("SSL snippet written via API")
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to write SSL snippet: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# Config (declarative)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _error(msg, code=400):
|
||||
return jsonify({"ok": False, "error": msg}), code
|
||||
@bp.route("/config", methods=["GET"])
|
||||
def get_config_bp():
|
||||
try:
|
||||
return _ok(get_config())
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to read proxy config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
def _ok(data=None):
|
||||
return jsonify({"ok": True, "data": data})
|
||||
@bp.route("/config", methods=["POST"])
|
||||
def post_config():
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
return _error("Request body must be a JSON object", 400)
|
||||
try:
|
||||
save_config(body)
|
||||
logger.info("Proxy config saved: %s", sorted(body.keys()))
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to save proxy config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/config", methods=["PATCH"])
|
||||
def patch_config():
|
||||
body = request.get_json(silent=True) or {}
|
||||
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)
|
||||
logger.info("Proxy config patched: %s", sorted(body.keys()))
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to patch proxy config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -53,9 +53,17 @@ 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["interface"] = dict(body["interface"])
|
||||
body["interface"].pop("private_key", None)
|
||||
|
||||
if current_key:
|
||||
body.setdefault("interface", {})["private_key"] = current_key
|
||||
|
||||
save_config(body)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
|
||||
Reference in New Issue
Block a user