Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Keep NAS installer normalisation independent of tr classes
pulse-triage[bot]392e3e47f92c
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex d7ae134d77..a0e76ef7f8 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -15,6 +15,34 @@## Purpose+### NAS utility compatibility preserves URL and lifecycle trust++The Unix installer uses explicit ASCII alphabets and whitespace for `tr`, not+POSIX character classes that older NAS utilities may interpret literally.+Scheme checks do not rewrite the endpoint. URL/OS/hostname and fingerprint+normalisation, nonce generation, effective systemd word sets and rendered rc.d+parent-PID reads use the same portable character sets. A mixed-case HTTPS+scheme is stripped correctly when selecting the pinned-certificate authority.+Malformed input and mismatching pins remain refusals; this changes neither+runtime URL policy nor CA/pin verification or the action runner's loopback-only+HTTP exception.++`TestAgentInstallerPortableTRPreflight` executes the real preflight entry with+real local TLS, saved CA and formatted fingerprint, alongside an explicitly+classless `tr` model and malformed URL/pin, wrong-pin and HTTP controls. It+checks download OS/architecture and saved-file bytes/modes. The downstream+identity/transport controls also check hostname, nonce and effective word sets.+The model reproduces the earlier corruption; it is not native QNAP evidence.++`TestAgentInstalledRemovalSavedTransport` executes saved-state recovery and the+initial uninstall caller through the real collector CLI and authenticated local+TLS. Exact confirmation permits only the selected private fixture erasure;+missing trust, wrong pins, server refusal, another identity and non-loopback HTTP+retain recovery files. Service/process operations are closed doubles, and their+quiescence can precede refusal: retained files do not mean the service stayed+running. This does not execute the root entry, native systemd/appliance removal+or establish the cause of a reporter's unexplained removal failure.+### Unix agent URL admission precedes replacementAfter checksum and signature verification, the Unix installer runs the stageddiff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.mdindex de0b725824..4b399f3a0d 100644--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md@@ -16,6 +16,22 @@## Purpose+### Unix agent preflight does not require character-class-aware NAS utilities++Installer case-folding uses fixed ASCII alphabets, and whitespace handling uses+explicit characters rather than `tr` classes. Correctly copied HTTPS URLs must+survive scheme, fingerprint and OS normalisation even with a classless NAS `tr`.+The original endpoint is preserved. Mixed-case HTTPS with a pin selects the+same authority; malformed URLs/fingerprints, wrong pins and HTTP with a pin+remain rejected. Download metadata checks are still only preflight, not signed+artifact execution, native installation or original-host recovery.++The ordinary installer tests execute this preflight against real local TLS+with the system utility and a deliberately classless model, assert the actual+download architecture, and retain synthetic installed files unchanged. Separate+real-CLI removal controls bind saved CA/pin and exact server confirmation to+confined teardown; service/process doubles are not native acceptance.+### Agent installer completion retains failed startupThe shared Unix agent completion path must return service-start failure exitdiff --git a/scripts/install.sh b/scripts/install.shindex 5bee9e6de2..9a52fb07e6 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -687,7 +687,7 @@ resolve_safe_profile_hostname() {if [[ -z "$resolved_hostname" ]]; thenresolved_hostname=$(hostname 2>/dev/null || true)fi- resolved_hostname=$(printf '%s' "$resolved_hostname" | tr '[:upper:]' '[:lower:]')+ resolved_hostname=$(printf '%s' "$resolved_hostname" | LC_ALL=C tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz')resolved_hostname="${resolved_hostname%.}"[[ ${#resolved_hostname} -ge 1 && ${#resolved_hostname} -le 253 &&"$resolved_hostname" =~ ^[a-z0-9][a-z0-9._:-]*$ ]] || return 1@@ -2112,7 +2112,7 @@ write_action_runner_config() {generate_action_runner_activation_nonce() {local nonce=""- nonce=$(od -An -N32 -tx1 /dev/urandom 2>/dev/null | tr -d '[:space:]' || true)+ nonce=$(od -An -N32 -tx1 /dev/urandom 2>/dev/null | tr -d ' \t\r\n\v\f' || true)[[ "$nonce" =~ ^[a-f0-9]{64}$ ]] || return 1printf '%s\n' "$nonce"}@@ -2150,7 +2150,7 @@ action_runner_reestablish_repair_fence() {# intentionally indeterminate: callers must not restore a predecessor because# an unreachable server may already have committed and revoked it.action_runner_url_uses_loopback_http() {- local raw_url="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"+ local raw_url="$(printf '%s' "$1" | LC_ALL=C tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz')"local authority=""local host=""local octet=""@@ -2183,7 +2183,7 @@ action_runner_url_uses_loopback_http() {action_runner_url_transport_allowed() {local raw_url="$1"- local lower_url="$(printf '%s' "$raw_url" | tr '[:upper:]' '[:lower:]')"+ local lower_url="$(printf '%s' "$raw_url" | LC_ALL=C tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz')"if [[ "$lower_url" =~ ^https://[^[:space:]]+$ && "$lower_url" != *'@'* ]]; thenreturn 0fi@@ -2570,7 +2570,7 @@ systemd_effective_words_equal() {local actual=""local expected=""actual=$(systemd_effective_unit_property "$unit_name" "$property") || return 1- actual=$(printf '%s\n' "$actual" | tr '[:space:]' '\n' | sed '/^$/d' | LC_ALL=C sort -u | tr '\n' ' ' | sed 's/[[:space:]]*$//')+ actual=$(printf '%s\n' "$actual" | tr ' \t\r\n\v\f' '\n' | sed '/^$/d' | LC_ALL=C sort -u | tr '\n' ' ' | sed 's/[[:space:]]*$//')expected=$(printf '%s\n' "$@" | LC_ALL=C sort -u | tr '\n' ' ' | sed 's/[[:space:]]*$//')[[ "$actual" == "$expected" ]]}@@ -3319,7 +3319,7 @@ pulse_agent_supervisor_pid();;esac- parent_pid=\$(ps -o ppid= -p "\${agent_pid}" 2>/dev/null | tr -d '[:space:]')+ parent_pid=\$(ps -o ppid= -p "\${agent_pid}" 2>/dev/null | tr -d ' \t\r\n\v\f')if [ -z "\${parent_pid}" ] || [ "\${parent_pid}" = "1" ]; thenreturn 1fi@@ -4879,7 +4879,7 @@ detect_proxmox() {pulse_url_uses_plain_http() {local url_lower- url_lower=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')+ url_lower=$(printf '%s' "$1" | LC_ALL=C tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz')[[ "$url_lower" =~ ^http:// ]]}@@ -4910,12 +4910,12 @@ verify_pinned_server_certificate() {local host=""local target=""local actual=""- normalized=$(printf '%s' "$SERVER_FINGERPRINT" | tr -d ':[:space:]' | tr '[:upper:]' '[:lower:]')+ normalized=$(printf '%s' "$SERVER_FINGERPRINT" | tr -d ': \t\r\n\v\f' | LC_ALL=C tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz')if [[ ! "$normalized" =~ ^[a-f0-9]{64}$ ]]; thenfail "Invalid --server-fingerprint value. Expected a SHA-256 certificate fingerprint (64 hexadecimal characters)." "$EXIT_PREFLIGHT_FAILED"fi- authority="${PULSE_URL#https://}"+ authority="${PULSE_URL#*://}"authority="${authority%%/*}"if [[ "$authority" == \[*\]* ]]; thenhost="${authority#\[}"@@ -6744,8 +6744,10 @@ if [[ -z "$PULSE_URL" ]]; thenfail "Missing required argument: --url (or --pulse-url)" "$EXIT_MISSING_ARGS"fi# Validate URL format (basic check) - case-insensitive for http:// or https://-# Normalize to lowercase for the check-url_lower=$(echo "$PULSE_URL" | tr '[:upper:]' '[:lower:]')+# Use explicit ASCII alphabets: older NAS tr implementations can treat POSIX+# character classes literally and corrupt even an already-lowercase https URL.+# Keep the original endpoint unchanged for downloads and runtime policy admission.+url_lower=$(echo "$PULSE_URL" | LC_ALL=C tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz')if [[ ! "$url_lower" =~ ^https?:// ]]; thenfail "Invalid URL format. Must start with http:// or https://"fi@@ -7057,7 +7059,7 @@ if [[ "$PREFLIGHT_ONLY" == "true" ]]; thenjson_event "preflight" "checking" "Running preflight checks"# Check 1: Architecture- PF_OS=$(uname -s | tr '[:upper:]' '[:lower:]')+ PF_OS=$(uname -s | LC_ALL=C tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz')PF_ARCH=$(uname -m)case "$PF_ARCH" inx86_64|amd64) PF_ARCH="amd64" ;;@@ -7174,7 +7176,7 @@ if [[ "$PREFLIGHT_ONLY" == "true" ]]; thenfi# --- Download ----OS=$(uname -s | tr '[:upper:]' '[:lower:]')+OS=$(uname -s | LC_ALL=C tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz')ARCH=$(uname -m)case "$ARCH" indiff --git a/scripts/installtests/agent_installed_removal_transport_test.go b/scripts/installtests/agent_installed_removal_transport_test.gonew file mode 100644index 0000000000..4d88023a6d--- /dev/null+++ b/scripts/installtests/agent_installed_removal_transport_test.go@@ -0,0 +1,221 @@+package installtests++import (+ "context"+ "crypto/sha256"+ "encoding/json"+ "encoding/pem"+ "fmt"+ "io"+ "log"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strconv"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// Execute saved-state recovery and the initial removal caller with the real+// collector CLI, real TLS and authenticated POST/confirmation. Only service and+// process operations are doubles; erasure is restricted to private directories.+// This is not the root entry point, native systemd or an appliance installation.+func TestAgentInstalledRemovalSavedTransport(t *testing.T) {+ if runtime.GOOS != "linux" {+ t.Skip("confined Linux removal caller")+ }+ buildDir := t.TempDir()+ binary := filepath.Join(buildDir, "pulse-agent")+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)+ defer cancel()+ build := exec.CommandContext(ctx, "go", "build", "-o", binary, "./cmd/pulse-agent")+ build.Dir = repoFile()+ if out, err := build.CombinedOutput(); err != nil {+ t.Fatalf("build real installed CLI: %v\n%s", err, out)+ }+ if err := os.Chmod(binary, 0755); err != nil {+ t.Fatal(err)+ }+ bytes, err := os.ReadFile(binary)+ if err != nil {+ t.Fatal(err)+ }+ t.Logf("actual installed CLI sha256=%x bytes=%d", sha256.Sum256(bytes), len(bytes))+ sourceBytes, err := os.ReadFile(repoFile("scripts", "install.sh"))+ if err != nil {+ t.Fatal(err)+ }+ _, entry, ok := strings.Cut(string(sourceBytes), "# --- Uninstall Logic ---\n")+ if !ok {+ t.Fatal("missing removal entry")+ }+ entry, _, ok = strings.Cut(entry, " # Remove least-privilege helper artifacts.")+ if !ok {+ t.Fatal("missing confined initial teardown boundary")+ }+ entry += "fi\n"+ functions := ""+ for _, name := range []string{"portable_path_uid", "portable_path_mode", "trusted_lifecycle_regular_file",+ "trusted_connection_state_file", "trusted_private_lifecycle_regular_file", "read_connection_state_value",+ "recover_connection_state", "recover_token_from_default_agent_token_file", "read_collector_token_file_safely",+ "collector_lifecycle_binary", "prepare_collector_lifecycle_token_file", "run_collector_lifecycle_command",+ "collector_credential_state_present", "uninstall_collector_registration", "remove_authorized_runtime_dir",+ "remove_agent_state_dir", "remove_privileged_helper_state_dir", "remove_safe_profile_state_dir", "fail"} {+ functions += extractInstallShellFunction(t, name) + "\n"+ }+ for _, mode := range []string{"saved-ca", "saved-pin", "missing-ca", "wrong-pin", "server-refused", "other-identity", "nonloopback-http"} {+ t.Run(mode, func(t *testing.T) {+ var requests atomic.Int32+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests.Add(1)+ var body struct {+ AgentID string `json:"agentId"`+ }+ err := json.NewDecoder(r.Body).Decode(&body)+ if err != nil || r.Method != http.MethodPost || r.URL.Path != "/api/agents/agent/uninstall" ||+ r.Header.Get("Authorization") != "Bearer synthetic-runtime-credential" || body.AgentID != "saved-agent" {+ t.Error("removal request lost exact identity, private bearer or method/path")+ http.Error(w, "invalid fixture request", http.StatusBadRequest)+ return+ }+ if mode == "server-refused" {+ http.Error(w, "refused", http.StatusForbidden)+ } else if mode == "other-identity" {+ fmt.Fprint(w, `{"success":true,"agentId":"other-agent"}`)+ } else {+ fmt.Fprint(w, `{"success":true,"agentId":"saved-agent"}`)+ }+ }))+ server.Config.ErrorLog = log.New(io.Discard, "", 0)+ defer server.Close()+ root := t.TempDir()+ state, helper, profile := filepath.Join(root, "state"), filepath.Join(root, "helper"), filepath.Join(root, "profile")+ for _, path := range []string{state, helper, profile} {+ if err := os.Mkdir(path, 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(path, "sentinel"), []byte("preserve until confirmed\n"), 0600); err != nil {+ t.Fatal(err)+ }+ }+ url, ca, pin := server.URL, filepath.Join(state, "saved-ca.pem"), ""+ if mode == "saved-pin" {+ pin = fmt.Sprintf("%x", sha256.Sum256(server.Certificate().Raw))+ ca = ""+ } else if mode == "missing-ca" {+ ca = ""+ } else if mode == "wrong-pin" {+ pin = strings.Repeat("0", 64)+ } else if mode == "nonloopback-http" {+ url, ca = "http://192.0.2.1:7655", ""+ }+ saved := map[string][]byte{+ "agent-id": []byte("saved-agent\n"), "runtime.token": []byte("synthetic-runtime-credential\n"),+ "saved-ca.pem": pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}),+ "connection.env": []byte(fmt.Sprintf("PULSE_URL='%s'\nPULSE_AGENT_ID='saved-agent'\nPULSE_HOSTNAME='saved-host'\nPULSE_CACERT='%s'\nPULSE_SERVER_FINGERPRINT='%s'\nPULSE_INSECURE_SKIP_VERIFY='true'\n", url, ca, pin)),+ }+ for name, content := range saved {+ if err := os.WriteFile(filepath.Join(state, name), content, 0600); err != nil {+ t.Fatal(err)+ }+ }+ script := `set -euo pipefail+UNINSTALL=true AGENT_NAME=pulse-agent EXIT_GENERAL=1 EXIT_MISSING_ARGS=16+ACTION_RUNNER_NAME=pulse-agent-runner PRIVILEGED_HELPER_NAME=pulse-agent-helper+OUTPUT_FORMAT=text NON_INTERACTIVE=true+PULSE_TOKEN='' PULSE_URL='' CURL_CA_BUNDLE='' SERVER_FINGERPRINT=''+AGENT_ID='' HOSTNAME_OVERRIDE='' REPORT_IP='' RUNTIME_TOKEN_FILE=''+INSECURE=false STATE_DIR_SOURCE=explicit RETARGET_ONLY=false+LEAST_PRIVILEGE_USER=$(id -un)+log_info() { :; }+log_warn() { printf '%s\n' "$*"; }+log_error() { printf '%s\n' "$*"; }+nas_agent_removal_platform() { return 1; }+truenas_scale_agent_removal_present() { return 1; }+systemctl() { return 91; }+command() {+ if [[ "$*" == '-v rc-service' ]]; then return 1; fi+ builtin command "$@"+}+quiesce_agent_units_for_removal() {+ [[ "$*" == 'pulse-agent-runner.service pulse-agent-helper.socket pulse-agent-helper.service pulse-agent.service' ]] || return 90+ printf 'quiesce\n' >> "$EVENTS"+}+pkill() { printf 'process-stop\n' >> "$EVENTS"; }+sleep() { :; }+teardown_action_runner_service() { printf 'runner-teardown\n' >> "$EVENTS"; }+teardown_privileged_helper_service() { printf 'helper-teardown\n' >> "$EVENTS"; }+teardown_systemd_agent_service() { printf 'collector-teardown\n' >> "$EVENTS"; }+rm() {+ [[ $# == 3 && "$1" == -rf && "$2" == -- ]] || return 92+ [[ "$3" == "$STATE_DIR" || "$3" == "$PRIVILEGED_HELPER_STATE_DIR" || "$3" == "$SAFE_PROFILE_STATE_DIR" ]] || return 93+ printf 'state-remove\n' >> "$EVENTS"+ builtin command rm "$@"+}+`+ for key, value := range map[string]string{+ "STATE_DIR": state, "STATE_DIR_REMOVAL_AUTHORITY": state,+ "PRIVILEGED_HELPER_STATE_DIR": helper, "PRIVILEGED_HELPER_STATE_DIR_REMOVAL_AUTHORITY": helper,+ "PRIVILEGED_HELPER_CREDENTIAL_DIR": helper, "SAFE_PROFILE_STATE_DIR": profile,+ "SAFE_PROFILE_STATE_DIR_REMOVAL_AUTHORITY": profile, "COLLECTOR_LIFECYCLE_BINARY_PATH": binary,+ "EVENTS": filepath.Join(root, "events"),+ } {+ script += key + "=" + strconv.Quote(value) + "\n"+ }+ script += functions + "\nrecover_connection_state \"$STATE_DIR/connection.env\"\nmain() {\n" + entry + "}\nmain\n"+ runCtx, stop := context.WithTimeout(context.Background(), 20*time.Second)+ defer stop()+ out, err := exec.CommandContext(runCtx, "bash", "-c", script).CombinedOutput()+ wantSuccess := mode == "saved-ca" || mode == "saved-pin"+ if (err == nil) != wantSuccess || runCtx.Err() != nil || strings.Contains(string(out), "synthetic-runtime-credential") {+ t.Fatalf("removal success=%t timeout=%v error=%v\n%s", wantSuccess, runCtx.Err(), err, out)+ }+ events, readErr := os.ReadFile(filepath.Join(root, "events"))+ if readErr != nil {+ t.Fatal(readErr)+ }+ wantRequests := int32(0)+ if wantSuccess || mode == "server-refused" || mode == "other-identity" {+ wantRequests = 1+ }+ if requests.Load() != wantRequests {+ t.Fatalf("removal requests=%d want=%d", requests.Load(), wantRequests)+ }+ if wantSuccess {+ if string(events) != "quiesce\nprocess-stop\nprocess-stop\nrunner-teardown\nhelper-teardown\ncollector-teardown\nstate-remove\nstate-remove\nstate-remove\n" {+ t.Fatalf("wrong confirmed teardown sequence: %s", events)+ }+ for _, path := range []string{state, helper, profile} {+ if _, err := os.Stat(path); !os.IsNotExist(err) {+ t.Fatalf("confirmed removal retained selected fixture %s", path)+ }+ }+ } else {+ // Quiescence may already have stopped and disabled services. It+ // is not rolled back or described as an unchanged installation.+ if string(events) != "quiesce\n" || !strings.Contains(string(out), "local credentials and services were retained") {+ t.Fatalf("unconfirmed removal proceeded to erasure: %s\n%s", events, out)+ }+ for name, want := range saved {+ path := filepath.Join(state, name)+ got, err := os.ReadFile(path)+ info, statErr := os.Stat(path)+ if err != nil || statErr != nil || string(got) != string(want) || info.Mode().Perm() != 0600 {+ t.Fatalf("refused removal mutated saved %s", name)+ }+ }+ for _, path := range []string{state, helper, profile} {+ if got, err := os.ReadFile(filepath.Join(path, "sentinel")); err != nil || string(got) != "preserve until confirmed\n" {+ t.Fatalf("refused removal lost recovery sentinel: %s %v", path, err)+ }+ }+ }+ t.Logf("mode=%s authenticated_requests=%d confirmed=%t recovery_retained=%t", mode, requests.Load(), wantSuccess, !wantSuccess)+ })+ }+}diff --git a/scripts/installtests/agent_portable_tr_test.go b/scripts/installtests/agent_portable_tr_test.gonew file mode 100644index 0000000000..c29ce02a7f--- /dev/null+++ b/scripts/installtests/agent_portable_tr_test.go@@ -0,0 +1,207 @@+package installtests++import (+ "context"+ "crypto/sha256"+ "encoding/pem"+ "fmt"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "testing"+ "time"+)++// Model tr implementations that treat POSIX classes as literal characters.+// This is deliberately not an assertion about the reporter's native QNAP tr.+func classlessTREnvironment(t *testing.T) []string {+ t.Helper()+ tr, err := exec.LookPath("tr")+ if err != nil {+ t.Fatal(err)+ }+ dir := t.TempDir()+ wrapper := `#!/usr/bin/env python3+import os, sys+args = sys.argv[1:]+for name in ("upper", "lower", "space"):+ args = [arg.replace("[:" + name + ":]", "\\[:" + name + ":\\]") for arg in args]+os.execv(` + fmt.Sprintf("%q", tr) + `, ["tr"] + args)+`+ if err := os.WriteFile(filepath.Join(dir, "tr"), []byte(wrapper), 0700); err != nil {+ t.Fatal(err)+ }+ env := append(os.Environ(), "PATH="+dir+string(os.PathListSeparator)+os.Getenv("PATH"))+ // Admit the model only when it reproduces the original corruption. A+ // passing control using an ordinary class-aware tr would prove nothing.+ cmd := exec.Command("bash", "-c", `printf https:// | tr '[:upper:]' '[:lower:]'`)+ cmd.Env = env+ if out, err := cmd.CombinedOutput(); err != nil || string(out) != "httws://" {+ t.Fatalf("classless tr control: %v, %q", err, out)+ }+ return env+}++func TestAgentInstallerPortableTRPreflight(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("Unix installer")+ }+ if _, err := exec.LookPath("openssl"); err != nil {+ t.Fatal("installer fingerprint prerequisite openssl missing")+ }+ classless := classlessTREnvironment(t)+ for _, tc := range []struct {+ name, scheme, pin string+ classless bool+ wantExit int+ }{+ {"ordinary-https", "https", "correct", false, 0},+ {"classless-https", "https", "correct", true, 0},+ {"classless-mixed-https", "hTtPs", "correct", true, 0},+ {"classless-malformed-url", "missing", "none", true, 1},+ {"classless-wrong-pin", "https", "wrong", true, 14},+ {"classless-malformed-pin", "https", "malformed", true, 14},+ {"classless-http-pin-despite-insecure", "http", "correct", true, 14},+ } {+ t.Run(tc.name, func(t *testing.T) {+ var mu sync.Mutex+ var requests []string+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ requests = append(requests, r.Method+" "+r.URL.RequestURI())+ mu.Unlock()+ switch r.URL.Path {+ case "/api/health":+ w.WriteHeader(http.StatusOK)+ case "/download/pulse-agent":+ w.Header().Set("X-Checksum-Sha256", strings.Repeat("a", 64))+ w.WriteHeader(http.StatusOK)+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ dir := t.TempDir()+ caPath := filepath.Join(dir, "saved-ca.pem")+ ca := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw})+ saved := map[string][]byte{+ "saved-ca.pem": ca, "agent-id": []byte("saved-id\n"),+ "runtime.token": []byte("synthetic-runtime-credential\n"),+ "connection.env": []byte("saved connection sentinel\n"),+ "pulse-agent": []byte("installed predecessor sentinel\n"),+ }+ for name, content := range saved {+ if err := os.WriteFile(filepath.Join(dir, name), content, 0600); err != nil {+ t.Fatal(err)+ }+ }+ url := strings.Replace(server.URL, "https", tc.scheme, 1)+ if tc.scheme == "missing" {+ url = "pulse.invalid"+ }+ args := []string{repoFile("scripts", "install.sh"), "--url", url, "--cacert", caPath,+ "--state-dir", dir, "--preflight-only", "--output", "json", "--non-interactive",+ "--disable-docker", "--disable-kubernetes", "--disable-proxmox"}+ if tc.pin != "none" {+ pin := fmt.Sprintf("%X", sha256.Sum256(server.Certificate().Raw))+ if tc.pin == "wrong" {+ pin = strings.Repeat("0", 64)+ } else if tc.pin == "malformed" {+ pin = strings.Repeat("Z", 64)+ }+ var pairs []string+ for i := 0; i < len(pin); i += 2 {+ pairs = append(pairs, pin[i:i+2])+ }+ args = append(args, "--server-fingerprint", " \t"+strings.Join(pairs, ":")+"\r\n\v\f")+ }+ if tc.scheme == "http" {+ args = append(args, "--insecure")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, "bash", args...)+ if tc.classless {+ cmd.Env = classless+ }+ out, err := cmd.CombinedOutput()+ exit := 0+ if err != nil {+ if failure, ok := err.(*exec.ExitError); ok {+ exit = failure.ExitCode()+ } else {+ t.Fatal(err)+ }+ }+ if exit != tc.wantExit || ctx.Err() != nil {+ t.Fatalf("preflight exit=%d want=%d timeout=%v\n%s", exit, tc.wantExit, ctx.Err(), out)+ }+ mu.Lock()+ observed := append([]string(nil), requests...)+ mu.Unlock()+ if tc.wantExit == 0 {+ want := "HEAD /download/pulse-agent?arch=" + runtime.GOOS + "-" + runtime.GOARCH+ if strings.Join(observed, "\n") != "GET /api/health\n"+want ||+ !strings.Contains(string(out), `"code":"ok"`) {+ t.Fatalf("wrong OS/download/preflight result: %v\n%s", observed, out)+ }+ } else if len(observed) != 0 || strings.Contains(string(out), `"code":"ok"`) {+ t.Fatalf("refused URL/pin reached HTTP or claimed success: %v\n%s", observed, out)+ }+ for name, want := range saved {+ path := filepath.Join(dir, name)+ got, err := os.ReadFile(path)+ info, statErr := os.Stat(path)+ if err != nil || statErr != nil || string(got) != string(want) || info.Mode().Perm() != 0600 {+ t.Fatalf("preflight mutated saved %s", name)+ }+ }+ if entries, err := os.ReadDir(dir); err != nil || len(entries) != len(saved) {+ t.Fatalf("preflight added saved state: %v %v", entries, err)+ }+ })+ }+}++func TestAgentInstallerPortableTRIdentityAndTransport(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("Unix installer")+ }+ script := "set -euo pipefail\n"+ for _, name := range []string{"resolve_safe_profile_hostname", "pulse_url_uses_plain_http",+ "action_runner_url_uses_loopback_http", "action_runner_url_transport_allowed",+ "generate_action_runner_activation_nonce", "systemd_effective_words_equal"} {+ script += extractInstallShellFunction(t, name) + "\n"+ }+ script += `+HOSTNAME_OVERRIDE='NODE-UPPER.Example.'+resolve_safe_profile_hostname+[[ "$HOSTNAME_OVERRIDE" == node-upper.example ]]+pulse_url_uses_plain_http 'HtTp://pulse.invalid'+! pulse_url_uses_plain_http 'HTTPS://pulse.invalid'+action_runner_url_transport_allowed 'HTTPS://pulse.invalid'+action_runner_url_transport_allowed 'HtTp://LOCALHOST:7655'+action_runner_url_transport_allowed 'http://127.2.3.4:7655'+action_runner_url_transport_allowed 'http://[::1]:7655'+for url in 'http://pulse.invalid' 'http://192.168.1.2' 'http://127.999.1.2' \+ 'https://[email protected]' 'https://pulse.invalid/with space' 'pulse.invalid'; do+ ! action_runner_url_transport_allowed "$url"+done+nonce=$(generate_action_runner_activation_nonce)+[[ "$nonce" =~ ^[a-f0-9]{64}$ ]]+systemd_effective_unit_property() { printf 'unix\tinet\r\ninet6\vunix\f'; }+systemd_effective_words_equal unit RestrictAddressFamilies inet6 unix inet+! systemd_effective_words_equal unit RestrictAddressFamilies unix inet+printf 'portable identity, nonce, word-set and transport controls passed\n'+`+ cmd := exec.Command("bash", "-c", script)+ cmd.Env = classlessTREnvironment(t)+ if out, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("classless downstream controls: %v\n%s", err, out)+ }+}diff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.goindex 86f5e2ee09..0cf519524f 100644--- a/scripts/installtests/install_sh_test.go+++ b/scripts/installtests/install_sh_test.go@@ -2849,7 +2849,7 @@ func TestInstallSHFreeBSDRendererUsesDaemonSupervisorPidfile(t *testing.T) {required := []string{`child_pidfile="/var/run/\${name}.child.pid"`,`pulse_agent_supervisor_pid()`,- `parent_pid=\$(ps -o ppid= -p "\${agent_pid}" 2>/dev/null | tr -d '[:space:]')`,+ `parent_pid=\$(ps -o ppid= -p "\${agent_pid}" 2>/dev/null | tr -d ' \t\r\n\v\f')`,`daemon:*)`,`/usr/sbin/daemon -r -P \${pidfile} -p \${child_pidfile} -f "\${command}" \${command_args}`,`kill -KILL "\${supervisor_pid}" 2>/dev/null || return 1`,