package main import ( "os" "path/filepath" "regexp" "strings" "testing" ) func TestTemplateImageRegistryDockerHubShorthand(t *testing.T) { t.Setenv("ADPANEL_ALLOWED_TEMPLATE_IMAGE_REGISTRIES", "docker.io,ghcr.io") for _, image := range []string{ "alpine:3.20", "ubuntu:24.04", "node:20-alpine", "ubuntu@sha256:" + strings.Repeat("a", 64), "library/ubuntu:24.04", } { if registry := templateImageRegistryOf(image); registry != "docker.io" { t.Fatalf("Docker Hub shorthand %q must resolve to docker.io, got %q", image, registry) } if reason := validateTemplateImageRef(image); reason != "" { t.Fatalf("allowlisted Docker Hub shorthand %q must pass reinstall preflight: %s", image, reason) } } for _, image := range []string{"registry.invalid/team/app:1", "localhost:5000/team/app:1"} { if reason := validateTemplateImageRef(image); reason == "" { t.Fatalf("unapproved registry %q must remain rejected", image) } } } // Remediation of the audit finding "the strict command validator is bypassed // by design via two sibling fields": install scripts are full shell scripts, // so the node agent must enforce the same container-boundary rule the panel // applies at ingestion (validateTemplateInstallScriptInput in // utils/server-template-payload.js). The installer container additionally runs // with the runtime baseline (cap-drop/no-new-privileges/pids-limit), but the // script-level gate keeps escape attempts off the host entirely. func TestValidateTemplateInstallScriptAcceptsOrdinaryScripts(t *testing.T) { accepted := []string{ "#!/bin/bash\napt-get update && apt-get install -y curl\n", "curl -fsSL https://example.invalid/x.sh | sh", "echo downloading server\ntar -xzf server.tar.gz -C /mnt/server", "git clone https://github.com/example/game.git /mnt/server", "java -jar setup.jar --install", "", " ", } for _, script := range accepted { if reason := validateTemplateInstallScript(script); reason != "" { t.Fatalf("expected acceptance for %q, got: %s", script, reason) } } } func TestValidateTemplateInstallScriptRejectsRuntimeReferences(t *testing.T) { rejected := []string{ "docker run --privileged -v /:/host alpine", "docker pull ghcr.io/example/image", "podman run -v /:/host alpine", "nerdctl info", "ctr images pull x", "nsenter -t 1 -m -- /bin/sh", "unshare --mount --pid --fork", "curl --unix-socket /var/run/docker.sock http://localhost/version", "apt-get install docker.io", "echo --network=host", "mkdir -p /proc/1/root/escape", // Case must not matter. "DOCKER run alpine", } for _, script := range rejected { if reason := validateTemplateInstallScript(script); reason == "" { t.Fatalf("expected rejection for %q", script) } else if !strings.Contains(reason, "install scripts cannot reference") { t.Fatalf("unexpected reason for %q: %s", script, reason) } } } func TestValidateTemplateInstallScriptWordBoundaryDoesNotFlagProseSubstrings(t *testing.T) { // The whole-word rule must not turn into a substring match: these contain // runtime names only inside larger words (unlike a real `docker` call) — // they must pass so legitimate content is not broken. Actual references // (word boundaries) are covered by the rejection test above. accepted := []string{ "echo dockered podmans", "wget https://example.invalid/dockers.tar.gz", } for _, script := range accepted { if reason := validateTemplateInstallScript(script); reason != "" { t.Fatalf("expected acceptance for %q, got: %s", script, reason) } } } func TestNormalizeTemplateInstallConfigStaysPureNormalization(t *testing.T) { // normalizeTemplateInstallConfig must not silently swallow a violating // script (returning nil would skip the install with no signal); the // explicit validator owns rejection at the create endpoint and preflight. install := normalizeTemplateInstallConfig(&templateInstallConfig{ Script: "docker run alpine", }) if install == nil { t.Fatal("normalization must keep the script; the boundary validator rejects it") } if reason := validateTemplateInstallScript(install.Script); reason == "" { t.Fatal("normalized script must still be rejected by the boundary validator") } } // TestInitializeScriptServiceUnitTrustBoundary pins the privilege-escalation // fix for the generated service units: on a deployed system the panel // directory (start.sh included) is owned by the unprivileged 'adpanel' // service user, so the unit — and every automated installer path — must // never execute any panel-directory file with root privileges. Root-side // runtime preparation lives in initialize.sh's own // prepare_panel_runtime_as_root(), the artifact the operator actually // invoked as root. func TestInitializeScriptServiceUnitTrustBoundary(t *testing.T) { wd, err := os.Getwd() if err != nil { t.Fatalf("get working directory: %v", err) } initializeBytes, err := os.ReadFile(filepath.Join(wd, "initialize.sh")) if err != nil { t.Fatalf("read initialize.sh: %v", err) } initialize := string(initializeBytes) // The legacy root-prefix directive is ignored on systemd >= 253 and // roots unit Exec lines on <= 252; it must never come back. if strings.Contains(initialize, "PermissionsStartOnly") { t.Error("initialize.sh must not re-enable root-prefixed unit execution (PermissionsStartOnly)") } // prep_scriptInvoc matches `bash "$prep_script"` / `bash "${prep_script}"` // — the retired pattern of root-executing the panel-writable start.sh. prepScriptInvoc := regexp.MustCompile(`bash ["']?\$\{?prep_script\}?["']?`) for _, line := range strings.Split(initialize, "\n") { // The retired emission was ExecStartPre=/bin/bash ${prep_script}; // "=" distinguishes real directives/assignments from prose. if strings.Contains(line, "ExecStartPre=") && strings.Contains(line, "start.sh") { t.Errorf("generated unit must not ExecStartPre the panel-writable start.sh: %s", line) } if strings.Contains(line, "ExecStartPre=/bin/bash") { t.Errorf("generated unit must not ExecStartPre a /bin/bash panel script: %s", line) } if prepScriptInvoc.MatchString(line) { t.Errorf("initialize.sh must not root-execute start.sh via prep_script: %s", line) } if strings.Contains(line, "local prep_script=") { t.Errorf("prep_script mechanism is retired; found: %s", line) } } if !strings.Contains(initialize, "prepare_panel_runtime_as_root") { t.Error("initialize.sh must provide prepare_panel_runtime_as_root as the installer-owned runtime preparation") } if !strings.Contains(initialize, "TRUST BOUNDARY") { t.Error("initialize.sh must document the start.sh trust boundary it enforces") } startBytes, err := os.ReadFile(filepath.Join(wd, "start.sh")) if err != nil { t.Fatalf("read start.sh: %v", err) } start := string(startBytes) if !strings.Contains(start, "TRUST BOUNDARY") || !strings.Contains(start, "prepare_panel_runtime_as_root") { t.Error("start.sh header must warn that it is panel-user-writable on deployed systems and that automated paths must use initialize.sh's prepare_panel_runtime_as_root instead") } }