refactor: daemon collectors, thin webui proxies, pure config reads
- move state collectors from lib/state.py to daemon/collectors/ (7 modules, registration side-effect; daemon/server.py imports the package before the first populate()) - webui/api: new daemon_route() decorator factory in common.py collapses the try/except daemon-proxy boilerplate in all 8 blueprints (rules/params/body/transform keep responses identical) - firewall: interface-coverage invariant — config is the source of truth for zone interfaces (absent key = empty, no hands-off zones); pure validate_coverage() enforced at save (400) and apply (409, force: true overrides), top-level `unmanaged` exemption - lib: get_config() reads are now pure (no dir creation or writes); new lib/bootstrap.py creates runtime dirs and persists the one-shot nginx legacy migration at daemon start, after system_import (lib.nginx.migrate_config_file) - lib/common: compute_pending() apply-bookkeeping helper - daemon: emit_and_refresh() handler helper; refresh_state(bump=) so /status/refresh no longer bumps versions (poll/mutation only) - acme: move --log last so acme.sh never treats a real arg as the log-file argument - docs: AGENTS.md, config.md, state-model.md, api.md updated; HARDEN.md dropped (plan implemented); apply-confirm force wording Tests: 917 passed; ruff check + format clean.
This commit is contained in:
+215
-436
@@ -3,11 +3,16 @@
|
||||
Exposed at /api/wireguard/* and delegates to vacuum-walld.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, request
|
||||
from flask import Blueprint
|
||||
|
||||
from daemon.client import BadRequest, Conflict, NotFound, delete, get, patch, post
|
||||
from daemon.client import ( # noqa: F401 (resolved via module globals)
|
||||
delete,
|
||||
get,
|
||||
patch,
|
||||
post,
|
||||
)
|
||||
from daemon.iface import (
|
||||
DELETE_WIREGUARD_CLASSES,
|
||||
DELETE_WIREGUARD_CLASSES_DOWN,
|
||||
@@ -30,473 +35,247 @@ from daemon.iface import (
|
||||
POST_WIREGUARD_INITIALIZE,
|
||||
POST_WIREGUARD_PEERS_ADD,
|
||||
)
|
||||
from webui.api.common import _error, _ok
|
||||
from webui.api.common import NO_BODY, daemon_route, require_dict_body, void_transform
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("wireguard", __name__)
|
||||
|
||||
|
||||
@bp.route("/config", methods=["GET"])
|
||||
def get_config_bp():
|
||||
"""Get the current WireGuard configuration.
|
||||
|
||||
Endpoint: GET /api/wireguard/config
|
||||
|
||||
Returns:
|
||||
JSON response with the WireGuard config on success, or an error
|
||||
response on failure.
|
||||
"""
|
||||
try:
|
||||
return _ok(get(GET_WIREGUARD_CONFIG))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to read WireGuard config: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Body builders / prechecks / transforms
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.route("/config", methods=["POST"])
|
||||
def post_config():
|
||||
"""Create or fully replace the WireGuard configuration.
|
||||
|
||||
Endpoint: POST /api/wireguard/config
|
||||
|
||||
Args:
|
||||
body: JSON body with the configuration. If an ``interface`` key
|
||||
is present, the private key will be stripped before forwarding.
|
||||
|
||||
Returns:
|
||||
Success response on acceptance, 400 on validation failure, or 500
|
||||
on server error.
|
||||
"""
|
||||
def _wg_config_body(request: Any, _va: Any) -> dict[str, Any]:
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
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)
|
||||
post(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)
|
||||
if "interface" in body:
|
||||
body = dict(body)
|
||||
body["interface"] = dict(body["interface"])
|
||||
body["interface"].pop("private_key", None)
|
||||
return body
|
||||
|
||||
|
||||
@bp.route("/config", methods=["PATCH"])
|
||||
def patch_config():
|
||||
"""Partially update the WireGuard configuration.
|
||||
|
||||
Endpoint: PATCH /api/wireguard/config
|
||||
|
||||
Args:
|
||||
body: JSON body with the fields to update. If an ``interface``
|
||||
key is present, the private key will be stripped before forwarding.
|
||||
|
||||
Returns:
|
||||
Success response on acceptance, 400 on validation failure, or 500
|
||||
on server error.
|
||||
"""
|
||||
def _add_peer_body(request: Any, _va: Any) -> dict[str, Any]:
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
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)
|
||||
patch(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)
|
||||
|
||||
|
||||
@bp.route("/apply", methods=["POST"])
|
||||
def apply_bp():
|
||||
"""Apply the current WireGuard configuration to the live tunnel.
|
||||
|
||||
Endpoint: POST /api/wireguard/apply
|
||||
|
||||
Returns:
|
||||
Success response on acceptance, or 500 on server error.
|
||||
"""
|
||||
try:
|
||||
post(POST_WIREGUARD_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():
|
||||
"""Bring the WireGuard tunnel interface up.
|
||||
|
||||
Endpoint: POST /api/wireguard/up
|
||||
|
||||
Returns:
|
||||
Success response on acceptance, or 500 on server error.
|
||||
"""
|
||||
try:
|
||||
post(POST_WIREGUARD_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)
|
||||
|
||||
|
||||
@bp.route("/down", methods=["POST"])
|
||||
def down_bp():
|
||||
"""Bring the WireGuard tunnel interface down.
|
||||
|
||||
Endpoint: POST /api/wireguard/down
|
||||
|
||||
Returns:
|
||||
Success response on acceptance, or 500 on server error.
|
||||
"""
|
||||
try:
|
||||
post(POST_WIREGUARD_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)
|
||||
|
||||
|
||||
@bp.route("/status", methods=["GET"])
|
||||
def status_bp():
|
||||
"""Get the current WireGuard tunnel status.
|
||||
|
||||
Endpoint: GET /api/wireguard/status
|
||||
|
||||
Returns:
|
||||
JSON response with the tunnel status on success, or an error
|
||||
response on failure.
|
||||
"""
|
||||
try:
|
||||
return _ok(get(GET_WIREGUARD_STATUS))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get WireGuard status: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/initialize", methods=["POST"])
|
||||
def initialize_bp():
|
||||
"""Initialize WireGuard for first-time use.
|
||||
|
||||
Endpoint: POST /api/wireguard/initialize
|
||||
|
||||
Returns:
|
||||
Success response on acceptance, or 500 on server error.
|
||||
"""
|
||||
try:
|
||||
post(POST_WIREGUARD_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)
|
||||
|
||||
|
||||
@bp.route("/peers", methods=["POST"])
|
||||
def add_peer_bp():
|
||||
"""Add a new peer to the WireGuard configuration.
|
||||
|
||||
Endpoint: POST /api/wireguard/peers
|
||||
|
||||
Args:
|
||||
name: Peer display name (required).
|
||||
endpoint: Optional peer endpoint address.
|
||||
allowed_ips: Optional list of allowed IP CIDRs.
|
||||
persistent_keepalive: Optional keepalive interval in seconds.
|
||||
preshared_key: Optional pre-shared key in hex.
|
||||
|
||||
Returns:
|
||||
JSON response with the created peer on success, 400 on validation
|
||||
failure, or 500 on server error.
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
name = body.get("name", "").strip()
|
||||
name = (body.get("name") or "").strip()
|
||||
if not name:
|
||||
return _error("'name' is required", 400)
|
||||
try:
|
||||
peer = post(
|
||||
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"),
|
||||
"description": body.get("description"),
|
||||
"access_class": body.get("access_class"),
|
||||
},
|
||||
)
|
||||
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)
|
||||
raise ValueError("'name' is required")
|
||||
return {
|
||||
"name": name,
|
||||
"endpoint": body.get("endpoint"),
|
||||
"allowed_ips": body.get("allowed_ips", []),
|
||||
"persistent_keepalive": body.get("persistent_keepalive"),
|
||||
"preshared_key": body.get("preshared_key"),
|
||||
"description": body.get("description"),
|
||||
"access_class": body.get("access_class"),
|
||||
}
|
||||
|
||||
|
||||
@bp.route("/peers/<name>", methods=["DELETE"])
|
||||
def remove_peer_bp(name):
|
||||
"""Remove a peer from the WireGuard configuration.
|
||||
|
||||
Endpoint: DELETE /api/wireguard/peers/<name>
|
||||
|
||||
Args:
|
||||
name: Peer name to remove (from URL path).
|
||||
|
||||
Returns:
|
||||
Success response with peer name on removal, 404 if peer not found,
|
||||
or 500 on server error.
|
||||
"""
|
||||
try:
|
||||
delete(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)
|
||||
|
||||
|
||||
@bp.route("/peers", methods=["GET"])
|
||||
def peers_bp():
|
||||
"""List all configured WireGuard peers.
|
||||
|
||||
Endpoint: GET /api/wireguard/peers
|
||||
|
||||
Returns:
|
||||
JSON response with the peers list on success, or an error response
|
||||
on failure.
|
||||
"""
|
||||
try:
|
||||
return _ok(get(GET_WIREGUARD_PEERS))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list WireGuard peers: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/peer-status", methods=["GET"])
|
||||
def peer_status_bp():
|
||||
"""Get real-time status information for all WireGuard peers.
|
||||
|
||||
Endpoint: GET /api/wireguard/peer-status
|
||||
|
||||
Returns:
|
||||
JSON response with peer status on success, or an error response
|
||||
on failure.
|
||||
"""
|
||||
try:
|
||||
return _ok(get(GET_WIREGUARD_PEER_STATUS))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get WireGuard peer status: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/generate-client", methods=["POST"])
|
||||
def generate_client_bp():
|
||||
"""Generate a WireGuard client configuration file for a peer.
|
||||
|
||||
Endpoint: POST /api/wireguard/generate-client
|
||||
|
||||
Args:
|
||||
name: Peer name (required).
|
||||
server_endpoint: Server endpoint address for the client config (required).
|
||||
|
||||
Returns:
|
||||
JSON response with the generated config string on success, 404 if
|
||||
peer not found, 400 on validation failure, or 500 on server error.
|
||||
"""
|
||||
def _gen_client_body(request: Any, _va: Any) -> dict[str, Any]:
|
||||
body = request.get_json(silent=True) or {}
|
||||
name = body.get("name", "").strip()
|
||||
name = (body.get("name") or "").strip()
|
||||
if not name:
|
||||
return _error("Field 'name' is required", 400)
|
||||
raise ValueError("Field 'name' is required")
|
||||
server_endpoint = body.get("server_endpoint", "")
|
||||
if not server_endpoint:
|
||||
return _error("Field 'server_endpoint' is required", 400)
|
||||
try:
|
||||
result = post(
|
||||
POST_WIREGUARD_GENERATE_CLIENT,
|
||||
{
|
||||
"name": name,
|
||||
"server_endpoint": server_endpoint,
|
||||
},
|
||||
)
|
||||
logger.info("Client config generated for peer '%s' via API", name)
|
||||
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), 500)
|
||||
raise ValueError("Field 'server_endpoint' is required")
|
||||
return {"name": name, "server_endpoint": server_endpoint}
|
||||
|
||||
|
||||
@bp.route("/classes", methods=["GET"])
|
||||
def _delete_class_body(request: Any, _va: Any) -> dict[str, Any]:
|
||||
body = request.get_json(silent=True) or {}
|
||||
key = (body.get("key") or "").strip()
|
||||
if not key:
|
||||
raise ValueError("'key' is required")
|
||||
return {"key": key}
|
||||
|
||||
|
||||
def _class_key_precheck(json: Any, va: dict[str, Any]) -> None:
|
||||
require_dict_body(json, va)
|
||||
if not ((json or {}).get("key") or "").strip():
|
||||
raise ValueError("'key' is required")
|
||||
|
||||
|
||||
def _peer_name_echo(_data: Any, _va: Any, sent: Any) -> Any:
|
||||
return {"name": sent["name"]}
|
||||
|
||||
|
||||
def _config_echo(data: Any, _va: Any, _sent: Any) -> Any:
|
||||
return {"config": data.get("config", "")}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@daemon_route(GET_WIREGUARD_CONFIG, bp)
|
||||
def get_config_bp():
|
||||
"""GET /api/wireguard/config — Get the current WireGuard configuration."""
|
||||
|
||||
|
||||
@daemon_route(
|
||||
POST_WIREGUARD_CONFIG,
|
||||
bp,
|
||||
precheck=require_dict_body,
|
||||
body=_wg_config_body,
|
||||
transform=void_transform,
|
||||
)
|
||||
def post_config():
|
||||
"""POST /api/wireguard/config — Create or fully replace the configuration."""
|
||||
|
||||
|
||||
@daemon_route(
|
||||
PATCH_WIREGUARD_CONFIG,
|
||||
bp,
|
||||
precheck=require_dict_body,
|
||||
body=_wg_config_body,
|
||||
transform=void_transform,
|
||||
)
|
||||
def patch_config():
|
||||
"""PATCH /api/wireguard/config — Partially update the configuration."""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tunnel control
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@daemon_route(POST_WIREGUARD_APPLY, bp, body=NO_BODY, transform=void_transform)
|
||||
def apply_bp():
|
||||
"""POST /api/wireguard/apply — Apply the current configuration to the tunnel."""
|
||||
|
||||
|
||||
@daemon_route(
|
||||
POST_WIREGUARD_APPLY, bp, rule="/up", body=NO_BODY, transform=void_transform
|
||||
)
|
||||
def up_bp():
|
||||
"""POST /api/wireguard/up — Bring the WireGuard tunnel interface up."""
|
||||
|
||||
|
||||
@daemon_route(POST_WIREGUARD_DOWN, bp, body=NO_BODY, transform=void_transform)
|
||||
def down_bp():
|
||||
"""POST /api/wireguard/down — Bring the WireGuard tunnel interface down."""
|
||||
|
||||
|
||||
@daemon_route(GET_WIREGUARD_STATUS, bp)
|
||||
def status_bp():
|
||||
"""GET /api/wireguard/status — Get the current WireGuard tunnel status."""
|
||||
|
||||
|
||||
@daemon_route(POST_WIREGUARD_INITIALIZE, bp, body=NO_BODY, transform=void_transform)
|
||||
def initialize_bp():
|
||||
"""POST /api/wireguard/initialize — Initialize WireGuard for first-time use."""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Peers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@daemon_route(POST_WIREGUARD_PEERS_ADD, bp, rule="/peers", body=_add_peer_body)
|
||||
def add_peer_bp():
|
||||
"""POST /api/wireguard/peers — Add a new peer to the configuration."""
|
||||
|
||||
|
||||
@daemon_route(
|
||||
DELETE_WIREGUARD_PEERS_REMOVE, bp, rule="/peers/<name>", transform=_peer_name_echo
|
||||
)
|
||||
def remove_peer_bp():
|
||||
"""DELETE /api/wireguard/peers/<name> — Remove a peer from the configuration."""
|
||||
|
||||
|
||||
@daemon_route(GET_WIREGUARD_PEERS, bp)
|
||||
def peers_bp():
|
||||
"""GET /api/wireguard/peers — List all configured WireGuard peers."""
|
||||
|
||||
|
||||
@daemon_route(GET_WIREGUARD_PEER_STATUS, bp)
|
||||
def peer_status_bp():
|
||||
"""GET /api/wireguard/peer-status — Get real-time status for all peers."""
|
||||
|
||||
|
||||
@daemon_route(
|
||||
POST_WIREGUARD_GENERATE_CLIENT, bp, body=_gen_client_body, transform=_config_echo
|
||||
)
|
||||
def generate_client_bp():
|
||||
"""POST /api/wireguard/generate-client — Generate a client config for a peer."""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Access classes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@daemon_route(GET_WIREGUARD_CLASSES, bp)
|
||||
def list_classes_bp():
|
||||
"""List all access classes.
|
||||
|
||||
Endpoint: GET /api/wireguard/classes
|
||||
"""
|
||||
try:
|
||||
return _ok(get(GET_WIREGUARD_CLASSES))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list access classes: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
"""GET /api/wireguard/classes — List all access classes."""
|
||||
|
||||
|
||||
@bp.route("/classes", methods=["POST"])
|
||||
@daemon_route(POST_WIREGUARD_CLASSES, bp, precheck=_class_key_precheck)
|
||||
def create_class_bp():
|
||||
"""Create a new access class.
|
||||
|
||||
Endpoint: POST /api/wireguard/classes
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
return _error("Request body must be a JSON object", 400)
|
||||
key = body.get("key", "").strip()
|
||||
if not key:
|
||||
return _error("'key' is required", 400)
|
||||
try:
|
||||
result = post(POST_WIREGUARD_CLASSES, body)
|
||||
return _ok(result)
|
||||
except BadRequest as exc:
|
||||
logger.info("Create access class rejected: %s", exc)
|
||||
return _error(str(exc), 400)
|
||||
except Conflict as exc:
|
||||
logger.info("Create access class conflict: %s", exc)
|
||||
return _error(str(exc), 409)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to create access class: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
"""POST /api/wireguard/classes — Create a new access class."""
|
||||
|
||||
|
||||
@bp.route("/classes", methods=["PATCH"])
|
||||
@daemon_route(
|
||||
PATCH_WIREGUARD_CLASSES, bp, rule="/classes", precheck=_class_key_precheck
|
||||
)
|
||||
def update_class_bp():
|
||||
"""Update an access class.
|
||||
|
||||
Endpoint: PATCH /api/wireguard/classes
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
return _error("Request body must be a JSON object", 400)
|
||||
key = body.get("key", "").strip()
|
||||
if not key:
|
||||
return _error("'key' is required", 400)
|
||||
try:
|
||||
result = patch(PATCH_WIREGUARD_CLASSES, body)
|
||||
return _ok(result)
|
||||
except BadRequest as exc:
|
||||
logger.info("Update access class rejected: %s", exc)
|
||||
return _error(str(exc), 400)
|
||||
except NotFound as exc:
|
||||
logger.info("Access class not found: %s", exc)
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to update access class: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
"""PATCH /api/wireguard/classes — Update an access class."""
|
||||
|
||||
|
||||
@bp.route("/classes", methods=["DELETE"])
|
||||
@daemon_route(
|
||||
DELETE_WIREGUARD_CLASSES,
|
||||
bp,
|
||||
rule="/classes",
|
||||
precheck=require_dict_body,
|
||||
body=_delete_class_body,
|
||||
)
|
||||
def delete_class_bp():
|
||||
"""Delete an access class.
|
||||
|
||||
Endpoint: DELETE /api/wireguard/classes
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
return _error("Request body must be a JSON object", 400)
|
||||
key = body.get("key", "").strip()
|
||||
if not key:
|
||||
return _error("'key' is required", 400)
|
||||
try:
|
||||
result = delete(DELETE_WIREGUARD_CLASSES, {"key": key})
|
||||
logger.info("Access class '%s' deleted via API", key)
|
||||
return _ok(result)
|
||||
except NotFound as exc:
|
||||
logger.info("Access class not found: %s", exc)
|
||||
return _error(str(exc), 404)
|
||||
except Conflict as exc:
|
||||
logger.info("Delete access class conflict: %s", exc)
|
||||
return _error(str(exc), 409)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to delete access class: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
"""DELETE /api/wireguard/classes — Delete an access class."""
|
||||
|
||||
|
||||
@bp.route("/classes/<key>/up", methods=["POST"])
|
||||
def class_up_bp(key):
|
||||
"""Bring up a single access class's WireGuard tunnel.
|
||||
|
||||
Endpoint: POST /api/wireguard/classes/<key>/up
|
||||
"""
|
||||
try:
|
||||
post(POST_WIREGUARD_CLASSES_UP, {"class_key": key})
|
||||
logger.info("WireGuard class '%s' tunnel brought up via API", key)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to bring up class '%s': %s", key, exc)
|
||||
return _error(str(exc), 500)
|
||||
@daemon_route(
|
||||
POST_WIREGUARD_CLASSES_UP,
|
||||
bp,
|
||||
rule="/classes/<key>/up",
|
||||
params={"class_key": "key"},
|
||||
body={},
|
||||
transform=void_transform,
|
||||
)
|
||||
def class_up_bp():
|
||||
"""POST /api/wireguard/classes/<key>/up — Bring up a class's tunnel."""
|
||||
|
||||
|
||||
@bp.route("/classes/<key>/down", methods=["POST"])
|
||||
def class_down_bp(key):
|
||||
"""Bring down a single access class's WireGuard tunnel.
|
||||
|
||||
Endpoint: POST /api/wireguard/classes/<key>/down
|
||||
"""
|
||||
try:
|
||||
delete(DELETE_WIREGUARD_CLASSES_DOWN, {"class_key": key})
|
||||
logger.info("WireGuard class '%s' tunnel brought down via API", key)
|
||||
return _ok(None)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to bring down class '%s': %s", key, exc)
|
||||
return _error(str(exc), 500)
|
||||
@daemon_route(
|
||||
DELETE_WIREGUARD_CLASSES_DOWN,
|
||||
bp,
|
||||
rule="/classes/<key>/down",
|
||||
methods=["POST"],
|
||||
params={"class_key": "key"},
|
||||
body={},
|
||||
transform=void_transform,
|
||||
)
|
||||
def class_down_bp():
|
||||
"""POST /api/wireguard/classes/<key>/down — Bring down a class's tunnel."""
|
||||
|
||||
|
||||
@bp.route("/classes/<key>/status", methods=["GET"])
|
||||
def class_status_bp(key):
|
||||
"""Get status for a single access class's tunnel.
|
||||
|
||||
Endpoint: GET /api/wireguard/classes/<key>/status
|
||||
"""
|
||||
try:
|
||||
return _ok(get(GET_WIREGUARD_CLASS_STATUS, {"class_key": key}))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get class '%s' status: %s", key, exc)
|
||||
return _error(str(exc), 500)
|
||||
@daemon_route(
|
||||
GET_WIREGUARD_CLASS_STATUS,
|
||||
bp,
|
||||
rule="/classes/<key>/status",
|
||||
params={"class_key": "key"},
|
||||
)
|
||||
def class_status_bp():
|
||||
"""GET /api/wireguard/classes/<key>/status — Get status for a class's tunnel."""
|
||||
|
||||
|
||||
@bp.route("/classes/keys/<key>", methods=["POST"])
|
||||
def class_init_keys_bp(key):
|
||||
"""Generate key pair for a single access class.
|
||||
|
||||
Endpoint: POST /api/wireguard/classes/keys/<key>
|
||||
"""
|
||||
try:
|
||||
post(POST_WIREGUARD_CLASS_INIT_KEYS, {"class_key": key})
|
||||
logger.info("WireGuard class '%s' keys generated via API", key)
|
||||
return _ok(None)
|
||||
except NotFound as exc:
|
||||
logger.info("Class '%s' not found for keys: %s", key, exc)
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to generate keys for class '%s': %s", key, exc)
|
||||
return _error(str(exc), 500)
|
||||
@daemon_route(
|
||||
POST_WIREGUARD_CLASS_INIT_KEYS,
|
||||
bp,
|
||||
rule="/classes/keys/<key>",
|
||||
params={"class_key": "key"},
|
||||
body={},
|
||||
transform=void_transform,
|
||||
)
|
||||
def class_init_keys_bp():
|
||||
"""POST /api/wireguard/classes/keys/<key> — Generate keys for a class."""
|
||||
|
||||
Reference in New Issue
Block a user