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:
+75
-239
@@ -3,11 +3,11 @@
|
||||
Exposed at /api/certs/* 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, post
|
||||
from daemon.client import delete, get, post # noqa: F401 (resolved via module globals)
|
||||
from daemon.iface import (
|
||||
DELETE_ACME_ACCOUNT_DEACTIVATE,
|
||||
DELETE_ACME_REMOVE,
|
||||
@@ -22,269 +22,105 @@ from daemon.iface import (
|
||||
POST_ACME_RENEW,
|
||||
POST_ACME_VALIDATE,
|
||||
)
|
||||
from webui.api.common import _error, _ok
|
||||
from webui.api.common import NO_BODY, daemon_route, void_transform
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
bp = Blueprint("certs", __name__)
|
||||
|
||||
|
||||
@bp.route("/list", methods=["GET"])
|
||||
def list_certs_bp():
|
||||
"""GET /api/certs/list — list all managed ACME certificates.
|
||||
|
||||
Returns:
|
||||
Response containing the list of certificates or an error message.
|
||||
"""
|
||||
try:
|
||||
return _ok(get(GET_ACME_LIST))
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to list certificates: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
def _validate_body(request: Any, _va: Any) -> dict[str, Any]:
|
||||
domain = ((request.get_json(silent=True) or {}).get("domain") or "").strip()
|
||||
if not domain:
|
||||
raise ValueError("'domain' is required")
|
||||
return {"domain": domain}
|
||||
|
||||
|
||||
@bp.route("/<domain>", methods=["GET"])
|
||||
def cert_details(domain: str):
|
||||
"""GET /api/certs/<domain> — get details for a specific certificate.
|
||||
|
||||
Args:
|
||||
domain: Domain name to look up.
|
||||
|
||||
Returns:
|
||||
Response containing certificate info or an error message.
|
||||
"""
|
||||
try:
|
||||
return _ok(get(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 as exc:
|
||||
logger.error("Failed to get cert info for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/validate", methods=["POST"])
|
||||
def validate():
|
||||
"""POST /api/certs/validate — run pre-flight checks for certificate issuance.
|
||||
|
||||
Expects JSON body with ``{``domain``}``.
|
||||
|
||||
Returns:
|
||||
Response containing validation results or an error message.
|
||||
"""
|
||||
def _issue_body(request: Any, _va: Any) -> dict[str, Any]:
|
||||
body = request.get_json(silent=True) or {}
|
||||
domain = (body.get("domain") or "").strip()
|
||||
if not domain:
|
||||
return _error("'domain' is required", 400)
|
||||
try:
|
||||
result = post(POST_ACME_VALIDATE, {"domain": domain})
|
||||
return _ok(result)
|
||||
except BadRequest as exc:
|
||||
logger.info("Validation rejected: %s", exc)
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to validate cert for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
|
||||
|
||||
@bp.route("/issue/start", methods=["POST"])
|
||||
def issue_start():
|
||||
"""POST /api/certs/issue/start — create a new certificate issuance request.
|
||||
|
||||
Expects JSON body with ``{``domain``}``; optional ``email`` and ``webroot``.
|
||||
|
||||
Returns:
|
||||
Response containing an issuance request ID or an error message.
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
domain = (body.get("domain") or "").strip()
|
||||
if not domain:
|
||||
return _error("'domain' is required", 400)
|
||||
raise ValueError("'domain' is required")
|
||||
email = (body.get("email") or "").strip() or None
|
||||
webroot = body.get("webroot")
|
||||
try:
|
||||
logger.info("Certificate issuance requested for '%s' via API", domain)
|
||||
result = post(
|
||||
POST_ACME_ISSUE, {"domain": domain, "webroot": webroot, "email": email}
|
||||
)
|
||||
logger.info(
|
||||
"Certificate issuance started for '%s' (id=%s)",
|
||||
domain,
|
||||
result.get("request_id"),
|
||||
)
|
||||
return _ok(result)
|
||||
except BadRequest as exc:
|
||||
logger.info("Cert issue for '%s' rejected: %s", domain, exc)
|
||||
return _error(str(exc), 400)
|
||||
except Conflict as exc:
|
||||
return _error(str(exc), 409)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to start cert issue for '%s': %s", domain, exc)
|
||||
return _error(str(exc), 500)
|
||||
return {"domain": domain, "webroot": body.get("webroot"), "email": email}
|
||||
|
||||
|
||||
@bp.route("/issue/<request_id>", methods=["GET"])
|
||||
def issue_status(request_id: str):
|
||||
"""GET /api/certs/issue/<request_id> — poll status of a certificate issuance request.
|
||||
|
||||
Args:
|
||||
request_id: Issuance request identifier returned by issue_start.
|
||||
|
||||
Returns:
|
||||
Response containing issuance status or an error message.
|
||||
"""
|
||||
try:
|
||||
result = get(GET_ACME_ISSUE_STATUS, {"id": request_id})
|
||||
return _ok(result)
|
||||
except NotFound as exc:
|
||||
logger.info("Issuance request '%s' not found: %s", request_id, exc)
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get issuance status for '%s': %s", request_id, exc)
|
||||
return _error(str(exc), 500)
|
||||
def _email_body(request: Any, _va: Any) -> dict[str, Any]:
|
||||
email = ((request.get_json(silent=True) or {}).get("email") or "").strip()
|
||||
if not email:
|
||||
raise ValueError("'email' is required")
|
||||
return {"email": email}
|
||||
|
||||
|
||||
@bp.route("/<domain>/renew", methods=["POST"])
|
||||
def renew_bp(domain: str):
|
||||
"""POST /api/certs/<domain>/renew — start an (async) certificate renewal.
|
||||
|
||||
Returns:
|
||||
Response containing a renewal request ID (poll it at
|
||||
``/api/certs/renew/<request_id>``) or an error message.
|
||||
"""
|
||||
try:
|
||||
logger.info("Certificate renewal requested for '%s' via API", domain)
|
||||
result = post(POST_ACME_RENEW, {"domain": domain})
|
||||
logger.info(
|
||||
"Certificate renewal started for '%s' (id=%s)",
|
||||
domain,
|
||||
result.get("request_id"),
|
||||
)
|
||||
return _ok(result)
|
||||
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)
|
||||
def _register_body(request: Any, _va: Any) -> dict[str, Any]:
|
||||
body = request.get_json(silent=True) or {}
|
||||
email = (body.get("email") or "").strip()
|
||||
if not email:
|
||||
raise ValueError("'email' is required")
|
||||
return {"email": email, "server": (body.get("server") or "").strip()}
|
||||
|
||||
|
||||
@bp.route("/renew/<request_id>", methods=["GET"])
|
||||
def renew_status(request_id: str):
|
||||
"""GET /api/certs/renew/<request_id> — poll status of a certificate renewal.
|
||||
|
||||
Args:
|
||||
request_id: Renewal request identifier returned by renew_bp.
|
||||
|
||||
Returns:
|
||||
Response containing renewal status or an error message.
|
||||
"""
|
||||
try:
|
||||
result = get(GET_ACME_RENEW_STATUS, {"id": request_id})
|
||||
return _ok(result)
|
||||
except NotFound as exc:
|
||||
logger.info("Renewal request '%s' not found: %s", request_id, exc)
|
||||
return _error(str(exc), 404)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get renewal status for '%s': %s", request_id, exc)
|
||||
return _error(str(exc), 500)
|
||||
def _email_echo(_data: Any, _va: Any, sent: Any) -> Any:
|
||||
return {"email": sent["email"]}
|
||||
|
||||
|
||||
@bp.route("/<domain>", methods=["DELETE"])
|
||||
def remove_bp(domain: str):
|
||||
"""DELETE /api/certs/<domain> — remove a certificate from ACME management.
|
||||
|
||||
Args:
|
||||
domain: Domain name whose certificate should be removed.
|
||||
|
||||
Returns:
|
||||
Response confirming removal or an error message.
|
||||
"""
|
||||
try:
|
||||
delete(DELETE_ACME_REMOVE, {"domain": domain})
|
||||
logger.info("Certificate removed for '%s' via API", domain)
|
||||
return _ok(None)
|
||||
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)
|
||||
@daemon_route(GET_ACME_LIST, bp)
|
||||
def list_certs_bp():
|
||||
"""GET /api/certs/list — List all managed ACME certificates."""
|
||||
|
||||
|
||||
@bp.route("/email", methods=["POST"])
|
||||
@daemon_route(GET_ACME_INFO, bp, rule="/<domain>")
|
||||
def cert_details():
|
||||
"""GET /api/certs/<domain> — Get details for a specific certificate."""
|
||||
|
||||
|
||||
@daemon_route(POST_ACME_VALIDATE, bp, body=_validate_body)
|
||||
def validate():
|
||||
"""POST /api/certs/validate — Run pre-flight checks for issuance."""
|
||||
|
||||
|
||||
@daemon_route(POST_ACME_ISSUE, bp, rule="/issue/start", body=_issue_body)
|
||||
def issue_start():
|
||||
"""POST /api/certs/issue/start — Create a new certificate issuance request."""
|
||||
|
||||
|
||||
@daemon_route(
|
||||
GET_ACME_ISSUE_STATUS, bp, rule="/issue/<request_id>", params={"id": "request_id"}
|
||||
)
|
||||
def issue_status():
|
||||
"""GET /api/certs/issue/<request_id> — Poll status of an issuance request."""
|
||||
|
||||
|
||||
@daemon_route(POST_ACME_RENEW, bp, rule="/<domain>/renew")
|
||||
def renew_bp():
|
||||
"""POST /api/certs/<domain>/renew — Start an (async) certificate renewal."""
|
||||
|
||||
|
||||
@daemon_route(
|
||||
GET_ACME_RENEW_STATUS, bp, rule="/renew/<request_id>", params={"id": "request_id"}
|
||||
)
|
||||
def renew_status():
|
||||
"""GET /api/certs/renew/<request_id> — Poll status of a certificate renewal."""
|
||||
|
||||
|
||||
@daemon_route(DELETE_ACME_REMOVE, bp, rule="/<domain>", transform=void_transform)
|
||||
def remove_bp():
|
||||
"""DELETE /api/certs/<domain> — Remove a certificate from ACME management."""
|
||||
|
||||
|
||||
@daemon_route(POST_ACME_EMAIL, bp, body=_email_body, transform=_email_echo)
|
||||
def set_email_bp():
|
||||
"""POST /api/certs/email — set the ACME account email address.
|
||||
|
||||
Expects JSON body with ``{``email``}``.
|
||||
|
||||
Returns:
|
||||
Response confirming the email was set or an error message.
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
email = (body.get("email") or "").strip()
|
||||
if not email:
|
||||
return _error("'email' is required", 400)
|
||||
try:
|
||||
post(POST_ACME_EMAIL, {"email": email})
|
||||
logger.info("ACME email set via API: %s", email)
|
||||
return _ok({"email": email})
|
||||
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)
|
||||
"""POST /api/certs/email — Set the ACME account email address."""
|
||||
|
||||
|
||||
@bp.route("/account", methods=["GET"])
|
||||
@daemon_route(GET_ACME_ACCOUNT, bp)
|
||||
def account():
|
||||
"""GET /api/certs/account — return ACME account information.
|
||||
|
||||
Returns:
|
||||
Response containing account status or an error message.
|
||||
"""
|
||||
try:
|
||||
result = get(GET_ACME_ACCOUNT)
|
||||
return _ok(result)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to get ACME account: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
"""GET /api/certs/account — Return ACME account information."""
|
||||
|
||||
|
||||
@bp.route("/account/register", methods=["POST"])
|
||||
@daemon_route(POST_ACME_ACCOUNT_REGISTER, bp, body=_register_body)
|
||||
def register_account():
|
||||
"""POST /api/certs/account/register — register a new ACME account.
|
||||
|
||||
Expects JSON body with ``{``email``, ``server``?}``.
|
||||
|
||||
Returns:
|
||||
Response confirming registration or an error message.
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
email = (body.get("email") or "").strip()
|
||||
if not email:
|
||||
return _error("'email' is required", 400)
|
||||
server = (body.get("server") or "").strip()
|
||||
try:
|
||||
result = post(POST_ACME_ACCOUNT_REGISTER, {"email": email, "server": server})
|
||||
return _ok(result)
|
||||
except BadRequest as exc:
|
||||
return _error(str(exc), 400)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to register ACME account: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
"""POST /api/certs/account/register — Register a new ACME account."""
|
||||
|
||||
|
||||
@bp.route("/account", methods=["DELETE"])
|
||||
@daemon_route(DELETE_ACME_ACCOUNT_DEACTIVATE, bp, rule="/account", body=NO_BODY)
|
||||
def deactivate_account():
|
||||
"""DELETE /api/certs/account — deactivate the ACME account.
|
||||
|
||||
Returns:
|
||||
Response confirming deactivation or an error message.
|
||||
"""
|
||||
try:
|
||||
result = delete(DELETE_ACME_ACCOUNT_DEACTIVATE)
|
||||
return _ok(result)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Failed to deactivate ACME account: %s", exc)
|
||||
return _error(str(exc), 500)
|
||||
"""DELETE /api/certs/account — Deactivate the ACME account."""
|
||||
|
||||
Reference in New Issue
Block a user