From 0b5ba58ecf8221fecdcd7e927da07dd40705380a Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 15:34:24 -0500 Subject: [PATCH] fix(cli): restore human-readable tabular output and bash autocompletion Closes #3 --- scripts/appctl | 15 +++- scripts/appctl_cli.py | 139 ++++++++++++++++++++++++++++++- scripts/appctl_router.py | 32 ++++++- tests/unit/test_appctl_cli.py | 115 +++++++++++++++++++++++++ tests/unit/test_appctl_router.py | 45 ++++++++++ 5 files changed, 337 insertions(+), 9 deletions(-) diff --git a/scripts/appctl b/scripts/appctl index 689e6f8..81ba6e7 100755 --- a/scripts/appctl +++ b/scripts/appctl @@ -12,10 +12,17 @@ PYTHON_BIN="${PYTHON_BIN:-python3}" SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}" CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py" -# If daemon Unix domain socket exists, delegate directly to thin client -if [ -S "$SOCKET_PATH" ] && [ -f "$CLI_CLIENT" ]; then - exec "$PYTHON_BIN" "$CLI_CLIENT" "$@" -fi +# If daemon Unix domain socket exists, delegate operational commands directly to thin client +# (fast-path local completion and resolution helpers through appctl_engine.py) +case "${1:-}" in + complete|completion|resolve) + ;; + *) + if [ -S "$SOCKET_PATH" ] && [ -f "$CLI_CLIENT" ]; then + exec "$PYTHON_BIN" "$CLI_CLIENT" "$@" + fi + ;; +esac ENV_FILE="/run/secrets/rendered/traefik-deployments.env" if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then diff --git a/scripts/appctl_cli.py b/scripts/appctl_cli.py index 3bf2d3e..01df017 100755 --- a/scripts/appctl_cli.py +++ b/scripts/appctl_cli.py @@ -48,6 +48,120 @@ def resolve_token(cli_token: str | None = None) -> str | None: return None +def _format_workload_table(workloads: list[dict[str, Any]]) -> str: + """Format a list of workload dictionaries into a human-readable tabular display.""" + if not workloads: + return "ℹ️ No workloads found." + + has_ssl = any("ssl" in w and isinstance(w["ssl"], dict) for w in workloads) + lines: list[str] = [] + + if has_ssl: + lines.append( + f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'CERT':<24} {'DESCRIPTION'}" + ) + lines.append( + f"{'-------':<18} {'----':<14} {'------':<30} {'----':<24} {'-----------'}" + ) + else: + lines.append( + f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'DESCRIPTION'}" + ) + lines.append( + f"{'-------':<18} {'----':<14} {'------':<30} {'-----------'}" + ) + + for w in workloads: + name = str(w.get("name", "-")) + w_type = str(w.get("type", w.get("app_type", "app"))) + domain = str(w.get("domain", "-")) + desc = str(w.get("description", "")) + if w.get("manifest_error"): + desc = f"⚠️ {w['manifest_error']}" + elif w.get("deployment_status"): + desc = f"{w['deployment_status']} ({w.get('provenance_status', '-')})" + + if has_ssl: + ssl_info = w.get("ssl") + cert_status = ( + str(ssl_info.get("status", "-")) + if isinstance(ssl_info, dict) + else "-" + ) + lines.append( + f"{name:<18} {w_type:<14} {domain:<30} {cert_status:<24} {desc}" + ) + else: + lines.append(f"{name:<18} {w_type:<14} {domain:<30} {desc}") + + return "\n".join(lines) + + +def _format_workload_info(workload: dict[str, Any]) -> str: + """Format a single workload metadata dictionary for `appctl info`.""" + name = workload.get("name", "unknown") + w_type = workload.get("type", workload.get("app_type", "app")) + header = ( + f"ℹ️ Core Infrastructure Service: {name}" + if w_type in ("core", "core_service") + else f"ℹ️ Workload Overview: {name}" + ) + lines = [ + header, + "-" * 50, + f"Directory: {workload.get('dir_path', '-')}", + f"Domain: {workload.get('domain', '-')}", + f"Type: {w_type}", + f"Description: {workload.get('description', '-')}", + ] + if workload.get("container"): + lines.append(f"Container: {workload['container']}") + aliases = workload.get("aliases") + if isinstance(aliases, list) and aliases: + lines.append(f"Aliases: {', '.join(str(a) for a in aliases)}") + networks = workload.get("networks") + if isinstance(networks, list) and networks: + lines.append(f"Networks: {', '.join(str(n) for n in networks)}") + if "auth" in workload: + lines.append(f"Auth Protected: {workload['auth']}") + if "visible" in workload: + lines.append(f"Dashboard: {'Visible' if workload['visible'] else 'Hidden'}") + source = workload.get("source") + if isinstance(source, dict): + lines.append(f"Source URL: {source.get('url', '-')}") + lines.append(f"Target Ref: {source.get('ref', '-')}") + if workload.get("manifest_error"): + lines.append(f"\n⚠️ Manifest Validation Error:\n {workload['manifest_error']}") + ssl_info = workload.get("ssl") + if isinstance(ssl_info, dict): + lines.append("\n🔒 SSL/TLS Certificate:") + lines.append(f" Status: {ssl_info.get('status', '-')}") + lines.append(f" Issuer: {ssl_info.get('issuer', '-')}") + lines.append(f" Expiration: {ssl_info.get('formatted_expiry', '-')}") + return "\n".join(lines) + + +def _format_ssl_info(ssl_info: dict[str, Any]) -> str: + """Format SSL certificate details for `appctl ssl`.""" + domain = ssl_info.get("domain", "-") + lines = [ + f"🔒 SSL/TLS Certificate: {domain}", + "-" * 50, + f"Domain: {domain}", + f"Status: {ssl_info.get('status', '-')}", + f"Issuer: {ssl_info.get('issuer', '-')}", + f"Subject: {ssl_info.get('subject', '-')}", + f"Expiration: {ssl_info.get('not_after', '-')}", + ] + if ssl_info.get("days_remaining") is not None: + lines.append( + f"Days Remaining: {ssl_info['days_remaining']} days ({ssl_info.get('formatted_expiry', '-')})" + ) + if ssl_info.get("error"): + lines.append(f"Details/Error: {ssl_info['error']}") + return "\n".join(lines) + + def format_response(resp: OperationResponse, raw_json: bool = False) -> str: """Format an OperationResponse for human-friendly terminal display or JSON output.""" if raw_json: @@ -63,6 +177,14 @@ def format_response(resp: OperationResponse, raw_json: bool = False) -> str: return resp.output if resp.result: + if "workloads" in resp.result and isinstance(resp.result["workloads"], list): + return _format_workload_table(resp.result["workloads"]) + if resp.operation == OperationType.WORKLOAD_RESOLVE and "workload" in resp.result: + return json.dumps(resp.result["workload"]) + if "workload" in resp.result and isinstance(resp.result["workload"], dict): + return _format_workload_info(resp.result["workload"]) + if "ssl" in resp.result and isinstance(resp.result["ssl"], dict): + return _format_ssl_info(resp.result["ssl"]) if "message" in resp.result and len(resp.result) <= 3: return f"✨ {resp.result['message']}" return json.dumps(resp.result, indent=2) @@ -101,14 +223,18 @@ def run_cli(argv: list[str] | None = None) -> int: # list / status list_p = subparsers.add_parser("list", aliases=["status"], parents=[common_parser], help="List workloads") - list_p.add_argument("--core", action="store_true", help="Include core platform services") - list_p.add_argument("--fetch", action="store_true", help="Fetch remote git revisions") - list_p.add_argument("--ssl", action="store_true", help="Check SSL certificate status") + list_p.add_argument("--core", "-c", "--all", "-a", action="store_true", dest="core", help="Include core platform services") + list_p.add_argument("--fetch", "-f", action="store_true", help="Fetch remote git revisions") + list_p.add_argument("--ssl", "-s", action="store_true", help="Check SSL certificate status") # info info_p = subparsers.add_parser("info", parents=[common_parser], help="Get workload metadata") info_p.add_argument("target", help="Workload name") - info_p.add_argument("--ssl", action="store_true", help="Check SSL certificate status") + info_p.add_argument("--ssl", "-s", action="store_true", help="Check SSL certificate status") + + # resolve + resolve_p = subparsers.add_parser("resolve", parents=[common_parser], help="Resolve target metadata") + resolve_p.add_argument("target", help="Workload or core target") # ssl ssl_p = subparsers.add_parser("ssl", parents=[common_parser], help="Inspect platform SSL certificates") @@ -177,6 +303,11 @@ def run_cli(argv: list[str] | None = None) -> int: target=parsed.target, parameters={"ssl": getattr(parsed, "ssl", False)}, ) + elif cmd == "resolve": + op_req = OperationRequest( + operation=OperationType.WORKLOAD_RESOLVE, + target=parsed.target, + ) elif cmd == "ssl": op_req = OperationRequest( operation=OperationType.PLATFORM_SSL, diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 4f8c2bf..2b51e21 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -62,6 +62,7 @@ from appctl_engine import ( from appctl_engine import ( check_ssl_cert, cmd_sync_homepage, + get_core_services, get_sites_apps, resolve_app, ) @@ -73,6 +74,7 @@ from core_manifest import ( parse_manifest, ) from gitops_dispatcher import validate_compose_security +from provenance import inspect_workload_two_axis MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation @@ -660,7 +662,33 @@ class OperationalRouter: params = request.parse_parameters() assert isinstance(params, ListParams) apps = get_sites_apps(sites_dir=str(self.sites_dir)) - apps_data = [a.to_dict() for a in apps] + apps_data: list[dict[str, Any]] = [] + + for app in apps: + item = app.to_dict() + app_path = Path(app.dir_path) + if params.fetch: + manifest_obj = app.manifest_obj or Manifest( + name=app.name, domain=app.domain + ) + two_axis = inspect_workload_two_axis( + app_dir=app_path, + manifest=manifest_obj, + fetch_upstream=True, + ) + item["deployment_status"] = two_axis.checkout.status_label + item["provenance_status"] = two_axis.provenance.status.value + if params.ssl and not app.is_internal: + item["ssl"] = check_ssl_cert(app.domain) + apps_data.append(item) + + if params.core: + for svc in get_core_services(core_dir=str(self.core_dir)): + svc_dict = svc.to_dict() + if params.ssl and not svc.is_internal: + svc_dict["ssl"] = check_ssl_cert(svc.domain) + apps_data.append(svc_dict) + return { "total": len(apps_data), "workloads": apps_data, @@ -671,6 +699,8 @@ class OperationalRouter: params = request.parse_parameters() assert isinstance(params, GetParams) data = app.to_dict() + if params.ssl and not getattr(app, "is_internal", True): + data["ssl"] = check_ssl_cert(app.domain) return {"workload": data, "message": f"Retrieved metadata for {app.name}"} def _op_workload_resolve(self, app: Any) -> dict[str, Any]: diff --git a/tests/unit/test_appctl_cli.py b/tests/unit/test_appctl_cli.py index 8093190..48d022d 100644 --- a/tests/unit/test_appctl_cli.py +++ b/tests/unit/test_appctl_cli.py @@ -113,3 +113,118 @@ def test_cli_handles_missing_socket(): ret = run_cli(["list", "--socket", "/nonexistent/appctl.sock"]) assert ret == 1 assert "socket not found" in mock_stderr.getvalue() + + +def test_cli_format_response_renders_workload_list_table(): + """Ensure workload.list renders a human-readable table instead of suppressing it behind result['message'].""" + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_list_01", + operation=OperationType.WORKLOAD_LIST, + result={ + "total": 2, + "workloads": [ + { + "name": "snappymail", + "type": "app", + "domain": "mail.example.test", + "description": "Webmail client", + }, + { + "name": "traefik", + "type": "core_service", + "domain": "traefik.example.test", + "description": "Edge Reverse Proxy", + }, + ], + "message": "Found 2 workloads", + }, + output="", + ) + rendered = format_response(resp, raw_json=False) + assert "SERVICE" in rendered + assert "DOMAIN" in rendered + assert "snappymail" in rendered + assert "mail.example.test" in rendered + assert "traefik" in rendered + assert "Edge Reverse Proxy" in rendered + assert "✨ Found 2 workloads" not in rendered + + +def test_cli_format_response_renders_workload_get_info(): + """Ensure workload.get (appctl info) renders structured workload metadata.""" + resp = OperationResponse( + version="1.0", + success=True, + operation_id="op_get_01", + operation=OperationType.WORKLOAD_GET, + target="snappymail", + result={ + "workload": { + "name": "snappymail", + "type": "app", + "dir_path": "/home/operator/Sites/snappymail", + "domain": "mail.example.test", + "description": "Lightweight Webmail", + "aliases": ["webmail", "mail"], + "networks": ["proxy-net"], + "auth": True, + "visible": True, + }, + "message": "Retrieved metadata for snappymail", + }, + output="", + ) + rendered = format_response(resp, raw_json=False) + assert "Workload Overview: snappymail" in rendered + assert "/home/operator/Sites/snappymail" in rendered + assert "mail.example.test" in rendered + assert "webmail, mail" in rendered + assert "✨ Retrieved metadata" not in rendered + + +def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, monkeypatch): + """Ensure scripts/appctl executes `complete` and `completion` via appctl_engine.py even when socket exists.""" + import os + import shutil + import socket as std_socket + import subprocess + import sys + + bash_bin = shutil.which("bash") or "bash" + sock_path = tmp_path / "appctl.sock" + srv = std_socket.socket(std_socket.AF_UNIX, std_socket.SOCK_STREAM) + srv.bind(str(sock_path)) + try: + appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl" + env = { + "PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"), + "PYTHON_BIN": sys.executable, + "HOMELAB_DOMAIN": "example.test", + "APPCTL_SOCKET_PATH": str(sock_path), + "SITES_DIR": str(tmp_path), + } + res_comp = subprocess.run( + [bash_bin, str(appctl_script), "completion", "bash"], + env=env, + capture_output=True, + text=True, + check=False, + ) + assert res_comp.returncode == 0 + assert "_appctl_completions()" in res_comp.stdout + + res_words = subprocess.run( + [bash_bin, str(appctl_script), "complete", "services"], + env=env, + capture_output=True, + text=True, + check=False, + ) + assert res_words.returncode == 0 + assert "traefik" in res_words.stdout + assert "core" in res_words.stdout + finally: + srv.close() + diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 0ad7536..2199243 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -768,3 +768,48 @@ def test_operational_router_rejects_operator_role_on_core_targets( assert resp.error is not None assert resp.error.code == ErrorCode.ERR_PERMISSION_DENIED + +def test_operational_router_workload_list_honors_filter_params( + tmp_path: Path, + viewer_principal: Principal, + mock_workload_dir: Path, + mock_core_dir: Path, +): + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=mock_workload_dir.parent, + core_dir=mock_core_dir, + ) + + # Without --core: only Sites workloads (1) + resp_sites = router.dispatch( + OperationRequest.model_validate({ + "operation": "workload.list", + "parameters": {"core": False, "fetch": False, "ssl": False}, + }), + viewer_principal, + ) + assert resp_sites.success is True + assert resp_sites.result is not None + assert resp_sites.result["total"] == 1 + assert resp_sites.result["workloads"][0]["name"] == "snappymail" + + # With --core and --ssl: includes Core services and SSL inspection + with patch("appctl_router.check_ssl_cert", return_value={"status": "🟢 80d remaining", "domain": "example.test"}) as mock_ssl: + resp_core = router.dispatch( + OperationRequest.model_validate({ + "operation": "workload.list", + "parameters": {"core": True, "fetch": False, "ssl": True}, + }), + viewer_principal, + ) + assert resp_core.success is True + assert resp_core.result is not None + names = {w["name"] for w in resp_core.result["workloads"]} + assert "snappymail" in names + assert "traefik" in names + assert "authelia" in names + assert mock_ssl.call_count >= 1 + +