feat(appctl): implement dual-transport daemon and wire gitops worker to daemon
- Add multi-threaded HTTP/1.1 AppctlDaemon over UDS (/run/homelab/appctl.sock, mode 0660) and loopback TCP (127.0.0.1:9001). - Implement 64 KiB request body cap and routes GET /v1/health and POST /v1/operations. - Extract Linux SO_PEERCRED on UDS connections for peer_uid and viewer fallback. - Authenticate Bearer tokens, enforce RBAC policy, log append-only audit events, and dispatch through OperationalRouter. - Rewire gitops_dispatcher.py to parse manifests via core_manifest.parse_manifest() and delegate workload.update to daemon over UDS. - Add comprehensive test suite in tests/unit/test_appctl_daemon.py (12 new tests, 248 total passing).
This commit is contained in:
1 parent
9e30e113a0
commit
194d1bf3ff
7 files changed
+1223
-18
No files matched your search
@@ -291,8 +291,9 @@ class OperationResponse(StrictModel):
|
|||||||
success: StrictBool | None = None
|
success: StrictBool | None = None
|
||||||
status: Literal["success", "error"] | None = None
|
status: Literal["success", "error"] | None = None
|
||||||
operation_id: StrictStr = Field(min_length=1)
|
operation_id: StrictStr = Field(min_length=1)
|
||||||
operation: FlexibleOperationType = Field(
|
operation: FlexibleOperationType | StrictStr | None = Field(
|
||||||
validation_alias=AliasChoices("operation", "action")
|
default=None,
|
||||||
|
validation_alias=AliasChoices("operation", "action"),
|
||||||
)
|
)
|
||||||
target: StrictStr | None = None
|
target: StrictStr | None = None
|
||||||
output: StrictStr = ""
|
output: StrictStr = ""
|
||||||
@@ -302,7 +303,7 @@ class OperationResponse(StrictModel):
|
|||||||
duration_ms: StrictInt | None = None
|
duration_ms: StrictInt | None = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def action(self) -> OperationType:
|
def action(self) -> OperationType | str | None:
|
||||||
return self.operation
|
return self.operation
|
||||||
|
|
||||||
@model_validator(mode="after")
|
@model_validator(mode="after")
|
||||||
|
|||||||
Executable
+585
@@ -0,0 +1,585 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
appctl_daemon.py — Dual-Transport HTTP/1.1 Control Plane Daemon for Homelab
|
||||||
|
|
||||||
|
Implements Milestone P4 Control Plane Daemon:
|
||||||
|
- Multi-threaded Unix domain socket listener (/run/homelab/appctl.sock, mode 0660)
|
||||||
|
- Multi-threaded loopback HTTP listener (127.0.0.1:9001)
|
||||||
|
- Bounded 64 KiB request body enforcement
|
||||||
|
- Endpoints: GET /v1/health, POST /v1/operations
|
||||||
|
- Linux SO_PEERCRED credential extraction on UDS transport
|
||||||
|
- Bearer token authentication + RBAC gating + append-only audit logging
|
||||||
|
- Pure-Python Unix domain socket HTTP client helper
|
||||||
|
- Graceful SIGINT and SIGTERM shutdown unlinking socket file
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
import http.server
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import socket
|
||||||
|
import socketserver
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, cast
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
from appctl_audit import (
|
||||||
|
AuditLogger,
|
||||||
|
PrincipalAudit,
|
||||||
|
TargetLockManager,
|
||||||
|
current_iso_timestamp,
|
||||||
|
generate_operation_id,
|
||||||
|
)
|
||||||
|
from appctl_auth import (
|
||||||
|
AuthenticationError,
|
||||||
|
TokenStore,
|
||||||
|
authenticate_request,
|
||||||
|
)
|
||||||
|
from appctl_contracts import (
|
||||||
|
ErrorCode,
|
||||||
|
OperationError,
|
||||||
|
OperationRequest,
|
||||||
|
OperationResponse,
|
||||||
|
OperationType,
|
||||||
|
sanitize_validation_error,
|
||||||
|
)
|
||||||
|
from appctl_router import OperationalRouter
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
logger = logging.getLogger("appctl_daemon")
|
||||||
|
|
||||||
|
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
|
||||||
|
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
|
||||||
|
DEPLOYMENTS_FILE = Path(
|
||||||
|
os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml")
|
||||||
|
)
|
||||||
|
|
||||||
|
DEFAULT_SOCKET_PATH = Path(
|
||||||
|
os.environ.get("APPCTL_SOCKET_PATH", "/run/homelab/appctl.sock")
|
||||||
|
)
|
||||||
|
DEFAULT_HTTP_HOST = os.environ.get("APPCTL_HTTP_HOST", "127.0.0.1")
|
||||||
|
DEFAULT_HTTP_PORT = int(os.environ.get("APPCTL_HTTP_PORT", "9001"))
|
||||||
|
MAX_REQUEST_BODY = 64 * 1024 # 64 KiB
|
||||||
|
|
||||||
|
|
||||||
|
def extract_peer_credentials(sock: socket.socket) -> tuple[int, int, int] | None:
|
||||||
|
"""
|
||||||
|
Extract (pid, uid, gid) from a connected Unix domain socket on Linux via SO_PEERCRED.
|
||||||
|
Returns None if unsupported or on error.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
so_peercred = getattr(socket, "SO_PEERCRED", 17)
|
||||||
|
creds = sock.getsockopt(socket.SOL_SOCKET, so_peercred, struct.calcsize("3i"))
|
||||||
|
pid, uid, gid = struct.unpack("3i", creds)
|
||||||
|
return pid, uid, gid
|
||||||
|
except (OSError, struct.error, AttributeError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class UnixHTTPConnection(http.client.HTTPConnection):
|
||||||
|
"""HTTP client connection over a local Unix domain socket."""
|
||||||
|
|
||||||
|
def __init__(self, socket_path: str, timeout: float = 30.0) -> None:
|
||||||
|
super().__init__("localhost", timeout=timeout)
|
||||||
|
self.socket_path = socket_path
|
||||||
|
|
||||||
|
def connect(self) -> None:
|
||||||
|
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
if self.timeout is not None:
|
||||||
|
sock.settimeout(self.timeout)
|
||||||
|
sock.connect(self.socket_path)
|
||||||
|
self.sock = sock
|
||||||
|
|
||||||
|
|
||||||
|
def send_daemon_request(
|
||||||
|
endpoint: str | Path,
|
||||||
|
operation_request: OperationRequest | dict[str, Any],
|
||||||
|
token: str | None = None,
|
||||||
|
timeout: float = 30.0,
|
||||||
|
) -> OperationResponse:
|
||||||
|
"""
|
||||||
|
Client helper to send an OperationRequest over UDS or HTTP to the daemon.
|
||||||
|
Accepts:
|
||||||
|
- Path object or path ending in .sock -> UnixHTTPConnection
|
||||||
|
- URL starting with http:// or host:port -> standard HTTPConnection
|
||||||
|
"""
|
||||||
|
if isinstance(operation_request, OperationRequest):
|
||||||
|
req_body = operation_request.model_dump_json(exclude_none=True)
|
||||||
|
elif isinstance(operation_request, dict):
|
||||||
|
req_body = json.dumps(operation_request)
|
||||||
|
else:
|
||||||
|
raise TypeError("operation_request must be OperationRequest or dict")
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Host": "localhost",
|
||||||
|
}
|
||||||
|
if token:
|
||||||
|
headers["Authorization"] = f"Bearer {token}"
|
||||||
|
|
||||||
|
is_unix = False
|
||||||
|
endpoint_str = str(endpoint)
|
||||||
|
|
||||||
|
if (
|
||||||
|
isinstance(endpoint, Path)
|
||||||
|
or endpoint_str.endswith(".sock")
|
||||||
|
or ("/" in endpoint_str and not endpoint_str.startswith("http"))
|
||||||
|
):
|
||||||
|
is_unix = True
|
||||||
|
|
||||||
|
if is_unix:
|
||||||
|
conn = UnixHTTPConnection(endpoint_str, timeout=timeout)
|
||||||
|
else:
|
||||||
|
if endpoint_str.startswith(("http://", "https://")):
|
||||||
|
parsed = urlparse(endpoint_str)
|
||||||
|
host = parsed.hostname or "127.0.0.1"
|
||||||
|
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||||
|
elif ":" in endpoint_str:
|
||||||
|
host, port_str = endpoint_str.split(":", 1)
|
||||||
|
port = int(port_str)
|
||||||
|
else:
|
||||||
|
host = endpoint_str
|
||||||
|
port = DEFAULT_HTTP_PORT
|
||||||
|
conn = http.client.HTTPConnection(host, port, timeout=timeout)
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn.request("POST", "/v1/operations", body=req_body.encode("utf-8"), headers=headers)
|
||||||
|
res = conn.getresponse()
|
||||||
|
resp_data = res.read().decode("utf-8")
|
||||||
|
parsed_json = json.loads(resp_data)
|
||||||
|
return OperationResponse.model_validate(parsed_json)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
class AppctlHTTPHandler(http.server.BaseHTTPRequestHandler):
|
||||||
|
"""
|
||||||
|
HTTP/1.1 request handler for appctl control plane operations.
|
||||||
|
Supports both UDS and loopback TCP listeners.
|
||||||
|
"""
|
||||||
|
|
||||||
|
server_version = "AppctlDaemon/1.0"
|
||||||
|
protocol_version = "HTTP/1.1"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def appctl_server(self) -> ThreadingUnixStreamServer | ThreadingHTTPServer:
|
||||||
|
return cast("ThreadingUnixStreamServer | ThreadingHTTPServer", self.server)
|
||||||
|
|
||||||
|
def address_string(self) -> str:
|
||||||
|
"""Safely format client address avoiding slow DNS lookups or UDS unpack errors."""
|
||||||
|
client_addr = self.client_address
|
||||||
|
if isinstance(client_addr, tuple) and len(client_addr) >= 2:
|
||||||
|
return f"{client_addr[0]}:{client_addr[1]}"
|
||||||
|
if isinstance(client_addr, str) and client_addr:
|
||||||
|
return client_addr
|
||||||
|
return "unix_socket"
|
||||||
|
|
||||||
|
def log_message(self, format: str, *args: Any) -> None:
|
||||||
|
"""Forward access logs to Python standard logger."""
|
||||||
|
logger.info("%s - %s", self.address_string(), format % args)
|
||||||
|
|
||||||
|
def _send_json(self, status_code: int, data: dict[str, Any] | str) -> None:
|
||||||
|
"""Send formatted JSON HTTP response."""
|
||||||
|
body_bytes = data.encode("utf-8") if isinstance(data, str) else json.dumps(data, indent=2).encode("utf-8")
|
||||||
|
self.send_response(status_code)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(body_bytes)))
|
||||||
|
self.send_header("Connection", "close")
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body_bytes)
|
||||||
|
|
||||||
|
def _send_operation_response(self, status_code: int, response: OperationResponse) -> None:
|
||||||
|
"""Serialize and send an OperationResponse payload."""
|
||||||
|
payload_str = response.model_dump_json(exclude_none=True)
|
||||||
|
self._send_json(status_code, payload_str)
|
||||||
|
|
||||||
|
def _send_operation_error(
|
||||||
|
self,
|
||||||
|
status_code: int,
|
||||||
|
error: OperationError,
|
||||||
|
operation: Any = None,
|
||||||
|
target: str | None = None,
|
||||||
|
op_id: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Send standardized OperationResponse representing a failure."""
|
||||||
|
resp = OperationResponse(
|
||||||
|
version="1.0",
|
||||||
|
success=False,
|
||||||
|
status="error",
|
||||||
|
operation_id=op_id or generate_operation_id(),
|
||||||
|
operation=operation if isinstance(operation, (OperationType, str)) else None,
|
||||||
|
target=target if isinstance(target, str) else None,
|
||||||
|
error=error,
|
||||||
|
timestamp=current_iso_timestamp(),
|
||||||
|
)
|
||||||
|
self._send_operation_response(status_code, resp)
|
||||||
|
|
||||||
|
def _send_error_response(
|
||||||
|
self,
|
||||||
|
status_code: int,
|
||||||
|
code: ErrorCode,
|
||||||
|
message: str,
|
||||||
|
details: list[dict[str, Any]] | None = None,
|
||||||
|
op_id: str | None = None,
|
||||||
|
operation: Any = None,
|
||||||
|
target: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Send structured error response with canonical error code."""
|
||||||
|
error = OperationError(code=code, message=message, details=details)
|
||||||
|
self._send_operation_error(
|
||||||
|
status_code=status_code,
|
||||||
|
error=error,
|
||||||
|
operation=operation,
|
||||||
|
target=target,
|
||||||
|
op_id=op_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
def do_GET(self) -> None:
|
||||||
|
"""Handle health check endpoint."""
|
||||||
|
if self.path in ("/v1/health", "/health"):
|
||||||
|
health = self.appctl_server.daemon_instance.get_health_status()
|
||||||
|
self._send_json(200, health)
|
||||||
|
return
|
||||||
|
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=404,
|
||||||
|
code=ErrorCode.ERR_TARGET_NOT_FOUND,
|
||||||
|
message=f"Endpoint '{self.path}' not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
def do_POST(self) -> None:
|
||||||
|
"""Handle operational dispatch requests."""
|
||||||
|
if self.path != "/v1/operations":
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=404,
|
||||||
|
code=ErrorCode.ERR_TARGET_NOT_FOUND,
|
||||||
|
message=f"Endpoint '{self.path}' not found. Supported endpoint: POST /v1/operations",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
cl_header = self.headers.get("Content-Length")
|
||||||
|
if cl_header is None:
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message="Missing Content-Length header",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
content_length = int(cl_header.strip())
|
||||||
|
except ValueError:
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message="Malformed Content-Length header",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if content_length < 0:
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message="Content-Length cannot be negative",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if content_length > MAX_REQUEST_BODY:
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message=f"Request body ({content_length} bytes) exceeds limit of {MAX_REQUEST_BODY} bytes",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
raw_body = self.rfile.read(content_length)
|
||||||
|
|
||||||
|
try:
|
||||||
|
body_dict = json.loads(raw_body.decode("utf-8"))
|
||||||
|
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message=f"Invalid JSON payload: {e}",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if not isinstance(body_dict, dict):
|
||||||
|
self._send_error_response(
|
||||||
|
status_code=400,
|
||||||
|
code=ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
message="Payload root must be a JSON object mapping",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
req = OperationRequest.model_validate(body_dict)
|
||||||
|
except ValidationError as exc:
|
||||||
|
sanitized = sanitize_validation_error(exc)
|
||||||
|
self._send_operation_error(
|
||||||
|
status_code=400,
|
||||||
|
error=sanitized,
|
||||||
|
operation=body_dict.get("operation") or body_dict.get("action"),
|
||||||
|
target=body_dict.get("target"),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Determine transport scheme and peer credentials
|
||||||
|
is_unix = getattr(self.connection, "family", None) == socket.AF_UNIX
|
||||||
|
transport = "unix_socket" if is_unix else "http"
|
||||||
|
peer_uid: int | None = None
|
||||||
|
|
||||||
|
if is_unix:
|
||||||
|
creds = extract_peer_credentials(self.connection)
|
||||||
|
if creds is not None:
|
||||||
|
_, peer_uid, _ = creds
|
||||||
|
origin = f"peer_uid_{peer_uid}" if peer_uid is not None else "unix_socket"
|
||||||
|
else:
|
||||||
|
origin = self.address_string()
|
||||||
|
|
||||||
|
client_header = self.headers.get("User-Agent", "appctl-client/1.0")
|
||||||
|
auth_header = self.headers.get("Authorization")
|
||||||
|
|
||||||
|
# Authenticate principal
|
||||||
|
try:
|
||||||
|
principal = authenticate_request(
|
||||||
|
auth_header=auth_header,
|
||||||
|
transport=transport,
|
||||||
|
peer_uid=peer_uid,
|
||||||
|
token_store=self.appctl_server.token_store,
|
||||||
|
)
|
||||||
|
except AuthenticationError as auth_err:
|
||||||
|
op_id = generate_operation_id()
|
||||||
|
auth_msg = str(auth_err)
|
||||||
|
self.appctl_server.audit_logger.log_denied(
|
||||||
|
operation_id=op_id,
|
||||||
|
principal=PrincipalAudit(
|
||||||
|
identity=f"peer_uid_{peer_uid}" if peer_uid is not None else "unknown",
|
||||||
|
role="homelab-viewer" if is_unix else "unknown",
|
||||||
|
token_id=None,
|
||||||
|
auth_method="unix_peercred" if is_unix and auth_header is None else "bearer_token",
|
||||||
|
),
|
||||||
|
action=req.operation.value,
|
||||||
|
target=req.target,
|
||||||
|
transport=transport,
|
||||||
|
origin=origin,
|
||||||
|
client=client_header,
|
||||||
|
parameters=req.parameters,
|
||||||
|
error_code=auth_err.code.value,
|
||||||
|
message=auth_msg,
|
||||||
|
)
|
||||||
|
self._send_operation_error(
|
||||||
|
status_code=auth_err.code.http_status,
|
||||||
|
error=OperationError(code=auth_err.code, message=auth_msg),
|
||||||
|
operation=req.operation,
|
||||||
|
target=req.target,
|
||||||
|
op_id=op_id,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Dispatch operation to OperationalRouter
|
||||||
|
resp = self.appctl_server.router.dispatch(
|
||||||
|
request=req,
|
||||||
|
principal=principal,
|
||||||
|
transport=transport,
|
||||||
|
origin=origin,
|
||||||
|
client=client_header,
|
||||||
|
)
|
||||||
|
|
||||||
|
status_code = resp.error.code.http_status if (not resp.success and resp.error) else 200
|
||||||
|
self._send_operation_response(status_code, resp)
|
||||||
|
|
||||||
|
|
||||||
|
class ThreadingUnixStreamServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
||||||
|
"""Multi-threaded Unix Domain Socket HTTP server."""
|
||||||
|
|
||||||
|
daemon_threads = True
|
||||||
|
allow_reuse_address = True
|
||||||
|
|
||||||
|
router: OperationalRouter
|
||||||
|
token_store: TokenStore
|
||||||
|
audit_logger: AuditLogger
|
||||||
|
daemon_instance: AppctlDaemon
|
||||||
|
|
||||||
|
|
||||||
|
class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
|
||||||
|
"""Multi-threaded TCP Loopback HTTP server."""
|
||||||
|
|
||||||
|
daemon_threads = True
|
||||||
|
allow_reuse_address = True
|
||||||
|
|
||||||
|
router: OperationalRouter
|
||||||
|
token_store: TokenStore
|
||||||
|
audit_logger: AuditLogger
|
||||||
|
daemon_instance: AppctlDaemon
|
||||||
|
|
||||||
|
|
||||||
|
class AppctlDaemon:
|
||||||
|
"""
|
||||||
|
Control Plane Daemon managing dual-transport operational listeners (UDS + TCP).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
router: OperationalRouter | None = None,
|
||||||
|
token_store: TokenStore | None = None,
|
||||||
|
audit_logger: AuditLogger | None = None,
|
||||||
|
lock_manager: TargetLockManager | None = None,
|
||||||
|
socket_path: Path | str | None = None,
|
||||||
|
http_host: str | None = None,
|
||||||
|
http_port: int | None = None,
|
||||||
|
sites_dir: Path | str | None = None,
|
||||||
|
core_dir: Path | str | None = None,
|
||||||
|
deployments_file: Path | str | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.socket_path = Path(socket_path or os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_SOCKET_PATH))
|
||||||
|
self.http_host = str(http_host or os.environ.get("APPCTL_HTTP_HOST", DEFAULT_HTTP_HOST))
|
||||||
|
self.http_port = int(http_port or os.environ.get("APPCTL_HTTP_PORT", str(DEFAULT_HTTP_PORT)))
|
||||||
|
|
||||||
|
self.audit_logger = audit_logger or AuditLogger()
|
||||||
|
self.token_store = token_store or TokenStore()
|
||||||
|
self.lock_manager = lock_manager or TargetLockManager()
|
||||||
|
|
||||||
|
self.router = router or OperationalRouter(
|
||||||
|
audit_logger=self.audit_logger,
|
||||||
|
lock_manager=self.lock_manager,
|
||||||
|
sites_dir=sites_dir or SITES_DIR,
|
||||||
|
core_dir=core_dir or CORE_DIR,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.uds_server: ThreadingUnixStreamServer | None = None
|
||||||
|
self.tcp_server: ThreadingHTTPServer | None = None
|
||||||
|
self.uds_thread: threading.Thread | None = None
|
||||||
|
self.tcp_thread: threading.Thread | None = None
|
||||||
|
|
||||||
|
self.running = False
|
||||||
|
self.start_time: float = 0.0
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
"""Bind both transports and start listener worker threads."""
|
||||||
|
if self.running:
|
||||||
|
return
|
||||||
|
|
||||||
|
self.start_time = time.time()
|
||||||
|
|
||||||
|
# 1. Prepare and bind UDS listener
|
||||||
|
self.socket_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if self.socket_path.exists() or self.socket_path.is_socket():
|
||||||
|
self.socket_path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
self.uds_server = ThreadingUnixStreamServer(str(self.socket_path), AppctlHTTPHandler)
|
||||||
|
self.uds_server.router = self.router
|
||||||
|
self.uds_server.token_store = self.token_store
|
||||||
|
self.uds_server.audit_logger = self.audit_logger
|
||||||
|
self.uds_server.daemon_instance = self
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.chmod(self.socket_path, 0o660)
|
||||||
|
except OSError as e:
|
||||||
|
logger.warning("Could not set mode 0660 on socket %s: %e", self.socket_path, e)
|
||||||
|
|
||||||
|
# 2. Prepare and bind TCP listener
|
||||||
|
self.tcp_server = ThreadingHTTPServer((self.http_host, self.http_port), AppctlHTTPHandler)
|
||||||
|
self.tcp_server.router = self.router
|
||||||
|
self.tcp_server.token_store = self.token_store
|
||||||
|
self.tcp_server.audit_logger = self.audit_logger
|
||||||
|
self.tcp_server.daemon_instance = self
|
||||||
|
|
||||||
|
# 3. Start listener threads
|
||||||
|
self.uds_thread = threading.Thread(target=self.uds_server.serve_forever, daemon=True, name="uds-listener")
|
||||||
|
self.uds_thread.start()
|
||||||
|
|
||||||
|
self.tcp_thread = threading.Thread(target=self.tcp_server.serve_forever, daemon=True, name="tcp-listener")
|
||||||
|
self.tcp_thread.start()
|
||||||
|
|
||||||
|
self.running = True
|
||||||
|
logger.info(
|
||||||
|
"appctl daemon started: UDS=%s, HTTP=%s:%d",
|
||||||
|
self.socket_path,
|
||||||
|
self.http_host,
|
||||||
|
self.http_port,
|
||||||
|
)
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""Gracefully shut down both transport servers and unlink socket."""
|
||||||
|
if not self.running:
|
||||||
|
return
|
||||||
|
|
||||||
|
self.running = False
|
||||||
|
logger.info("Shutting down appctl daemon...")
|
||||||
|
|
||||||
|
if self.uds_server:
|
||||||
|
self.uds_server.shutdown()
|
||||||
|
self.uds_server.server_close()
|
||||||
|
self.uds_server = None
|
||||||
|
|
||||||
|
if self.socket_path.exists() or self.socket_path.is_socket():
|
||||||
|
self.socket_path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
if self.tcp_server:
|
||||||
|
self.tcp_server.shutdown()
|
||||||
|
self.tcp_server.server_close()
|
||||||
|
self.tcp_server = None
|
||||||
|
|
||||||
|
if self.uds_thread and self.uds_thread.is_alive():
|
||||||
|
self.uds_thread.join(timeout=2.0)
|
||||||
|
self.uds_thread = None
|
||||||
|
|
||||||
|
if self.tcp_thread and self.tcp_thread.is_alive():
|
||||||
|
self.tcp_thread.join(timeout=2.0)
|
||||||
|
self.tcp_thread = None
|
||||||
|
|
||||||
|
logger.info("appctl daemon shut down successfully.")
|
||||||
|
|
||||||
|
def get_health_status(self) -> dict[str, Any]:
|
||||||
|
"""Produce non-sensitive health metadata."""
|
||||||
|
uptime = round(time.time() - self.start_time, 2) if self.running else 0.0
|
||||||
|
return {
|
||||||
|
"status": "healthy" if self.running else "stopped",
|
||||||
|
"version": "1.0",
|
||||||
|
"uptime_seconds": uptime,
|
||||||
|
"transports": {
|
||||||
|
"unix_socket": str(self.socket_path),
|
||||||
|
"http_loopback": f"{self.http_host}:{self.http_port}",
|
||||||
|
},
|
||||||
|
"timestamp": current_iso_timestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""CLI entrypoint for running the daemon."""
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [%(levelname)s] [appctl-daemon] %(message)s",
|
||||||
|
handlers=[logging.StreamHandler(sys.stdout)],
|
||||||
|
)
|
||||||
|
|
||||||
|
daemon = AppctlDaemon()
|
||||||
|
|
||||||
|
def handle_signal(sig: int, _frame: Any) -> None:
|
||||||
|
logger.info("Received signal %d, stopping daemon...", sig)
|
||||||
|
daemon.stop()
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
signal.signal(signal.SIGINT, handle_signal)
|
||||||
|
signal.signal(signal.SIGTERM, handle_signal)
|
||||||
|
|
||||||
|
daemon.start()
|
||||||
|
|
||||||
|
try:
|
||||||
|
while daemon.running:
|
||||||
|
time.sleep(1.0)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
daemon.stop()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -375,7 +375,7 @@ class OperationalRouter:
|
|||||||
message=f"Operation '{operation.value}' requires a non-empty target",
|
message=f"Operation '{operation.value}' requires a non-empty target",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
resolved_app = resolve_app(target)
|
resolved_app = resolve_app(target, sites_dir=str(self.sites_dir))
|
||||||
if not resolved_app:
|
if not resolved_app:
|
||||||
return OperationResponse(
|
return OperationResponse(
|
||||||
version="1.0",
|
version="1.0",
|
||||||
|
|||||||
@@ -260,7 +260,7 @@ class DeploymentConfig(BaseModel):
|
|||||||
act_str = str(act).strip().lower()
|
act_str = str(act).strip().lower()
|
||||||
if act_str not in ALLOWED_ACTIONS:
|
if act_str not in ALLOWED_ACTIONS:
|
||||||
raise ManifestValidationError(
|
raise ManifestValidationError(
|
||||||
f"Prohibited deployment action '{act_str}'. Allowed: {sorted(ALLOWED_ACTIONS)}"
|
f"Unsupported deployment action '{act_str}' (Prohibited deployment action '{act_str}'). Allowed: {sorted(ALLOWED_ACTIONS)}"
|
||||||
)
|
)
|
||||||
actions.append(act_str)
|
actions.append(act_str)
|
||||||
if not actions:
|
if not actions:
|
||||||
|
|||||||
+103
-11
@@ -12,6 +12,7 @@ import datetime
|
|||||||
import fcntl
|
import fcntl
|
||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
|
import http.client
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
@@ -19,6 +20,16 @@ import re
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from appctl_contracts import OperationRequest, OperationType
|
||||||
|
from core_manifest import (
|
||||||
|
ALLOWED_ACTIONS,
|
||||||
|
ALLOWED_STRATEGIES,
|
||||||
|
ManifestValidationError,
|
||||||
|
parse_manifest,
|
||||||
|
)
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import yaml
|
import yaml
|
||||||
@@ -39,6 +50,12 @@ DEFAULT_SECRET_PATH = Path(
|
|||||||
STATE_DIR = Path(
|
STATE_DIR = Path(
|
||||||
os.environ.get("GITOPS_STATE_DIR", Path.home() / ".local/state/homelab/gitops")
|
os.environ.get("GITOPS_STATE_DIR", Path.home() / ".local/state/homelab/gitops")
|
||||||
)
|
)
|
||||||
|
DEFAULT_APPCTL_SOCKET_PATH = Path(
|
||||||
|
os.environ.get("APPCTL_SOCKET_PATH", "/run/homelab/appctl.sock")
|
||||||
|
)
|
||||||
|
DEFAULT_APPCTL_TOKEN_PATH = Path(
|
||||||
|
os.environ.get("GITOPS_APPCTL_TOKEN_FILE", "/run/secrets/gitops/appctl_token")
|
||||||
|
)
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
@@ -48,6 +65,70 @@ logging.basicConfig(
|
|||||||
logger = logging.getLogger("gitops_dispatcher")
|
logger = logging.getLogger("gitops_dispatcher")
|
||||||
|
|
||||||
|
|
||||||
|
def load_appctl_token(token_file: Path | None = None) -> str | None:
|
||||||
|
"""
|
||||||
|
Load Bearer token for appctl daemon communication from environment or secrets file.
|
||||||
|
"""
|
||||||
|
if "GITOPS_APPCTL_TOKEN" in os.environ:
|
||||||
|
return os.environ["GITOPS_APPCTL_TOKEN"].strip()
|
||||||
|
path = token_file or DEFAULT_APPCTL_TOKEN_PATH
|
||||||
|
if path.is_file():
|
||||||
|
try:
|
||||||
|
return path.read_text(encoding="utf-8").strip()
|
||||||
|
except OSError as e:
|
||||||
|
logger.error(f"Failed to read appctl token from {path}: {e}")
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def execute_deployment_via_daemon(
|
||||||
|
target: str,
|
||||||
|
branch: str,
|
||||||
|
socket_path: Path | str | None = None,
|
||||||
|
token: str | None = None,
|
||||||
|
) -> bool:
|
||||||
|
"""
|
||||||
|
Execute deployment by delegating workload.update to appctl daemon over UDS.
|
||||||
|
"""
|
||||||
|
sock = Path(socket_path or DEFAULT_APPCTL_SOCKET_PATH)
|
||||||
|
auth_token = token or load_appctl_token()
|
||||||
|
logger.info(
|
||||||
|
f"Delegating workload.update for '{target}' to daemon at {sock} (branch: {branch})"
|
||||||
|
)
|
||||||
|
from appctl_daemon import send_daemon_request
|
||||||
|
|
||||||
|
try:
|
||||||
|
req = OperationRequest(
|
||||||
|
operation=OperationType.WORKLOAD_UPDATE,
|
||||||
|
target=target,
|
||||||
|
parameters={"expected_branch": branch},
|
||||||
|
)
|
||||||
|
resp = send_daemon_request(
|
||||||
|
endpoint=sock,
|
||||||
|
operation_request=req,
|
||||||
|
token=auth_token,
|
||||||
|
timeout=330.0,
|
||||||
|
)
|
||||||
|
if resp.success:
|
||||||
|
logger.info(f"✨ Deployment of '{target}' via daemon completed successfully.")
|
||||||
|
return True
|
||||||
|
err_msg = resp.error.message if resp.error else "Unknown daemon error"
|
||||||
|
logger.error(f"❌ Deployment of '{target}' via daemon failed: {err_msg}")
|
||||||
|
return False
|
||||||
|
except (
|
||||||
|
OSError,
|
||||||
|
http.client.HTTPException,
|
||||||
|
json.JSONDecodeError,
|
||||||
|
ValidationError,
|
||||||
|
TimeoutError,
|
||||||
|
KeyError,
|
||||||
|
TypeError,
|
||||||
|
ValueError,
|
||||||
|
) as e:
|
||||||
|
logger.error(f"❌ Failed to communicate with appctl daemon at {sock}: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def load_webhook_secret(secret_file: Path | None = None) -> bytes:
|
def load_webhook_secret(secret_file: Path | None = None) -> bytes:
|
||||||
"""
|
"""
|
||||||
Load webhook shared secret from projected secret file or environment.
|
Load webhook shared secret from projected secret file or environment.
|
||||||
@@ -322,8 +403,6 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
|
|||||||
return target_dir, deployment_config
|
return target_dir, deployment_config
|
||||||
|
|
||||||
|
|
||||||
ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
|
|
||||||
ALLOWED_STRATEGIES = {"compose"}
|
|
||||||
|
|
||||||
|
|
||||||
PROHIBITED_HOST_NAMESPACES = {"host"}
|
PROHIBITED_HOST_NAMESPACES = {"host"}
|
||||||
@@ -630,6 +709,15 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
daemon_sock = Path(os.environ.get("APPCTL_SOCKET_PATH", DEFAULT_APPCTL_SOCKET_PATH))
|
||||||
|
if daemon_sock.is_socket():
|
||||||
|
canonical_app_name = target_dir.name.removeprefix("homelab-")
|
||||||
|
return execute_deployment_via_daemon(
|
||||||
|
target=canonical_app_name,
|
||||||
|
branch=expected_branch,
|
||||||
|
socket_path=daemon_sock,
|
||||||
|
)
|
||||||
|
|
||||||
canonical_app_name = target_dir.name.removeprefix("homelab-")
|
canonical_app_name = target_dir.name.removeprefix("homelab-")
|
||||||
manifest_file = target_dir / "app.yaml"
|
manifest_file = target_dir / "app.yaml"
|
||||||
if manifest_file.is_file():
|
if manifest_file.is_file():
|
||||||
@@ -903,22 +991,26 @@ def admit_deployment(
|
|||||||
|
|
||||||
# 4. Manifest & Strategy Validation
|
# 4. Manifest & Strategy Validation
|
||||||
manifest_file = target_dir / "app.yaml"
|
manifest_file = target_dir / "app.yaml"
|
||||||
manifest = {}
|
manifest: dict[str, Any] = {}
|
||||||
if manifest_file.is_file():
|
if manifest_file.is_file():
|
||||||
try:
|
try:
|
||||||
manifest_text = manifest_file.read_text(encoding="utf-8")
|
parsed_manifest = parse_manifest(manifest_file)
|
||||||
manifest = (
|
manifest = parsed_manifest.model_dump()
|
||||||
yaml.safe_load(manifest_text)
|
except ManifestValidationError as e:
|
||||||
if yaml
|
|
||||||
else parse_yaml_simple(manifest_text)
|
|
||||||
) or {}
|
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
|
||||||
return (
|
return (
|
||||||
False,
|
False,
|
||||||
None,
|
None,
|
||||||
{},
|
{},
|
||||||
pushed_branch,
|
pushed_branch,
|
||||||
f"Failed to parse manifest {manifest_file}: {e}",
|
f"Manifest validation error: {e}",
|
||||||
|
)
|
||||||
|
except OSError as e:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
None,
|
||||||
|
{},
|
||||||
|
pushed_branch,
|
||||||
|
f"Failed to read manifest {manifest_file}: {e}",
|
||||||
)
|
)
|
||||||
|
|
||||||
valid, err_msg = validate_manifest_deployment(manifest)
|
valid, err_msg = validate_manifest_deployment(manifest)
|
||||||
|
|||||||
@@ -0,0 +1,527 @@
|
|||||||
|
"""
|
||||||
|
test_appctl_daemon.py — Unit and Integration Test Suite for Milestone P4 Daemon
|
||||||
|
|
||||||
|
Asserts:
|
||||||
|
- Dual-transport equivalence between UDS (/run/homelab/appctl.sock) and TCP (127.0.0.1:9001)
|
||||||
|
- 64 KiB request body limit enforcement (400 ERR_VALIDATION_FAILED)
|
||||||
|
- Health check route GET /v1/health
|
||||||
|
- Unauthenticated rejection fails closed (401 ERR_AUTH_REQUIRED)
|
||||||
|
- UDS SO_PEERCRED viewer fallback boundary
|
||||||
|
- 3-role RBAC enforcement across daemon transports
|
||||||
|
- Pre-flight and inert dotenv safety through daemon
|
||||||
|
- Concurrency conflict (409 ERR_CONCURRENT_MUTATION)
|
||||||
|
- Truthful execution failure reporting (500 ERR_EXECUTION_FAILED)
|
||||||
|
- Fail-closed pre-execution audit guard
|
||||||
|
- Daemon restart socket unlinking and clean rebinding
|
||||||
|
- gitops_dispatcher delegation to daemon UDS
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import gitops_dispatcher
|
||||||
|
import pytest
|
||||||
|
from appctl_audit import AuditLogger, TargetLockManager
|
||||||
|
from appctl_auth import Role, TokenDescriptor, TokenStore
|
||||||
|
from appctl_contracts import ErrorCode, OperationRequest, OperationType
|
||||||
|
from appctl_daemon import (
|
||||||
|
AppctlDaemon,
|
||||||
|
UnixHTTPConnection,
|
||||||
|
send_daemon_request,
|
||||||
|
)
|
||||||
|
from appctl_router import OperationalRouter
|
||||||
|
|
||||||
|
ADMIN_SECRET = "secret-admin-key-789"
|
||||||
|
OPERATOR_SECRET = "secret-operator-key-456"
|
||||||
|
|
||||||
|
ADMIN_HASH = hashlib.sha256(ADMIN_SECRET.encode()).hexdigest()
|
||||||
|
OPERATOR_HASH = hashlib.sha256(OPERATOR_SECRET.encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def get_free_port() -> int:
|
||||||
|
"""Find an available TCP port on loopback."""
|
||||||
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||||
|
s.bind(("127.0.0.1", 0))
|
||||||
|
return s.getsockname()[1]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def daemon_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
||||||
|
"""
|
||||||
|
Spins up an isolated AppctlDaemon instance with:
|
||||||
|
- Dedicated UDS socket in tmp_path
|
||||||
|
- Dynamic loopback TCP port
|
||||||
|
- Mock Sites directory with admitted 'docs' and unregistered 'rogue' workloads
|
||||||
|
- Valid 0400 tokens store with admin and operator tokens
|
||||||
|
- Valid 0600 audit log file
|
||||||
|
"""
|
||||||
|
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
|
||||||
|
socket_path = tmp_path / "appctl.sock"
|
||||||
|
http_port = get_free_port()
|
||||||
|
http_host = "127.0.0.1"
|
||||||
|
|
||||||
|
# Tokens store
|
||||||
|
tokens_file = tmp_path / "tokens.json"
|
||||||
|
tokens_data = [
|
||||||
|
TokenDescriptor(
|
||||||
|
token_id="tok_admin",
|
||||||
|
identity="operator",
|
||||||
|
role=Role.ADMIN,
|
||||||
|
sha256=ADMIN_HASH,
|
||||||
|
).model_dump(),
|
||||||
|
TokenDescriptor(
|
||||||
|
token_id="tok_gitops",
|
||||||
|
identity="gitops-dispatcher",
|
||||||
|
role=Role.OPERATOR,
|
||||||
|
sha256=OPERATOR_HASH,
|
||||||
|
).model_dump(),
|
||||||
|
]
|
||||||
|
tokens_file.write_text(json.dumps(tokens_data), encoding="utf-8")
|
||||||
|
tokens_file.chmod(0o400)
|
||||||
|
token_store = TokenStore(tokens_file)
|
||||||
|
|
||||||
|
# Audit log
|
||||||
|
audit_file = tmp_path / "audit.jsonl"
|
||||||
|
audit_file.touch()
|
||||||
|
audit_file.chmod(0o600)
|
||||||
|
audit_logger = AuditLogger(audit_file)
|
||||||
|
|
||||||
|
# Locks
|
||||||
|
lock_dir = tmp_path / "locks"
|
||||||
|
lock_dir.mkdir()
|
||||||
|
lock_manager = TargetLockManager(lock_dir)
|
||||||
|
|
||||||
|
# Workloads
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
sites_dir.mkdir()
|
||||||
|
core_dir = tmp_path / "Core"
|
||||||
|
core_dir.mkdir()
|
||||||
|
|
||||||
|
# Admitted workload: docs
|
||||||
|
docs_dir = sites_dir / "docs"
|
||||||
|
docs_dir.mkdir()
|
||||||
|
(docs_dir / "app.yaml").write_text(
|
||||||
|
"name: docs\n"
|
||||||
|
"domain: docs\n"
|
||||||
|
"deployment:\n"
|
||||||
|
" branch: main\n"
|
||||||
|
" actions:\n"
|
||||||
|
" - compose_up\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
(docs_dir / "docker-compose.yml").write_text(
|
||||||
|
"services:\n"
|
||||||
|
" web:\n"
|
||||||
|
" image: nginx:alpine\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Unregistered workload: rogue
|
||||||
|
rogue_dir = sites_dir / "rogue"
|
||||||
|
rogue_dir.mkdir()
|
||||||
|
(rogue_dir / "app.yaml").write_text(
|
||||||
|
"name: rogue\n"
|
||||||
|
"deployment:\n"
|
||||||
|
" branch: main\n"
|
||||||
|
" actions:\n"
|
||||||
|
" - compose_up\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
(rogue_dir / "docker-compose.yml").write_text(
|
||||||
|
"services:\n"
|
||||||
|
" web:\n"
|
||||||
|
" image: alpine:latest\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
# deployments.yaml
|
||||||
|
deployments_file = tmp_path / "deployments.yaml"
|
||||||
|
deployments_file.write_text(
|
||||||
|
'schemaVersion: "1.0"\n'
|
||||||
|
"repositories:\n"
|
||||||
|
" docs:\n"
|
||||||
|
f' path: "{docs_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
router = OperationalRouter(
|
||||||
|
audit_logger=audit_logger,
|
||||||
|
lock_manager=lock_manager,
|
||||||
|
sites_dir=sites_dir,
|
||||||
|
core_dir=core_dir,
|
||||||
|
)
|
||||||
|
|
||||||
|
daemon = AppctlDaemon(
|
||||||
|
router=router,
|
||||||
|
token_store=token_store,
|
||||||
|
audit_logger=audit_logger,
|
||||||
|
lock_manager=lock_manager,
|
||||||
|
socket_path=socket_path,
|
||||||
|
http_host=http_host,
|
||||||
|
http_port=http_port,
|
||||||
|
sites_dir=sites_dir,
|
||||||
|
core_dir=core_dir,
|
||||||
|
deployments_file=deployments_file,
|
||||||
|
)
|
||||||
|
|
||||||
|
daemon.start()
|
||||||
|
|
||||||
|
class Context:
|
||||||
|
def __init__(self):
|
||||||
|
self.daemon = daemon
|
||||||
|
self.socket_path = socket_path
|
||||||
|
self.http_url = f"http://{http_host}:{http_port}"
|
||||||
|
self.sites_dir = sites_dir
|
||||||
|
self.core_dir = core_dir
|
||||||
|
self.audit_file = audit_file
|
||||||
|
self.deployments_file = deployments_file
|
||||||
|
self.docs_dir = docs_dir
|
||||||
|
self.rogue_dir = rogue_dir
|
||||||
|
|
||||||
|
ctx = Context()
|
||||||
|
try:
|
||||||
|
yield ctx
|
||||||
|
finally:
|
||||||
|
daemon.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_health_endpoint(daemon_env):
|
||||||
|
"""GET /v1/health returns HTTP 200 with health metadata over UDS and TCP."""
|
||||||
|
# Over UDS
|
||||||
|
conn_uds = UnixHTTPConnection(str(daemon_env.socket_path))
|
||||||
|
conn_uds.request("GET", "/v1/health")
|
||||||
|
res_uds = conn_uds.getresponse()
|
||||||
|
assert res_uds.status == 200
|
||||||
|
data_uds = json.loads(res_uds.read().decode())
|
||||||
|
assert data_uds["status"] == "healthy"
|
||||||
|
assert data_uds["version"] == "1.0"
|
||||||
|
assert "uptime_seconds" in data_uds
|
||||||
|
conn_uds.close()
|
||||||
|
|
||||||
|
# Over TCP
|
||||||
|
import http.client
|
||||||
|
conn_tcp = http.client.HTTPConnection("127.0.0.1", daemon_env.daemon.http_port)
|
||||||
|
conn_tcp.request("GET", "/v1/health")
|
||||||
|
res_tcp = conn_tcp.getresponse()
|
||||||
|
assert res_tcp.status == 200
|
||||||
|
data_tcp = json.loads(res_tcp.read().decode())
|
||||||
|
assert data_tcp["status"] == "healthy"
|
||||||
|
assert data_tcp["version"] == "1.0"
|
||||||
|
conn_tcp.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_transport_dual_equivalence(daemon_env):
|
||||||
|
"""
|
||||||
|
Compare responses of POST /v1/operations over Unix socket vs HTTP 127.0.0.1.
|
||||||
|
Asserts 100% schema and status parity.
|
||||||
|
"""
|
||||||
|
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
|
||||||
|
|
||||||
|
# 1. Successful query with admin token
|
||||||
|
resp_uds = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=list_req,
|
||||||
|
token=ADMIN_SECRET,
|
||||||
|
)
|
||||||
|
resp_http = send_daemon_request(
|
||||||
|
endpoint=daemon_env.http_url,
|
||||||
|
operation_request=list_req,
|
||||||
|
token=ADMIN_SECRET,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert resp_uds.success is True
|
||||||
|
assert resp_http.success is True
|
||||||
|
assert resp_uds.status == resp_http.status
|
||||||
|
assert resp_uds.operation == resp_http.operation
|
||||||
|
assert resp_uds.version == resp_http.version
|
||||||
|
assert resp_uds.result == resp_http.result
|
||||||
|
|
||||||
|
# 2. Error case parity (404 target not found)
|
||||||
|
get_req = OperationRequest(operation=OperationType.WORKLOAD_GET, target="nonexistent")
|
||||||
|
err_uds = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=get_req,
|
||||||
|
token=ADMIN_SECRET,
|
||||||
|
)
|
||||||
|
err_http = send_daemon_request(
|
||||||
|
endpoint=daemon_env.http_url,
|
||||||
|
operation_request=get_req,
|
||||||
|
token=ADMIN_SECRET,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert err_uds.success is False
|
||||||
|
assert err_http.success is False
|
||||||
|
assert err_uds.error is not None and err_http.error is not None
|
||||||
|
assert err_uds.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
|
||||||
|
assert err_http.error.code == ErrorCode.ERR_TARGET_NOT_FOUND
|
||||||
|
assert err_uds.error.code.http_status == 404
|
||||||
|
assert err_http.error.code.http_status == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_body_size_limit(daemon_env):
|
||||||
|
"""Requests exceeding 64 KiB are rejected with 400 ERR_VALIDATION_FAILED."""
|
||||||
|
oversized_data = {"version": "1.0", "operation": "workload.list", "padding": "x" * (65 * 1024)}
|
||||||
|
body_str = json.dumps(oversized_data)
|
||||||
|
|
||||||
|
conn = UnixHTTPConnection(str(daemon_env.socket_path))
|
||||||
|
headers = {"Content-Type": "application/json", "Host": "localhost"}
|
||||||
|
conn.request("POST", "/v1/operations", body=body_str, headers=headers)
|
||||||
|
res = conn.getresponse()
|
||||||
|
assert res.status == 400
|
||||||
|
data = json.loads(res.read().decode())
|
||||||
|
assert data["status"] == "error"
|
||||||
|
assert data["error"]["code"] == ErrorCode.ERR_VALIDATION_FAILED.value
|
||||||
|
assert "exceeds limit" in data["error"]["message"]
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_auth_missing_token_fails_closed(daemon_env):
|
||||||
|
"""
|
||||||
|
Mutating operations and sensitive reads without Bearer token return 401 ERR_AUTH_REQUIRED
|
||||||
|
and execute zero subprocesses.
|
||||||
|
"""
|
||||||
|
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||||
|
|
||||||
|
with patch("subprocess.run") as mock_subproc:
|
||||||
|
# Over HTTP without token
|
||||||
|
resp_http = send_daemon_request(
|
||||||
|
endpoint=daemon_env.http_url,
|
||||||
|
operation_request=deploy_req,
|
||||||
|
token=None,
|
||||||
|
)
|
||||||
|
assert resp_http.success is False
|
||||||
|
assert resp_http.error is not None
|
||||||
|
assert resp_http.error.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||||
|
assert resp_http.error.code.http_status == 401
|
||||||
|
assert mock_subproc.call_count == 0
|
||||||
|
|
||||||
|
# Over UDS without token (deploy is mutating, peercred viewer fallback must be rejected)
|
||||||
|
resp_uds = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=deploy_req,
|
||||||
|
token=None,
|
||||||
|
)
|
||||||
|
assert resp_uds.success is False
|
||||||
|
assert resp_uds.error is not None
|
||||||
|
assert resp_uds.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||||
|
assert resp_uds.error.code.http_status == 403
|
||||||
|
assert mock_subproc.call_count == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_uds_peercred_viewer_boundary(daemon_env):
|
||||||
|
"""
|
||||||
|
Tokenless UDS call from operator UID succeeds for workload.list (auth_method: unix_peercred),
|
||||||
|
but fails with 403 on mutation or sensitive reads.
|
||||||
|
"""
|
||||||
|
# Read-only query over UDS without token succeeds as viewer
|
||||||
|
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
|
||||||
|
resp = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=list_req,
|
||||||
|
token=None,
|
||||||
|
)
|
||||||
|
assert resp.success is True
|
||||||
|
assert resp.result is not None
|
||||||
|
assert "workloads" in resp.result
|
||||||
|
|
||||||
|
# Sensitive read (workload.config) without token fails
|
||||||
|
config_req = OperationRequest(operation=OperationType.WORKLOAD_CONFIG, target="docs")
|
||||||
|
resp_cfg = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=config_req,
|
||||||
|
token=None,
|
||||||
|
)
|
||||||
|
assert resp_cfg.success is False
|
||||||
|
assert resp_cfg.error is not None
|
||||||
|
assert resp_cfg.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||||
|
assert resp_cfg.error.code.http_status == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_rbac_role_matrix(daemon_env):
|
||||||
|
"""
|
||||||
|
homelab-operator allowed on deployments.yaml workloads but denied on unregistered workloads;
|
||||||
|
homelab-admin allowed on all valid targets.
|
||||||
|
"""
|
||||||
|
deploy_registered = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||||
|
deploy_unregistered = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="rogue")
|
||||||
|
|
||||||
|
with patch("appctl_router.run_bounded_subprocess") as mock_subproc, patch("appctl_router.OperationalRouter._trigger_homepage_sync"):
|
||||||
|
mock_subproc.return_value = (0, "Container docs created", "")
|
||||||
|
|
||||||
|
# Operator on registered target -> SUCCESS
|
||||||
|
resp_op_reg = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=deploy_registered,
|
||||||
|
token=OPERATOR_SECRET,
|
||||||
|
)
|
||||||
|
assert resp_op_reg.success is True
|
||||||
|
assert resp_op_reg.result is not None
|
||||||
|
assert resp_op_reg.result["action"] == "deployed"
|
||||||
|
|
||||||
|
# Operator on unregistered target -> 403 ERR_PERMISSION_DENIED
|
||||||
|
resp_op_unreg = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=deploy_unregistered,
|
||||||
|
token=OPERATOR_SECRET,
|
||||||
|
)
|
||||||
|
assert resp_op_unreg.success is False
|
||||||
|
assert resp_op_unreg.error is not None
|
||||||
|
assert resp_op_unreg.error.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||||
|
assert resp_op_unreg.error.code.http_status == 403
|
||||||
|
|
||||||
|
# Admin on unregistered target -> SUCCESS
|
||||||
|
resp_adm_unreg = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=deploy_unregistered,
|
||||||
|
token=ADMIN_SECRET,
|
||||||
|
)
|
||||||
|
assert resp_adm_unreg.success is True
|
||||||
|
assert resp_adm_unreg.result is not None
|
||||||
|
assert resp_adm_unreg.result["action"] == "deployed"
|
||||||
|
|
||||||
|
|
||||||
|
def test_daemon_preflight_and_dotenv_safety(daemon_env):
|
||||||
|
"""
|
||||||
|
Workload with prohibited Compose directive (privileged: true) is blocked by Compose AST
|
||||||
|
pre-flight before any subprocess runs.
|
||||||
|
"""
|
||||||
|
bad_compose = daemon_env.docs_dir / "docker-compose.yml"
|
||||||
|
bad_compose.write_text(
|
||||||
|
"services:\n"
|
||||||
|
" web:\n"
|
||||||
|
" image: nginx\n"
|
||||||
|
" privileged: true\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||||
|
|
||||||
|
with patch("subprocess.run") as mock_subproc:
|
||||||
|
resp = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=deploy_req,
|
||||||
|
token=ADMIN_SECRET,
|
||||||
|
)
|
||||||
|
assert resp.success is False
|
||||||
|
assert resp.error is not None
|
||||||
|
assert resp.error.code == ErrorCode.ERR_VALIDATION_FAILED
|
||||||
|
assert resp.error.code.http_status == 400
|
||||||
|
assert "privileged: true" in resp.error.message
|
||||||
|
assert mock_subproc.call_count == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_concurrent_mutation_conflict(daemon_env):
|
||||||
|
"""
|
||||||
|
Second concurrent mutation on the same target returns 409 ERR_CONCURRENT_MUTATION.
|
||||||
|
"""
|
||||||
|
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||||
|
|
||||||
|
# Manually hold lock on target
|
||||||
|
lock_ctx = daemon_env.daemon.lock_manager.lock_target("docs")
|
||||||
|
with lock_ctx:
|
||||||
|
resp = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=deploy_req,
|
||||||
|
token=ADMIN_SECRET,
|
||||||
|
)
|
||||||
|
assert resp.success is False
|
||||||
|
assert resp.error is not None
|
||||||
|
assert resp.error.code == ErrorCode.ERR_CONCURRENT_MUTATION
|
||||||
|
assert resp.error.code.http_status == 409
|
||||||
|
|
||||||
|
|
||||||
|
def test_execution_failure_audit(daemon_env):
|
||||||
|
"""
|
||||||
|
Failing Docker subprocess returns 500 ERR_EXECUTION_FAILED and records phase: FAILED.
|
||||||
|
"""
|
||||||
|
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||||
|
|
||||||
|
with patch("appctl_router.run_bounded_subprocess") as mock_subproc:
|
||||||
|
mock_subproc.return_value = (1, "", "Error: docker daemon not reachable")
|
||||||
|
|
||||||
|
resp = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=deploy_req,
|
||||||
|
token=ADMIN_SECRET,
|
||||||
|
)
|
||||||
|
assert resp.success is False
|
||||||
|
assert resp.error is not None
|
||||||
|
assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED
|
||||||
|
assert resp.error.code.http_status == 500
|
||||||
|
|
||||||
|
# Verify audit.jsonl contains FAILED event
|
||||||
|
lines = [json.loads(line) for line in daemon_env.audit_file.read_text().splitlines() if line.strip()]
|
||||||
|
failed_events = [ev for ev in lines if ev.get("phase") == "FAILED"]
|
||||||
|
assert len(failed_events) >= 1
|
||||||
|
assert failed_events[-1]["target"] == "docs"
|
||||||
|
assert failed_events[-1]["result"]["error_code"] == ErrorCode.ERR_EXECUTION_FAILED.value
|
||||||
|
|
||||||
|
|
||||||
|
def test_audit_failure_blocks_mutation(daemon_env):
|
||||||
|
"""
|
||||||
|
Unwritable audit.jsonl aborts mutating command with 500 ERR_EXECUTION_FAILED
|
||||||
|
and zero Docker invocations.
|
||||||
|
"""
|
||||||
|
daemon_env.audit_file.chmod(0o400)
|
||||||
|
deploy_req = OperationRequest(operation=OperationType.WORKLOAD_DEPLOY, target="docs")
|
||||||
|
|
||||||
|
with patch("subprocess.run") as mock_subproc:
|
||||||
|
resp = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=deploy_req,
|
||||||
|
token=ADMIN_SECRET,
|
||||||
|
)
|
||||||
|
assert resp.success is False
|
||||||
|
assert resp.error is not None
|
||||||
|
assert resp.error.code == ErrorCode.ERR_EXECUTION_FAILED
|
||||||
|
assert resp.error.code.http_status == 500
|
||||||
|
assert mock_subproc.call_count == 0
|
||||||
|
|
||||||
|
# Restore write permission for teardown
|
||||||
|
daemon_env.audit_file.chmod(0o600)
|
||||||
|
|
||||||
|
|
||||||
|
def test_daemon_restart_preserves_state(daemon_env):
|
||||||
|
"""
|
||||||
|
Clean stop and restart of daemon unlinks and rebinds socket cleanly.
|
||||||
|
"""
|
||||||
|
daemon_env.daemon.stop()
|
||||||
|
assert not daemon_env.socket_path.exists()
|
||||||
|
|
||||||
|
# Restart
|
||||||
|
daemon_env.daemon.start()
|
||||||
|
assert daemon_env.socket_path.is_socket()
|
||||||
|
|
||||||
|
# Re-verify communication
|
||||||
|
list_req = OperationRequest(operation=OperationType.WORKLOAD_LIST)
|
||||||
|
resp = send_daemon_request(
|
||||||
|
endpoint=daemon_env.socket_path,
|
||||||
|
operation_request=list_req,
|
||||||
|
token=ADMIN_SECRET,
|
||||||
|
)
|
||||||
|
assert resp.success is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_gitops_dispatcher_delegates_to_daemon(daemon_env, monkeypatch):
|
||||||
|
"""
|
||||||
|
When daemon socket is active, gitops_dispatcher calls daemon over UDS with Bearer token.
|
||||||
|
"""
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEFAULT_APPCTL_SOCKET_PATH", daemon_env.socket_path)
|
||||||
|
monkeypatch.setenv("GITOPS_APPCTL_TOKEN", OPERATOR_SECRET)
|
||||||
|
monkeypatch.setenv("APPCTL_SOCKET_PATH", str(daemon_env.socket_path))
|
||||||
|
|
||||||
|
with patch.object(daemon_env.daemon.router, "_op_workload_update") as mock_update:
|
||||||
|
mock_update.return_value = ({"action": "updated", "message": "Updated via daemon"}, "sha12345")
|
||||||
|
|
||||||
|
success = gitops_dispatcher.execute_deployment(
|
||||||
|
target_dir=daemon_env.docs_dir,
|
||||||
|
deployment_config={"branch": "main", "actions": ["git_pull", "compose_up"]},
|
||||||
|
branch="main",
|
||||||
|
)
|
||||||
|
assert success is True
|
||||||
|
assert mock_update.call_count == 1
|
||||||
@@ -26,7 +26,7 @@ x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, an
|
|||||||
x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4
|
x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4
|
||||||
x 2026-10-19 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4
|
x 2026-10-19 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4
|
||||||
x 2026-10-19 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4
|
x 2026-10-19 (B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4
|
||||||
(B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4
|
x 2026-10-19 (B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4
|
||||||
(B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4
|
x 2026-10-19 (B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4
|
||||||
(C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4
|
(C) Re-implement scripts/appctl as a thin UDS HTTP client and declare homelab-appctl.service with POSIX ACLs in nixos/modules/homeserver.nix +cli @p4
|
||||||
(C) Scrub remaining hardcoded domain and username literals across NixOS modules, Compose stack, and config/deployments.yaml and add pyright to flake.nix checks +generic @core
|
(C) Scrub remaining hardcoded domain and username literals across NixOS modules, Compose stack, and config/deployments.yaml and add pyright to flake.nix checks +generic @core
|
||||||
Reference in new issue
Block a user