fix(cli): enforce fail-closed daemon socket check and remove legacy Bash fallback
- Remove 312 lines of legacy Bash orchestration fallback in scripts/appctl - Fail closed with exit code 1 and actionable diagnostic error on stderr when socket is absent - Retain fast-path local shell completion handlers (complete, completion) - Auto-detect .venv Python interpreter when PYTHON_BIN is unset - Migrate test_appctl_env_injection_resilience to test production P4 environment assembly - Add unit tests for missing socket and offline completion in test_appctl_cli.py - Mark item completed in todo.txt Closes #9 Refs #9
This commit is contained in:
1 parent
c86faa8397
commit
7c1b9b75c5
4 files changed
+136
-335
No files matched your search
+15
-303
@@ -1,189 +1,26 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
# appctl - Unified, Manifest-Driven Container Orchestrator
|
# appctl - Unified, Manifest-Driven Container Orchestrator
|
||||||
# Discovers individual application repositories located in ~/Sites/*/
|
# Thin CLI wrapper delegating operational commands to homelab-appctl.service over UDS
|
||||||
# Injects global homelab secrets, per-app metadata from app.yaml, and monitors Git sync
|
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
ENGINE="$SCRIPT_DIR/appctl_engine.py"
|
ENGINE="$SCRIPT_DIR/appctl_engine.py"
|
||||||
PYTHON_BIN="${PYTHON_BIN:-python3}"
|
if [ -z "$PYTHON_BIN" ]; then
|
||||||
|
if [ -x "$SCRIPT_DIR/../.venv/bin/python3" ]; then
|
||||||
|
PYTHON_BIN="$SCRIPT_DIR/../.venv/bin/python3"
|
||||||
|
else
|
||||||
|
PYTHON_BIN="python3"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}"
|
SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}"
|
||||||
CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py"
|
CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py"
|
||||||
|
|
||||||
# If daemon Unix domain socket exists, delegate operational commands directly to thin client
|
# Fast-path local shell completion helpers
|
||||||
# (fast-path local completion and resolution helpers through appctl_engine.py)
|
|
||||||
case "${1:-}" in
|
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
|
|
||||||
ENV_FILE="/run/secrets/traefik-deployments.env"
|
|
||||||
fi
|
|
||||||
export SITES_DIR="${SITES_DIR:-$HOME/Sites}"
|
|
||||||
export CORE_DIR="${CORE_DIR:-$HOME/Core}"
|
|
||||||
export ENV_FILE
|
|
||||||
|
|
||||||
# Source global secrets/environment if available
|
|
||||||
HOMESERVER_ENV="/run/secrets/rendered/homeserver.env"
|
|
||||||
if [ ! -f "$HOMESERVER_ENV" ] && [ -f "/run/secrets/homeserver.env" ]; then
|
|
||||||
HOMESERVER_ENV="/run/secrets/homeserver.env"
|
|
||||||
fi
|
|
||||||
if [ -f "$HOMESERVER_ENV" ]; then
|
|
||||||
set -a
|
|
||||||
# shellcheck disable=SC1090
|
|
||||||
source "$HOMESERVER_ENV"
|
|
||||||
set +a
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -f "$ENV_FILE" ]; then
|
|
||||||
set -a
|
|
||||||
# shellcheck disable=SC1090
|
|
||||||
source "$ENV_FILE"
|
|
||||||
set +a
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Lock the homelab root domain before setup_app_env can mutate $DOMAIN
|
|
||||||
# Canonical precedence: HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN
|
|
||||||
export HOMELAB_DOMAIN="${HOMELAB_DOMAIN:-${DOMAIN_SUFFIX:-${DOMAIN:-}}}"
|
|
||||||
|
|
||||||
# Show help usage
|
|
||||||
show_help() {
|
|
||||||
echo "🚀 appctl - Homelab Container Orchestrator"
|
|
||||||
echo ""
|
|
||||||
echo "Usage: appctl <command> [service] [options...]"
|
|
||||||
echo ""
|
|
||||||
echo "Commands:"
|
|
||||||
echo " list, status [--fetch] [--core] [--ssl] List all applications with Git sync & container status"
|
|
||||||
echo " ssl [service] Inspect SSL/TLS certificates across homelab domains"
|
|
||||||
echo " info <service> [--ssl] Display comprehensive application & Git diagnostics"
|
|
||||||
echo " up <service|core> Start/build a service stack or Core component"
|
|
||||||
echo " down <service|core> Stop and remove a service stack or Core component"
|
|
||||||
echo " restart <service|core> Restart a service stack, Core component, or entire Core"
|
|
||||||
echo " update <service> Full stack update (git pull -> compose pull -> recreate)"
|
|
||||||
echo " pull <service|core> Pull latest images and recreate service or Core component"
|
|
||||||
echo " logs <service|core> Stream service or Core component logs"
|
|
||||||
echo " config <service|core> Validate and view resolved compose configuration"
|
|
||||||
echo " sync Synchronize Homepage dashboard services.yaml from app.yaml"
|
|
||||||
echo " completion [bash] Output shell autocompletion script"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Setup application environment based on resolved metadata
|
|
||||||
setup_app_env() {
|
|
||||||
local query="$1"
|
|
||||||
local resolved_json
|
|
||||||
resolved_json=$("$PYTHON_BIN" "$ENGINE" resolve "$query" || true)
|
|
||||||
|
|
||||||
if [ -z "$resolved_json" ]; then
|
|
||||||
echo "❌ Error: Service '$query' not found under $SITES_DIR or Core"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Extract fields via python json
|
|
||||||
TARGET_TYPE=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('type', 'app'))" "$resolved_json")
|
|
||||||
APP_DIR=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json")
|
|
||||||
CANONICAL_NAME=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json")
|
|
||||||
TARGET_CONTAINER=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('container', ''))" "$resolved_json")
|
|
||||||
|
|
||||||
if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then
|
|
||||||
if [ ! -d "$CORE_DIR" ]; then
|
|
||||||
echo "❌ Error: Core directory not found at $CORE_DIR"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
CORE_ENV_FILE="/run/secrets/rendered/homeserver.env"
|
|
||||||
if [ ! -f "$CORE_ENV_FILE" ] && [ -f "/run/secrets/homeserver.env" ]; then
|
|
||||||
CORE_ENV_FILE="/run/secrets/homeserver.env"
|
|
||||||
fi
|
|
||||||
COMPOSE_ENV_ARG=()
|
|
||||||
if [ -f "$CORE_ENV_FILE" ]; then
|
|
||||||
COMPOSE_ENV_ARG=(--env-file "$CORE_ENV_FILE")
|
|
||||||
fi
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
RESOLVED_DOMAIN=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['domain'])" "$resolved_json")
|
|
||||||
|
|
||||||
# 1. Base infrastructure defaults
|
|
||||||
export PROXY_NETWORK="${PROXY_NETWORK:-proxy-net}"
|
|
||||||
export NETWORK_NAME="${NETWORK_NAME:-$PROXY_NETWORK}"
|
|
||||||
export CERT_RESOLVER="${CERT_RESOLVER:-myresolver}"
|
|
||||||
export DOMAIN_SUFFIX="${DOMAIN_SUFFIX:-$HOMELAB_DOMAIN}"
|
|
||||||
|
|
||||||
# 2. Canonical application identity
|
|
||||||
export SERVICE_NAME="$CANONICAL_NAME"
|
|
||||||
export CONTAINER_NAME="$CANONICAL_NAME"
|
|
||||||
export SERVICE_DOMAIN="$RESOLVED_DOMAIN"
|
|
||||||
export DOMAIN="$RESOLVED_DOMAIN"
|
|
||||||
|
|
||||||
# 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.)
|
|
||||||
while IFS= read -r -d '' k && IFS= read -r -d '' v; do
|
|
||||||
export "$k=$v"
|
|
||||||
done < <("$PYTHON_BIN" -c "
|
|
||||||
import json, re, sys
|
|
||||||
RESERVED = {'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}
|
|
||||||
d = json.loads(sys.argv[1])
|
|
||||||
env_dict = d.get('env', {})
|
|
||||||
if isinstance(env_dict, dict):
|
|
||||||
for k, v in env_dict.items():
|
|
||||||
k_str = str(k).strip()
|
|
||||||
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', k_str) or k_str in RESERVED:
|
|
||||||
continue
|
|
||||||
if v is not None and v != '':
|
|
||||||
sys.stdout.buffer.write(k_str.encode('utf-8') + b'\0' + str(v).encode('utf-8') + b'\0')
|
|
||||||
" "$resolved_json")
|
|
||||||
|
|
||||||
# 4. Source local .env if present
|
|
||||||
if [ -f "$APP_DIR/.env" ]; then
|
|
||||||
set -a
|
|
||||||
# shellcheck disable=SC1090
|
|
||||||
source "$APP_DIR/.env"
|
|
||||||
set +a
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 5. Source local app.env if present
|
|
||||||
if [ -f "$APP_DIR/app.env" ]; then
|
|
||||||
set -a
|
|
||||||
# shellcheck disable=SC1090
|
|
||||||
source "$APP_DIR/app.env"
|
|
||||||
set +a
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
if [ $# -lt 1 ]; then
|
|
||||||
show_help
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
COMMAND=$1
|
|
||||||
APP=$2
|
|
||||||
|
|
||||||
case "$COMMAND" in
|
|
||||||
list|status)
|
|
||||||
"$PYTHON_BIN" "$ENGINE" list "${@:2}"
|
|
||||||
;;
|
|
||||||
ssl)
|
|
||||||
"$PYTHON_BIN" "$ENGINE" ssl "${@:2}"
|
|
||||||
;;
|
|
||||||
info)
|
|
||||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
|
||||||
"$PYTHON_BIN" "$ENGINE" info "${@:2}"
|
|
||||||
;;
|
|
||||||
sync)
|
|
||||||
"$PYTHON_BIN" "$ENGINE" sync "${@:2}"
|
|
||||||
;;
|
|
||||||
complete)
|
complete)
|
||||||
"$PYTHON_BIN" "$ENGINE" complete "${@:2}"
|
exec "$PYTHON_BIN" "$ENGINE" complete "${@:2}"
|
||||||
;;
|
|
||||||
resolve)
|
|
||||||
"$PYTHON_BIN" "$ENGINE" resolve "${@:2}"
|
|
||||||
;;
|
;;
|
||||||
completion)
|
completion)
|
||||||
cat <<'EOF'
|
cat <<'EOF'
|
||||||
@@ -199,7 +36,7 @@ _appctl_completions() {
|
|||||||
cword=$COMP_CWORD
|
cword=$COMP_CWORD
|
||||||
fi
|
fi
|
||||||
|
|
||||||
local commands="list status ssl info up down restart update pull logs config sync completion"
|
local commands="list status ssl info up down restart update pull logs config sync health resolve completion"
|
||||||
|
|
||||||
if [ "$cword" -eq 1 ]; then
|
if [ "$cword" -eq 1 ]; then
|
||||||
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
|
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
|
||||||
@@ -245,138 +82,13 @@ _appctl_completions() {
|
|||||||
}
|
}
|
||||||
complete -F _appctl_completions appctl
|
complete -F _appctl_completions appctl
|
||||||
EOF
|
EOF
|
||||||
;;
|
|
||||||
up)
|
|
||||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
|
||||||
setup_app_env "$APP"
|
|
||||||
if [ "$TARGET_TYPE" = "core" ]; then
|
|
||||||
echo "🚀 Starting Core stack ($CORE_DIR)..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "${@:3}"
|
|
||||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
|
||||||
echo "🚀 Starting Core service: $TARGET_CONTAINER ($CORE_DIR)..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "$TARGET_CONTAINER" "${@:3}"
|
|
||||||
else
|
|
||||||
echo "🚀 Starting $CANONICAL_NAME ($APP_DIR)..."
|
|
||||||
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
|
|
||||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
down)
|
|
||||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
|
||||||
setup_app_env "$APP"
|
|
||||||
if [ "$TARGET_TYPE" = "core" ]; then
|
|
||||||
echo "🛑 Stopping Core stack ($CORE_DIR)..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" down "${@:3}"
|
|
||||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
|
||||||
echo "🛑 Stopping Core service: $TARGET_CONTAINER ($CORE_DIR)..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" stop "$TARGET_CONTAINER" "${@:3}"
|
|
||||||
else
|
|
||||||
echo "🛑 Stopping $CANONICAL_NAME ($APP_DIR)..."
|
|
||||||
cd "$APP_DIR" && docker compose down "${@:3}"
|
|
||||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
restart)
|
|
||||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
|
||||||
setup_app_env "$APP"
|
|
||||||
if [ "$TARGET_TYPE" = "core" ]; then
|
|
||||||
if [ -n "$3" ] && [[ "$3" != -* ]]; then
|
|
||||||
echo "🔄 Restarting Core service: $3 ($CORE_DIR)..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "$3" "${@:4}"
|
|
||||||
else
|
|
||||||
echo "🔄 Restarting Core stack ($CORE_DIR)..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "${@:3}"
|
|
||||||
fi
|
|
||||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
|
||||||
echo "🔄 Restarting Core service: $TARGET_CONTAINER ($CORE_DIR)..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "$TARGET_CONTAINER" "${@:3}"
|
|
||||||
else
|
|
||||||
echo "🔄 Restarting $CANONICAL_NAME ($APP_DIR)..."
|
|
||||||
cd "$APP_DIR" && docker compose down && docker compose up -d "${@:3}"
|
|
||||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
update)
|
|
||||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
|
||||||
setup_app_env "$APP"
|
|
||||||
if [ "$TARGET_TYPE" = "core" ]; then
|
|
||||||
echo "🔄 Updating Core stack ($CORE_DIR)..."
|
|
||||||
if [ -d "$CORE_DIR/.git" ]; then
|
|
||||||
if [ -n "$(git -C "$CORE_DIR" status --porcelain)" ]; then
|
|
||||||
echo "❌ Error: Cannot update. Working tree in $CORE_DIR has uncommitted changes."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "📥 Pulling latest git changes for Core..."
|
|
||||||
git -C "$CORE_DIR" pull --ff-only
|
|
||||||
fi
|
|
||||||
echo "🐳 Pulling latest Core container images..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull
|
|
||||||
echo "🚀 Recreating Core container stack..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "${@:3}"
|
|
||||||
echo "✨ Core successfully updated!"
|
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
|
||||||
|
|
||||||
echo "🔄 Updating $CANONICAL_NAME ($APP_DIR)..."
|
|
||||||
if [ -d "$APP_DIR/.git" ]; then
|
|
||||||
if [ -n "$(git -C "$APP_DIR" status --porcelain)" ]; then
|
|
||||||
echo "❌ Error: Cannot update. Working tree in $APP_DIR has uncommitted changes."
|
|
||||||
echo "Commit or stash your changes before updating."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "📥 Pulling latest git changes..."
|
|
||||||
git -C "$APP_DIR" pull --ff-only
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "🐳 Pulling latest container images..."
|
|
||||||
cd "$APP_DIR" && docker compose pull
|
|
||||||
|
|
||||||
echo "🚀 Recreating container stack..."
|
|
||||||
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
|
|
||||||
|
|
||||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
|
||||||
echo "✨ $CANONICAL_NAME successfully updated!"
|
|
||||||
;;
|
|
||||||
pull)
|
|
||||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
|
||||||
setup_app_env "$APP"
|
|
||||||
if [ "$TARGET_TYPE" = "core" ]; then
|
|
||||||
echo "📥 Pulling latest images for Core stack..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull "${@:3}"
|
|
||||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
|
||||||
echo "📥 Pulling latest image for Core service: $TARGET_CONTAINER..."
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull "$TARGET_CONTAINER" "${@:3}"
|
|
||||||
else
|
|
||||||
echo "📥 Pulling latest images for $CANONICAL_NAME..."
|
|
||||||
cd "$APP_DIR" && docker compose pull && docker compose up -d --remove-orphans "${@:3}"
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
logs)
|
|
||||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
|
||||||
setup_app_env "$APP"
|
|
||||||
if [ "$TARGET_TYPE" = "core" ]; then
|
|
||||||
if [ -n "$3" ] && [[ "$3" != -* ]]; then
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "$3" "${@:4}"
|
|
||||||
else
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "${@:3}"
|
|
||||||
fi
|
|
||||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "$TARGET_CONTAINER" "${@:3}"
|
|
||||||
else
|
|
||||||
cd "$APP_DIR" && docker compose logs -f "${@:3}"
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
config)
|
|
||||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
|
||||||
setup_app_env "$APP"
|
|
||||||
if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then
|
|
||||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" config "${@:3}"
|
|
||||||
else
|
|
||||||
cd "$APP_DIR" && docker compose config "${@:3}"
|
|
||||||
fi
|
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
show_help
|
if [ ! -S "$SOCKET_PATH" ]; then
|
||||||
|
echo "❌ Error: appctl daemon socket not found at $SOCKET_PATH. Ensure homelab-appctl.service is running." >&2
|
||||||
exit 1
|
exit 1
|
||||||
|
fi
|
||||||
|
exec "$PYTHON_BIN" "$CLI_CLIENT" "$@"
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
@@ -4,11 +4,14 @@ Security invariant tests for Docker Compose and container isolation.
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import yaml
|
import yaml
|
||||||
|
from appctl_audit import AuditLogger, TargetLockManager
|
||||||
|
from appctl_auth import Principal, Role
|
||||||
|
from appctl_contracts import OperationRequest
|
||||||
|
from appctl_router import OperationalRouter, assemble_workload_env
|
||||||
|
from core_manifest import parse_manifest
|
||||||
|
|
||||||
# Comment-out reason: testing pyproject-level pythonpath definition
|
# Comment-out reason: testing pyproject-level pythonpath definition
|
||||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
@@ -101,10 +104,9 @@ def test_no_eval_in_appctl_script():
|
|||||||
assert "eval " not in content, "Dangerous 'eval' detected in scripts/appctl!"
|
assert "eval " not in content, "Dangerous 'eval' detected in scripts/appctl!"
|
||||||
|
|
||||||
|
|
||||||
def test_appctl_env_injection_resilience(tmp_path: Path):
|
def test_appctl_env_injection_resilience(tmp_path: Path, monkeypatch):
|
||||||
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution
|
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution
|
||||||
|
during P4 production environment assembly and router dispatch. Executes OperationalRouter with a mock docker binary.
|
||||||
in scripts/appctl during environment setup. Executes scripts/appctl directly with a mock docker binary.
|
|
||||||
"""
|
"""
|
||||||
canary = tmp_path / "pwned.txt"
|
canary = tmp_path / "pwned.txt"
|
||||||
payload = f"$(touch {canary})"
|
payload = f"$(touch {canary})"
|
||||||
@@ -127,14 +129,22 @@ env:
|
|||||||
"services:\n web:\n image: nginx\n", encoding="utf-8"
|
"services:\n web:\n image: nginx\n", encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 2. Setup mock docker binary to capture environment without requiring a running Docker daemon
|
# 2. Verify unit-level pure Python environment assembly
|
||||||
|
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
|
||||||
|
manifest = parse_manifest(app_dir / "app.yaml")
|
||||||
|
assembled_env = assemble_workload_env(app_dir, manifest, "vuln-app")
|
||||||
|
assert not canary.exists(), "Command substitution executed during assemble_workload_env!"
|
||||||
|
assert assembled_env["INJECTION_TEST"] == payload
|
||||||
|
assert assembled_env["NORMAL_VAR"] == "safe_value"
|
||||||
|
|
||||||
|
# 3. Setup mock docker binary to capture environment without requiring a running Docker daemon
|
||||||
mock_bin = tmp_path / "bin"
|
mock_bin = tmp_path / "bin"
|
||||||
mock_bin.mkdir()
|
mock_bin.mkdir()
|
||||||
mock_docker = mock_bin / "docker"
|
mock_docker = mock_bin / "docker"
|
||||||
bash_bin = shutil.which("bash") or "bash"
|
bash_bin = shutil.which("bash") or "bash"
|
||||||
|
|
||||||
mock_docker_script = f"""#!{bash_bin}
|
mock_docker_script = f"""#!{bash_bin}
|
||||||
if [ "$1" = "compose" ] && [ "$2" = "config" ]; then
|
if [ "$1" = "compose" ] && [ "$4" = "config" ]; then
|
||||||
echo "MOCK_DOCKER_COMPOSE_CONFIG"
|
echo "MOCK_DOCKER_COMPOSE_CONFIG"
|
||||||
echo "CAPTURED_INJECTION=$INJECTION_TEST"
|
echo "CAPTURED_INJECTION=$INJECTION_TEST"
|
||||||
echo "CAPTURED_NORMAL=$NORMAL_VAR"
|
echo "CAPTURED_NORMAL=$NORMAL_VAR"
|
||||||
@@ -145,36 +155,39 @@ exit 0
|
|||||||
mock_docker.write_text(mock_docker_script, encoding="utf-8")
|
mock_docker.write_text(mock_docker_script, encoding="utf-8")
|
||||||
mock_docker.chmod(0o755)
|
mock_docker.chmod(0o755)
|
||||||
|
|
||||||
# 3. Execute scripts/appctl config vuln-app directly
|
# 4. Dispatch workload.config through OperationalRouter
|
||||||
appctl_path = CORE_ROOT / "scripts" / "appctl"
|
monkeypatch.setenv("PATH", f"{mock_bin}:{os.environ.get('PATH', '')}")
|
||||||
env = os.environ.copy()
|
router = OperationalRouter(
|
||||||
if "NIX_PYTHONPATH" in env and "PYTHONPATH" not in env:
|
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||||
env["PYTHONPATH"] = env["NIX_PYTHONPATH"]
|
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||||
env["PATH"] = f"{mock_bin}:{Path(sys.executable).parent}:{env['PATH']}"
|
sites_dir=sites_dir,
|
||||||
env["PYTHON_BIN"] = sys.executable
|
core_dir=CORE_ROOT,
|
||||||
env["SITES_DIR"] = str(sites_dir)
|
)
|
||||||
env["HOMELAB_DOMAIN"] = "example.test"
|
req = OperationRequest.model_validate({
|
||||||
env["CORE_DIR"] = str(CORE_ROOT)
|
"operation": "workload.config",
|
||||||
|
"target": "vuln-app",
|
||||||
res = subprocess.run(
|
})
|
||||||
[bash_bin, str(appctl_path), "config", "vuln-app"],
|
admin_principal = Principal(
|
||||||
env=env,
|
identity="operator",
|
||||||
capture_output=True,
|
role=Role.ADMIN,
|
||||||
text=True,
|
token_id="tok_admin",
|
||||||
check=False,
|
auth_method="bearer_token",
|
||||||
)
|
)
|
||||||
|
|
||||||
# 4. Assertions: command substitution was not executed, script ran, and mock docker received literal value
|
resp = router.dispatch(req, admin_principal)
|
||||||
|
|
||||||
|
# 5. Assertions: command substitution was not executed, router succeeded, mock docker received literal value
|
||||||
assert not canary.exists(), (
|
assert not canary.exists(), (
|
||||||
"Command substitution was executed on the host during environment setup!"
|
"Command substitution was executed on the host during environment setup!"
|
||||||
)
|
)
|
||||||
assert res.returncode == 0, (
|
assert resp.success is True, (
|
||||||
f"appctl config failed: {res.stderr}\nStdout: {res.stdout}"
|
f"OperationalRouter dispatch failed: {resp.error}"
|
||||||
)
|
)
|
||||||
assert "MOCK_DOCKER_COMPOSE_CONFIG" in res.stdout
|
assert resp.result is not None
|
||||||
assert f"CAPTURED_INJECTION={payload}" in res.stdout
|
output = resp.result.get("output", "")
|
||||||
assert "CAPTURED_NORMAL=safe_value" in res.stdout
|
assert "MOCK_DOCKER_COMPOSE_CONFIG" in output
|
||||||
assert "/dangerous/override" not in res.stdout
|
assert f"CAPTURED_INJECTION={payload}" in output
|
||||||
|
assert "CAPTURED_NORMAL=safe_value" in output
|
||||||
|
|
||||||
|
|
||||||
def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests():
|
def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests():
|
||||||
|
|||||||
@@ -360,3 +360,79 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path,
|
|||||||
finally:
|
finally:
|
||||||
srv.close()
|
srv.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_appctl_wrapper_fails_closed_when_socket_is_missing(tmp_path: Path):
|
||||||
|
"""Ensure scripts/appctl fails closed with exit code 1 and diagnostic stderr when socket is missing."""
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
bash_bin = shutil.which("bash") or "bash"
|
||||||
|
non_existent_sock = tmp_path / "missing_appctl.sock"
|
||||||
|
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(non_existent_sock),
|
||||||
|
"SITES_DIR": str(tmp_path),
|
||||||
|
}
|
||||||
|
if "PYTHONPATH" in os.environ:
|
||||||
|
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||||
|
|
||||||
|
res = subprocess.run(
|
||||||
|
[bash_bin, str(appctl_script), "status"],
|
||||||
|
env=env,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
assert res.returncode == 1
|
||||||
|
assert "daemon socket not found" in res.stderr
|
||||||
|
|
||||||
|
|
||||||
|
def test_appctl_wrapper_fast_paths_completion_without_socket(tmp_path: Path):
|
||||||
|
"""Ensure scripts/appctl completes offline via appctl_engine.py even when socket is missing."""
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
bash_bin = shutil.which("bash") or "bash"
|
||||||
|
non_existent_sock = tmp_path / "missing_appctl.sock"
|
||||||
|
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(non_existent_sock),
|
||||||
|
"SITES_DIR": str(tmp_path),
|
||||||
|
}
|
||||||
|
if "PYTHONPATH" in os.environ:
|
||||||
|
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ x 2026-10-23 (A) Migrate operator user from kiskaadee to operator in nixos/confi
|
|||||||
x 2026-10-23 (A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth
|
x 2026-10-23 (A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth
|
||||||
x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms
|
x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms
|
||||||
x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git
|
x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git
|
||||||
(B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security
|
x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security
|
||||||
(B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux
|
(B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux
|
||||||
(B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth
|
(B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth
|
||||||
(B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4
|
(B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4
|
||||||
|
|||||||
Reference in new issue
Block a user