ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(installer): Phase 5 — additive Python bootstrap foundation
Juan Denisdb16100a421b
diff --git a/backend/serverkit_installer/README.md b/backend/serverkit_installer/README.mdnew file mode 100644index 00000000..b4100851--- /dev/null+++ b/backend/serverkit_installer/README.md@@ -0,0 +1,57 @@+# serverkit_installer++Phase 5 foundation from the+[Installer/Updater/Uninstaller Hardening Plan](../../docs/plans/INSTALLER_UPDATER_UNINSTALLER_HARDENING_PLAN.md)+(§8). A stdlib-only, import-safe, unit-tested Python port of the bash installer's+detection and orchestration logic.++> **Additive, not a replacement.** `install.sh` is still the canonical installer.+> This package exists so the stabilized multi-distro logic has a single,+> unit-testable home that the backend can eventually share. It is **not** wired+> into `install.sh` yet — per the plan's migration path, the bash scripts stay+> in charge until this is fully validated on real boxes.++## Why it doesn't import `app`++The real bootstrap runs **before** the backend venv exists, so importing+`app.utils.system` (which pulls in Flask/SQLAlchemy) would fail. This package is+deliberately stdlib-only (plus PyYAML for the manifest) and mirrors+`app/utils/system.py`'s `run_privileged`/sudo contract in `_proc.py`.++## Modules++| Module | Mirrors | Responsibility |+|--------|---------|----------------|+| `distro.py` | `install.sh:os_family_from` + `scripts/lib/env.sh` | OS family + container/WSL/systemd detection |+| `deps.py` | `scripts/deps/manifest.yaml` | Load the manifest, resolve packages per family |+| `firewall.py` | `scripts/lib/firewall.sh` | Detect backend, build open/close command lists |+| `service.py` | `scripts/lib/init.sh` | Detect init system, build start/stop/enable commands |+| `main.py` | — | Compose a read-only install **plan** + CLI |+| `_proc.py` | `app/utils/system.py` | sudo-aware subprocess helpers |++The command **builders** are pure functions returning argv lists, so they're+tested without touching a real firewall/init system.++## Usage++```bash+# Read-only: print what an install would do on the detected distro+python -m serverkit_installer plan++# Just the distro detection+python -m serverkit_installer detect --os-release /etc/os-release++# Force backends for a preview on any host+python -m serverkit_installer plan --firewall firewalld --init systemd+```++## Tests++`backend/tests/test_serverkit_installer.py` (46 cases) — family mapping kept in+lockstep with `os_family_from`, manifest resolution for every family, the+firewall/service command builders, environment predicates, and the composed+plan. Pure logic, no host mutation:++```bash+cd backend && pytest tests/test_serverkit_installer.py+```diff --git a/backend/serverkit_installer/__init__.py b/backend/serverkit_installer/__init__.pynew file mode 100644index 00000000..2d0e2156--- /dev/null+++ b/backend/serverkit_installer/__init__.py@@ -0,0 +1,19 @@+"""ServerKit installer bootstrap (Phase 5 foundation).++A stdlib-only, import-safe, unit-tested Python package that mirrors the bash+installer's distro/dependency/firewall/service logic. Per the hardening plan+(docs/plans/INSTALLER_UPDATER_UNINSTALLER_HARDENING_PLAN.md §8) this is an+*additive foundation*: install.sh remains the canonical installer. The point of+porting the stabilized bash logic here is to get unit-testable orchestration and+a single source of truth for distro detection that the backend can eventually+share.++It is deliberately import-safe with NO dependency on ``app`` (which pulls in+Flask/SQLAlchemy) because the real bootstrap runs *before* the backend venv+exists. It mirrors ``app/utils/system.py``'s ``run_privileged``/sudo contract+rather than importing it.+"""++from . import deps, distro, firewall, service # noqa: F401++__all__ = ["distro", "deps", "firewall", "service"]diff --git a/backend/serverkit_installer/__main__.py b/backend/serverkit_installer/__main__.pynew file mode 100644index 00000000..dd695e6a--- /dev/null+++ b/backend/serverkit_installer/__main__.py@@ -0,0 +1,4 @@+"""Entry point: ``python -m serverkit_installer``."""+from .main import main++raise SystemExit(main())diff --git a/backend/serverkit_installer/_proc.py b/backend/serverkit_installer/_proc.pynew file mode 100644index 00000000..83583808--- /dev/null+++ b/backend/serverkit_installer/_proc.py@@ -0,0 +1,63 @@+"""Subprocess + privilege helpers for the installer bootstrap.++Stdlib-only on purpose: this code can run *before* the backend venv exists, so+it must not import ``app.utils.system`` (which imports Flask). It mirrors that+module's ``needs_sudo``/``run_privileged`` semantics so the two stay+conceptually unified — a command list is wrapped with ``sudo`` only when the+process isn't already root, isn't on Windows, and ``sudo`` is available.+"""+from __future__ import annotations++import os+import shutil+import subprocess+from typing import List, Sequence+++def needs_sudo() -> bool:+ """Return True if commands should be prefixed with ``sudo``."""+ if os.name == "nt":+ return False+ geteuid = getattr(os, "geteuid", None)+ if geteuid is not None and geteuid() == 0:+ return False+ if not shutil.which("sudo"):+ return False+ return True+++def with_privilege(cmd: Sequence[str]) -> List[str]:+ """Return *cmd* with ``sudo`` prepended when necessary."""+ parts = list(cmd)+ if parts and needs_sudo() and parts[0] != "sudo":+ return ["sudo"] + parts+ return parts+++def run(cmd: Sequence[str], *, dry_run: bool = False, check: bool = False,+ capture: bool = True, **kwargs) -> subprocess.CompletedProcess:+ """Run *cmd* (a list). Under ``dry_run`` nothing executes — a synthetic,+ successful CompletedProcess is returned so callers can treat both paths+ uniformly.+ """+ parts = list(cmd)+ if dry_run:+ return subprocess.CompletedProcess(parts, 0, stdout="", stderr="")+ kwargs.setdefault("text", True)+ if capture:+ kwargs.setdefault("stdout", subprocess.PIPE)+ kwargs.setdefault("stderr", subprocess.PIPE)+ return subprocess.run(parts, check=check, **kwargs)+++def command_ok(cmd: Sequence[str]) -> bool:+ """Run *cmd* quietly and return True iff it exits 0. Never raises."""+ try:+ result = subprocess.run(+ list(cmd),+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ return result.returncode == 0+ except (OSError, ValueError):+ return Falsediff --git a/backend/serverkit_installer/deps.py b/backend/serverkit_installer/deps.pynew file mode 100644index 00000000..eea2da19--- /dev/null+++ b/backend/serverkit_installer/deps.py@@ -0,0 +1,55 @@+"""Dependency manifest loader.++Reads scripts/deps/manifest.yaml — the declarative per-family package spec — and+resolves the pieces an installer needs (base packages, python spec, node/docker+method, package manager) for a given family. This is the manifest's primary+consumer: the bash installer can't parse YAML before Python exists, so it+mirrors these choices inline; here we read the file directly.+"""+from __future__ import annotations++from pathlib import Path+from typing import Optional++try:+ import yaml+except ImportError: # pragma: no cover - PyYAML is a hard backend dependency+ yaml = None+++def default_manifest_path() -> Path:+ """Repo-relative path to scripts/deps/manifest.yaml.++ deps.py lives at backend/serverkit_installer/deps.py, so the repo root is+ two parents up.+ """+ return Path(__file__).resolve().parents[2] / "scripts" / "deps" / "manifest.yaml"+++def load_manifest(path: Optional[str] = None) -> dict:+ """Load and parse the manifest. Raises if PyYAML is unavailable."""+ if yaml is None:+ raise RuntimeError("PyYAML is required to read the dependency manifest")+ manifest_path = Path(path) if path else default_manifest_path()+ with open(manifest_path, encoding="utf-8") as handle:+ return yaml.safe_load(handle) or {}+++def base_packages(manifest: dict, family: str) -> list:+ return list((manifest.get("base_packages") or {}).get(family, []))+++def python_spec(manifest: dict, family: str) -> dict:+ return dict((manifest.get("python") or {}).get(family, {}))+++def node_spec(manifest: dict, family: str) -> dict:+ return dict((manifest.get("node") or {}).get(family, {}))+++def docker_spec(manifest: dict, family: str) -> dict:+ return dict((manifest.get("docker") or {}).get(family, {}))+++def package_manager(manifest: dict, family: str) -> Optional[str]:+ return (manifest.get("package_manager") or {}).get(family)diff --git a/backend/serverkit_installer/distro.py b/backend/serverkit_installer/distro.pynew file mode 100644index 00000000..92a9767c--- /dev/null+++ b/backend/serverkit_installer/distro.py@@ -0,0 +1,153 @@+"""OS / distro + environment detection.++The family mapping is a faithful port of install.sh's ``os_family_from`` (kept+in lockstep so bash and Python agree on what "supported distro" means), and the+container/WSL/systemd predicates mirror scripts/lib/env.sh.+"""+from __future__ import annotations++import os+import shutil+from dataclasses import dataclass++FAMILIES = ("debian", "rhel", "fedora", "suse", "arch", "alpine")++# Exact ID → family map (matches install.sh's case arms).+_ID_FAMILY = {+ "ubuntu": "debian", "linuxmint": "debian", "pop": "debian",+ "raspbian": "debian", "elementary": "debian", "zorin": "debian",+ "debian": "debian", "devuan": "debian",+ "fedora": "fedora", "nobara": "fedora",+ "rocky": "rhel", "almalinux": "rhel", "rhel": "rhel", "centos": "rhel",+ "ol": "rhel", "oracle": "rhel", "eurolinux": "rhel",+ "sles": "suse", "sled": "suse", "suse": "suse", "sle-micro": "suse",+ "arch": "arch", "manjaro": "arch", "endeavouros": "arch", "cachyos": "arch",+ "alpine": "alpine",+}++# ID_LIKE substrings → family, in priority order. rhel before fedora so RHEL+# clones (ID_LIKE="rhel centos fedora") pick the RHEL family, not fedora.+_LIKE_FAMILY = (+ ("debian", "debian"), ("ubuntu", "debian"),+ ("rhel", "rhel"), ("centos", "rhel"),+ ("fedora", "fedora"),+ ("suse", "suse"),+ ("arch", "arch"),+ ("alpine", "alpine"),+)+++def family_from(distro_id: str, id_like: str = "") -> str:+ """Map an os-release ID (+ ID_LIKE fallback) to a ServerKit family.++ Returns one of FAMILIES or ``"unknown"``.+ """+ did = (distro_id or "").strip().lower()+ if did in _ID_FAMILY:+ return _ID_FAMILY[did]+ if did.startswith("opensuse"):+ return "suse"+ like = (id_like or "").lower()+ for needle, family in _LIKE_FAMILY:+ if needle in like:+ return family+ return "unknown"+++def parse_os_release(path: str = "/etc/os-release") -> dict:+ """Parse a shell-style os-release file into a dict. Missing file → {}."""+ out: dict = {}+ try:+ with open(path, encoding="utf-8") as handle:+ for raw in handle:+ line = raw.strip()+ if not line or line.startswith("#") or "=" not in line:+ continue+ key, value = line.split("=", 1)+ out[key.strip()] = value.strip().strip('"').strip("'")+ except OSError:+ pass+ return out+++@dataclass(frozen=True)+class Distro:+ id: str+ id_like: str+ pretty_name: str+ family: str++ @property+ def supported(self) -> bool:+ return self.family in FAMILIES+++def detect(os_release_path: str = "/etc/os-release") -> Distro:+ """Detect the running distro from an os-release file."""+ data = parse_os_release(os_release_path)+ return Distro(+ id=data.get("ID", ""),+ id_like=data.get("ID_LIKE", ""),+ pretty_name=data.get("PRETTY_NAME", ""),+ family=family_from(data.get("ID", ""), data.get("ID_LIKE", "")),+ )+++# ---------------------------------------------------------------------------+# Environment predicates (mirror scripts/lib/env.sh). The keyword overrides+# exist for unit testing against fixtures.+# ---------------------------------------------------------------------------+_CONTAINER_CGROUP_MARKERS = ("docker", "lxc", "containerd", "kubepods", "podman")+++def is_container(+ *,+ force: "bool | None" = None,+ dockerenv: str = "/.dockerenv",+ containerenv: str = "/run/.containerenv",+ cgroup_file: str = "/proc/1/cgroup",+ container_env: "str | None" = None,+) -> bool:+ """True when running inside a container."""+ if force is not None:+ return force+ if os.path.exists(dockerenv):+ return True+ if os.path.exists(containerenv):+ return True+ env_val = os.environ.get("container") if container_env is None else container_env+ if env_val:+ return True+ try:+ with open(cgroup_file, encoding="utf-8", errors="ignore") as handle:+ content = handle.read()+ return any(marker in content for marker in _CONTAINER_CGROUP_MARKERS)+ except OSError:+ return False+++def is_wsl(+ *,+ force: "bool | None" = None,+ osrelease_file: str = "/proc/sys/kernel/osrelease",+) -> bool:+ """True under Windows Subsystem for Linux."""+ if force is not None:+ return force+ try:+ with open(osrelease_file, encoding="utf-8", errors="ignore") as handle:+ content = handle.read().lower()+ return "microsoft" in content or "wsl" in content+ except OSError:+ return False+++def has_systemd(+ *,+ force: "bool | None" = None,+ systemd_dir: str = "/run/systemd/system",+) -> bool:+ """True when systemd is usable as the init/service manager."""+ if force is not None:+ return force+ return bool(shutil.which("systemctl")) and os.path.isdir(systemd_dir)diff --git a/backend/serverkit_installer/firewall.py b/backend/serverkit_installer/firewall.pynew file mode 100644index 00000000..b637fc61--- /dev/null+++ b/backend/serverkit_installer/firewall.py@@ -0,0 +1,100 @@+"""Firewall abstraction — a port of scripts/lib/firewall.sh.++Detection touches the host, but the open/close command *builders* are pure+functions returning lists of argv lists, which makes them trivially unit-tested+and lets ``apply`` run or merely print them under dry-run.+"""+from __future__ import annotations++from typing import List, Optional, Sequence++from ._proc import command_ok, run, with_privilege++BACKENDS = ("firewalld", "ufw", "nftables", "iptables", "none")+++def _split(spec: str):+ """'80/tcp' -> ('80', 'tcp'); '80' -> ('80', 'tcp')."""+ if "/" in spec:+ port, proto = spec.split("/", 1)+ return port, proto+ return spec, "tcp"+++def detect(override: Optional[str] = None) -> str:+ """Return the active firewall backend. ``override`` forces a result."""+ import shutil++ if override:+ return override+ if shutil.which("firewall-cmd") and command_ok(["firewall-cmd", "--state"]):+ return "firewalld"+ if shutil.which("ufw") and _ufw_active():+ return "ufw"+ if shutil.which("nft") and command_ok(["nft", "list", "ruleset"]):+ return "nftables"+ if shutil.which("iptables"):+ return "iptables"+ return "none"+++def _ufw_active() -> bool:+ try:+ import subprocess++ out = subprocess.run(+ ["ufw", "status"], stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL, text=True,+ ).stdout or ""+ except (OSError, ValueError):+ return False+ return any(line.strip().lower().startswith("status: active") for line in out.splitlines())+++def open_commands(backend: str, ports: Sequence[str]) -> List[List[str]]:+ """Argv lists that open *ports* (each like '80/tcp') for *backend*."""+ cmds: List[List[str]] = []+ for spec in ports:+ port, proto = _split(spec)+ if backend == "firewalld":+ cmds.append(["firewall-cmd", "--permanent", f"--add-port={port}/{proto}"])+ elif backend == "ufw":+ cmds.append(["ufw", "allow", f"{port}/{proto}"])+ elif backend == "iptables":+ cmds.append(["iptables", "-I", "INPUT", "-p", proto, "--dport", port, "-j", "ACCEPT"])+ elif backend == "nftables":+ cmds.append(["nft", "add", "rule", "inet", "filter", "input", proto, "dport", port, "accept"])+ if backend == "firewalld" and cmds:+ cmds.append(["firewall-cmd", "--reload"])+ return cmds+++def close_commands(backend: str, ports: Sequence[str]) -> List[List[str]]:+ """Argv lists that close *ports* for *backend*."""+ cmds: List[List[str]] = []+ for spec in ports:+ port, proto = _split(spec)+ if backend == "firewalld":+ cmds.append(["firewall-cmd", "--permanent", f"--remove-port={port}/{proto}"])+ elif backend == "ufw":+ cmds.append(["ufw", "delete", "allow", f"{port}/{proto}"])+ elif backend == "iptables":+ cmds.append(["iptables", "-D", "INPUT", "-p", proto, "--dport", port, "-j", "ACCEPT"])+ # nftables deletion needs a rule handle we can't reliably resolve here.+ if backend == "firewalld" and cmds:+ cmds.append(["firewall-cmd", "--reload"])+ return cmds+++def apply(commands: Sequence[Sequence[str]], *, dry_run: bool = False) -> List[str]:+ """Run each command (with privilege). Returns the rendered command strings.++ Best-effort: a failing rule is recorded but does not abort the batch.+ """+ rendered: List[str] = []+ for cmd in commands:+ full = with_privilege(cmd)+ rendered.append(" ".join(full))+ if not dry_run:+ run(full, capture=True)+ return rendereddiff --git a/backend/serverkit_installer/main.py b/backend/serverkit_installer/main.pynew file mode 100644index 00000000..21d86046--- /dev/null+++ b/backend/serverkit_installer/main.py@@ -0,0 +1,109 @@+"""Installer bootstrap orchestration (additive foundation).++The canonical installer is still ``install.sh``. This module composes the+detection + manifest + firewall + service pieces into a single "plan" — what an+install *would* do on the detected distro — and prints it. It performs no host+mutation on its own (the ``plan`` command is read-only), so it is safe to run+anywhere, including in CI and on a dev box.++Usage:+ python -m serverkit_installer plan+ python -m serverkit_installer detect --os-release /etc/os-release+"""+from __future__ import annotations++import argparse+import json+from typing import Optional++from . import deps, distro, firewall, service++PANEL_PORTS = ["80/tcp", "443/tcp"]+BACKEND_SERVICE = "serverkit"+++def build_plan(+ *,+ os_release_path: str = "/etc/os-release",+ manifest_path: Optional[str] = None,+ firewall_backend: Optional[str] = None,+ init_system: Optional[str] = None,+) -> dict:+ """Return a read-only description of the install actions for this host.++ Every field is derived without mutating the system. ``firewall_backend`` and+ ``init_system`` can be forced (used by tests and dry-run previews).+ """+ box = distro.detect(os_release_path)++ plan: dict = {+ "distro": {+ "id": box.id,+ "id_like": box.id_like,+ "pretty_name": box.pretty_name,+ "family": box.family,+ "supported": box.supported,+ },+ "environment": {+ "container": distro.is_container(),+ "wsl": distro.is_wsl(),+ "systemd": distro.has_systemd(),+ },+ }++ # Packages from the manifest (best-effort: an unknown family or unreadable+ # manifest just yields empty lists rather than blowing up the preview).+ try:+ manifest = deps.load_manifest(manifest_path)+ plan["packages"] = {+ "package_manager": deps.package_manager(manifest, box.family),+ "base": deps.base_packages(manifest, box.family),+ "python": deps.python_spec(manifest, box.family),+ "node": deps.node_spec(manifest, box.family),+ "docker": deps.docker_spec(manifest, box.family),+ }+ except (RuntimeError, OSError) as exc:+ plan["packages"] = {"error": str(exc)}++ fw_backend = firewall.detect(firewall_backend)+ plan["firewall"] = {+ "backend": fw_backend,+ "open": [" ".join(c) for c in firewall.open_commands(fw_backend, PANEL_PORTS)],+ }++ init = service.detect(init_system)+ plan["service"] = {+ "init": init,+ "enable": (lambda c: " ".join(c) if c else None)(service.enable_command(init, BACKEND_SERVICE)),+ "start": (lambda c: " ".join(c) if c else None)(service.start_command(init, BACKEND_SERVICE)),+ }+ return plan+++def main(argv: Optional[list] = None) -> int:+ parser = argparse.ArgumentParser(prog="serverkit_installer", description=__doc__)+ parser.add_argument("command", nargs="?", default="plan", choices=["plan", "detect"])+ parser.add_argument("--os-release", default="/etc/os-release")+ parser.add_argument("--manifest", default=None)+ parser.add_argument("--firewall", default=None, help="force a firewall backend")+ parser.add_argument("--init", default=None, help="force an init system")+ parser.add_argument("--json", action="store_true", help="emit JSON")+ args = parser.parse_args(argv)++ if args.command == "detect":+ box = distro.detect(args.os_release)+ if args.json:+ print(json.dumps(box.__dict__))+ else:+ print(f"{box.pretty_name or box.id or 'unknown'} -> family={box.family} "+ f"(supported={box.supported})")+ return 0++ plan = build_plan(+ os_release_path=args.os_release,+ manifest_path=args.manifest,+ firewall_backend=args.firewall,+ init_system=args.init,+ )+ print(json.dumps(plan, indent=2))+ return 0diff --git a/backend/serverkit_installer/service.py b/backend/serverkit_installer/service.pynew file mode 100644index 00000000..b81198e3--- /dev/null+++ b/backend/serverkit_installer/service.py@@ -0,0 +1,107 @@+"""Init-system / service abstraction — a port of scripts/lib/init.sh.++Detection touches the host; the command builders are pure functions returning a+single argv list (or ``None`` when the action is unsupported under the detected+init), which keeps them unit-testable.+"""+from __future__ import annotations++import os+import shutil+from typing import List, Optional++from ._proc import command_ok, run, with_privilege++INITS = ("systemd", "openrc", "runit", "sysvinit", "none")+++def detect(override: Optional[str] = None) -> str:+ """Return the detected init system. ``override`` forces a result."""+ if override:+ return override+ if os.path.isdir("/run/systemd/system") or _pid1_is_systemd():+ return "systemd"+ if shutil.which("rc-service"):+ return "openrc"+ if shutil.which("sv") and (os.path.isdir("/etc/runit") or os.path.isdir("/run/runit")):+ return "runit"+ if os.path.isdir("/etc/init.d") or shutil.which("service"):+ return "sysvinit"+ return "none"+++def _pid1_is_systemd() -> bool:+ try:+ with open("/proc/1/comm", encoding="utf-8") as handle:+ return handle.read().strip() == "systemd"+ except OSError:+ return False+++def start_command(init: str, service: str) -> Optional[List[str]]:+ return {+ "systemd": ["systemctl", "start", service],+ "openrc": ["rc-service", service, "start"],+ "runit": ["sv", "up", service],+ "sysvinit": ["service", service, "start"],+ }.get(init)+++def stop_command(init: str, service: str) -> Optional[List[str]]:+ return {+ "systemd": ["systemctl", "stop", service],+ "openrc": ["rc-service", service, "stop"],+ "runit": ["sv", "down", service],+ "sysvinit": ["service", service, "stop"],+ }.get(init)+++def enable_command(init: str, service: str) -> Optional[List[str]]:+ if init == "systemd":+ return ["systemctl", "enable", service]+ if init == "openrc":+ return ["rc-update", "add", service]+ if init == "sysvinit":+ if shutil.which("update-rc.d"):+ return ["update-rc.d", service, "enable"]+ if shutil.which("chkconfig"):+ return ["chkconfig", service, "on"]+ return ["update-rc.d", service, "enable"]+ # runit enable is symlink-based; 'none' is unsupported.+ return None+++def reload_command(init: str, service: Optional[str] = None) -> Optional[List[str]]:+ if init == "systemd":+ return ["systemctl", "daemon-reload"] if service is None else ["systemctl", "reload", service]+ if service is None:+ return None+ return {+ "openrc": ["rc-service", service, "reload"],+ "sysvinit": ["service", service, "reload"],+ }.get(init)+++def is_active(init: str, service: str) -> bool:+ """Return True when *service* is currently running under *init*."""+ if init == "systemd":+ return command_ok(["systemctl", "is-active", "--quiet", service])+ if init == "openrc":+ return command_ok(["rc-service", service, "status"])+ if init == "runit":+ return command_ok(["sv", "status", service])+ if init == "sysvinit":+ return command_ok(["service", service, "status"])+ return False+++def apply(command: Optional[List[str]], *, dry_run: bool = False) -> Optional[str]:+ """Run a single service command (with privilege). Returns the rendered+ string, or ``None`` when the action is unsupported under this init.+ """+ if command is None:+ return None+ full = with_privilege(command)+ if not dry_run:+ run(full, capture=True)+ return " ".join(full)diff --git a/backend/tests/test_serverkit_installer.py b/backend/tests/test_serverkit_installer.pynew file mode 100644index 00000000..1cda9d09--- /dev/null+++ b/backend/tests/test_serverkit_installer.py@@ -0,0 +1,230 @@+"""Unit tests for the Phase 5 installer bootstrap (serverkit_installer).++These are pure-logic tests: distro/family mapping, manifest parsing, the+firewall/service command builders, environment predicates, and the read-only+plan. No host mutation, no Flask — the package is import-safe and stdlib-only,+so this file never touches the ``app`` fixture.+"""+import textwrap++import pytest++from serverkit_installer import deps, distro, firewall, service+from serverkit_installer.main import build_plan+++# ---------------------------------------------------------------------------+# distro.family_from — must agree with install.sh's os_family_from+# ---------------------------------------------------------------------------[email protected]("distro_id,expected", [+ ("ubuntu", "debian"),+ ("debian", "debian"),+ ("linuxmint", "debian"),+ ("fedora", "fedora"),+ ("nobara", "fedora"),+ ("rocky", "rhel"),+ ("almalinux", "rhel"),+ ("centos", "rhel"),+ ("opensuse-leap", "suse"),+ ("opensuse-tumbleweed", "suse"),+ ("sles", "suse"),+ ("arch", "arch"),+ ("manjaro", "arch"),+ ("alpine", "alpine"),+ ("totally-unknown", "unknown"),+])+def test_family_from_known_ids(distro_id, expected):+ assert distro.family_from(distro_id) == expected++[email protected]("id_like,expected", [+ ("debian", "debian"),+ ("ubuntu debian", "debian"),+ ("rhel centos fedora", "rhel"), # RHEL clone: rhel wins over fedora+ ("fedora", "fedora"), # pure fedora spin+ ("suse opensuse", "suse"),+ ("arch", "arch"),+ ("alpine", "alpine"),+ ("plan9", "unknown"),+])+def test_family_from_id_like_fallback(id_like, expected):+ # Unknown ID forces the ID_LIKE path.+ assert distro.family_from("mystery-distro", id_like) == expected+++def test_parse_os_release_and_detect(tmp_path):+ osr = tmp_path / "os-release"+ osr.write_text(textwrap.dedent('''\+ NAME="Rocky Linux"+ ID="rocky"+ ID_LIKE="rhel centos fedora"+ PRETTY_NAME="Rocky Linux 9.3 (Blue Onyx)"+ VERSION_ID="9.3"+ '''))+ box = distro.detect(str(osr))+ assert box.id == "rocky"+ assert box.family == "rhel"+ assert box.pretty_name.startswith("Rocky Linux 9")+ assert box.supported is True+++def test_detect_missing_os_release_is_unknown(tmp_path):+ box = distro.detect(str(tmp_path / "does-not-exist"))+ assert box.family == "unknown"+ assert box.supported is False+++# ---------------------------------------------------------------------------+# distro environment predicates+# ---------------------------------------------------------------------------+def test_is_container_via_cgroup_fixture(tmp_path):+ cg = tmp_path / "cgroup"+ cg.write_text("0::/system.slice/docker-abc.scope\n")+ assert distro.is_container(+ dockerenv=str(tmp_path / "none"),+ containerenv=str(tmp_path / "none"),+ container_env="",+ cgroup_file=str(cg),+ ) is True+++def test_is_container_force_and_plain_host(tmp_path):+ assert distro.is_container(force=True) is True+ assert distro.is_container(force=False) is False+ cg = tmp_path / "cgroup"+ cg.write_text("0::/init.scope\n")+ assert distro.is_container(+ dockerenv=str(tmp_path / "none"),+ containerenv=str(tmp_path / "none"),+ container_env="",+ cgroup_file=str(cg),+ ) is False+++def test_is_wsl(tmp_path):+ osr = tmp_path / "osrelease"+ osr.write_text("5.15.0-microsoft-standard-WSL2\n")+ assert distro.is_wsl(osrelease_file=str(osr)) is True+ bare = tmp_path / "bare"+ bare.write_text("6.1.0-generic\n")+ assert distro.is_wsl(osrelease_file=str(bare)) is False+ assert distro.is_wsl(force=True) is True+++def test_has_systemd_force():+ assert distro.has_systemd(force=True) is True+ assert distro.has_systemd(force=False) is False+++# ---------------------------------------------------------------------------+# deps — manifest loader (uses the real scripts/deps/manifest.yaml)+# ---------------------------------------------------------------------------+def test_manifest_loads_and_resolves_every_family():+ manifest = deps.load_manifest()+ for family in distro.FAMILIES:+ base = deps.base_packages(manifest, family)+ assert "nginx" in base, f"{family} base packages should include nginx"+ assert deps.package_manager(manifest, family), f"{family} needs a package manager"+ assert deps.python_spec(manifest, family), f"{family} needs a python spec"+++def test_manifest_python_packages_match_policy():+ manifest = deps.load_manifest()+ # Debian 12 ships 3.11; Ubuntu/Fedora ship 3.12.+ assert deps.python_spec(manifest, "debian")["package"] == "python3.11"+ assert deps.python_spec(manifest, "fedora")["package"] == "python3.12"+ assert deps.package_manager(manifest, "suse") == "zypper"+++# ---------------------------------------------------------------------------+# firewall command builders (pure)+# ---------------------------------------------------------------------------+def test_firewall_detect_override():+ assert firewall.detect("ufw") == "ufw"+++def test_firewall_open_firewalld():+ cmds = firewall.open_commands("firewalld", ["80/tcp", "443/tcp"])+ assert ["firewall-cmd", "--permanent", "--add-port=80/tcp"] in cmds+ assert ["firewall-cmd", "--permanent", "--add-port=443/tcp"] in cmds+ assert cmds[-1] == ["firewall-cmd", "--reload"]+++def test_firewall_open_ufw_and_iptables():+ assert firewall.open_commands("ufw", ["80/tcp"]) == [["ufw", "allow", "80/tcp"]]+ assert firewall.open_commands("iptables", ["443/tcp"]) == [+ ["iptables", "-I", "INPUT", "-p", "tcp", "--dport", "443", "-j", "ACCEPT"]+ ]+++def test_firewall_close_mirrors_open():+ assert firewall.close_commands("ufw", ["80/tcp"]) == [["ufw", "delete", "allow", "80/tcp"]]+ fd = firewall.close_commands("firewalld", ["80/tcp"])+ assert ["firewall-cmd", "--permanent", "--remove-port=80/tcp"] in fd+ assert fd[-1] == ["firewall-cmd", "--reload"]+++def test_firewall_none_is_empty():+ assert firewall.open_commands("none", ["80/tcp"]) == []+++def test_firewall_apply_dry_run_renders_without_executing():+ cmds = firewall.open_commands("firewalld", ["80/tcp"])+ rendered = firewall.apply(cmds, dry_run=True)+ assert any("firewall-cmd --permanent --add-port=80/tcp" in r for r in rendered)+++# ---------------------------------------------------------------------------+# service / init command builders (pure)+# ---------------------------------------------------------------------------+def test_service_detect_override():+ assert service.detect("openrc") == "openrc"++[email protected]("init,expected", [+ ("systemd", ["systemctl", "start", "serverkit"]),+ ("openrc", ["rc-service", "serverkit", "start"]),+ ("runit", ["sv", "up", "serverkit"]),+ ("sysvinit", ["service", "serverkit", "start"]),+])+def test_service_start_command(init, expected):+ assert service.start_command(init, "serverkit") == expected+++def test_service_enable_command():+ assert service.enable_command("systemd", "serverkit") == ["systemctl", "enable", "serverkit"]+ assert service.enable_command("openrc", "serverkit") == ["rc-update", "add", "serverkit"]+ # runit/none have no simple enable command.+ assert service.enable_command("none", "serverkit") is None+++def test_service_reload_command():+ assert service.reload_command("systemd") == ["systemctl", "daemon-reload"]+ assert service.reload_command("systemd", "serverkit") == ["systemctl", "reload", "serverkit"]+++def test_service_apply_dry_run():+ rendered = service.apply(service.start_command("systemd", "serverkit"), dry_run=True)+ assert "systemctl start serverkit" in rendered+ assert service.apply(None, dry_run=True) is None+++# ---------------------------------------------------------------------------+# main.build_plan — read-only end-to-end composition+# ---------------------------------------------------------------------------+def test_build_plan_for_a_forced_rhel_box(tmp_path):+ osr = tmp_path / "os-release"+ osr.write_text('ID="rocky"\nID_LIKE="rhel fedora"\nPRETTY_NAME="Rocky Linux 9"\n')+ plan = build_plan(+ os_release_path=str(osr),+ firewall_backend="firewalld",+ init_system="systemd",+ )+ assert plan["distro"]["family"] == "rhel"+ assert plan["distro"]["supported"] is True+ assert "nginx" in plan["packages"]["base"]+ assert plan["packages"]["package_manager"] == "dnf"+ assert plan["firewall"]["backend"] == "firewalld"+ assert any("--add-port=80/tcp" in c for c in plan["firewall"]["open"])+ assert plan["service"]["init"] == "systemd"+ assert plan["service"]["start"] == "systemctl start serverkit"