Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

fix(proxmox): prevent setup-script token drift and add lifecycle integration tests (#1312)

rcourtman8818a740e29b
diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.go
index bf42297534..5cbb8c7361 100644
--- a/internal/api/config_handlers.go
+++ b/internal/api/config_handlers.go
@@ -4164,9 +4164,9 @@ pveum user add pulse-monitor@pam --comment "Pulse monitoring service" 2>/dev/nul
SETUP_AUTH_TOKEN="%s"
AUTO_REG_SUCCESS=false
+TOKEN_ROTATION_SKIPPED=false
-attempt_auto_registration() {
-
+resolve_setup_auth_token() {
if [ -z "$SETUP_AUTH_TOKEN" ] && [ -n "$PULSE_SETUP_TOKEN" ]; then
SETUP_AUTH_TOKEN="$PULSE_SETUP_TOKEN"
fi
@@ -4186,9 +4186,18 @@ attempt_auto_registration() {
printf "\n" >/dev/tty
fi
fi
+}
+
+attempt_auto_registration() {
+ resolve_setup_auth_token
if [ -z "$TOKEN_VALUE" ]; then
- echo "⚠️ Auto-registration skipped: token value unavailable"
+ if [ "$TOKEN_ROTATION_SKIPPED" = true ]; then
+ echo "⚠️ Auto-registration skipped: existing token preserved to avoid credential drift"
+ echo " Set PULSE_FORCE_TOKEN_ROTATE=1 if you need to rotate and register a new token."
+ else
+ echo "⚠️ Auto-registration skipped: token value unavailable"
+ fi
AUTO_REG_SUCCESS=false
REGISTER_RESPONSE=""
return
@@ -4258,50 +4267,57 @@ attempt_auto_registration() {
# Generate API token
echo "Generating API token..."
-# Rotate token if it already exists so reruns remain idempotent
+# Keep existing tokens by default so reruns cannot silently desynchronize Pulse credentials.
TOKEN_EXISTED=false
TOKEN_OUTPUT=""
TOKEN_VALUE=""
if pveum user token list pulse-monitor@pam 2>/dev/null | grep -q "$TOKEN_NAME"; then
TOKEN_EXISTED=true
- echo "Existing token '$TOKEN_NAME' found. Rotating in place..."
- if ! pveum user token remove pulse-monitor@pam "$TOKEN_NAME" >/dev/null 2>&1; then
- echo "⚠️ Failed to remove existing token '$TOKEN_NAME'. Attempting create anyway..."
+ if [ "${PULSE_FORCE_TOKEN_ROTATE:-}" = "1" ]; then
+ echo "Existing token '$TOKEN_NAME' found. Rotating in place (PULSE_FORCE_TOKEN_ROTATE=1)."
+ if ! pveum user token remove pulse-monitor@pam "$TOKEN_NAME" >/dev/null 2>&1; then
+ echo "⚠️ Failed to remove existing token '$TOKEN_NAME'. Attempting create anyway..."
+ fi
+ else
+ TOKEN_ROTATION_SKIPPED=true
+ echo "Existing token '$TOKEN_NAME' found. Keeping it unchanged to avoid breaking existing Pulse credentials."
+ echo "Set PULSE_FORCE_TOKEN_ROTATE=1 to rotate this token and issue a new secret."
fi
fi
-# Create token and capture value (shown once by Proxmox)
-TOKEN_OUTPUT=$(pveum user token add pulse-monitor@pam "$TOKEN_NAME" --privsep 0 2>&1)
-TOKEN_CREATE_RC=$?
-if [ "$TOKEN_CREATE_RC" -ne 0 ]; then
- echo "❌ Failed to create token '$TOKEN_NAME'"
- echo "$TOKEN_OUTPUT"
- echo ""
- echo "Manual registration may be required."
- echo ""
-else
- TOKEN_VALUE=$(echo "$TOKEN_OUTPUT" | grep "│ value" | awk -F'│' '{print $3}' | tr -d ' ' | tail -1)
-
- if [ -z "$TOKEN_VALUE" ]; then
- echo ""
- echo "================================================================"
- echo "IMPORTANT: Copy the token value below - it's only shown once!"
- echo "================================================================"
+if [ "$TOKEN_ROTATION_SKIPPED" != true ]; then
+ # Create token and capture value (shown once by Proxmox)
+ TOKEN_OUTPUT=$(pveum user token add pulse-monitor@pam "$TOKEN_NAME" --privsep 0 2>&1)
+ TOKEN_CREATE_RC=$?
+ if [ "$TOKEN_CREATE_RC" -ne 0 ]; then
+ echo "❌ Failed to create token '$TOKEN_NAME'"
echo "$TOKEN_OUTPUT"
- echo "================================================================"
echo ""
- echo "⚠️ Failed to extract token value from output."
- echo " Manual registration may be required."
+ echo "Manual registration may be required."
echo ""
else
- if [ "$TOKEN_EXISTED" = true ]; then
- echo "API token rotated successfully"
+ TOKEN_VALUE=$(echo "$TOKEN_OUTPUT" | grep "│ value" | awk -F'│' '{print $3}' | tr -d ' ' | tail -1)
+
+ if [ -z "$TOKEN_VALUE" ]; then
+ echo ""
+ echo "================================================================"
+ echo "IMPORTANT: Copy the token value below - it's only shown once!"
+ echo "================================================================"
+ echo "$TOKEN_OUTPUT"
+ echo "================================================================"
+ echo ""
+ echo "⚠️ Failed to extract token value from output."
+ echo " Manual registration may be required."
+ echo ""
else
- echo "API token generated successfully"
+ if [ "$TOKEN_EXISTED" = true ]; then
+ echo "API token rotated successfully"
+ else
+ echo "API token generated successfully"
+ fi
+ echo ""
fi
- echo ""
fi
-
fi
# Set up permissions
@@ -4549,7 +4565,9 @@ echo ""
if [ "$AUTO_REG_SUCCESS" != true ]; then
echo "Manual setup instructions:"
echo " Token ID: $PULSE_TOKEN_ID"
- if [ -n "$TOKEN_VALUE" ]; then
+ if [ "$TOKEN_ROTATION_SKIPPED" = true ]; then
+ echo " Token Value: [unchanged - existing token secret preserved]"
+ elif [ -n "$TOKEN_VALUE" ]; then
echo " Token Value: $TOKEN_VALUE"
else
echo " Token Value: [See token output above]"
@@ -4656,80 +4674,89 @@ proxmox-backup-manager user create pulse-monitor@pbs 2>/dev/null || echo "User a
# Generate API token
echo "Generating API token..."
-# Rotate token if it already exists so reruns remain idempotent
+# Keep existing tokens by default so reruns cannot silently desynchronize Pulse credentials.
TOKEN_EXISTED=false
TOKEN_OUTPUT=""
TOKEN_VALUE=""
+TOKEN_ROTATION_SKIPPED=false
+AUTO_REG_SUCCESS=false
if proxmox-backup-manager user list-tokens pulse-monitor@pbs 2>/dev/null | grep -q "$TOKEN_NAME"; then
TOKEN_EXISTED=true
- echo "Existing token '$TOKEN_NAME' found. Rotating in place..."
- if ! proxmox-backup-manager user delete-token pulse-monitor@pbs "$TOKEN_NAME" >/dev/null 2>&1; then
- echo "⚠️ Failed to remove existing token '$TOKEN_NAME'. Attempting create anyway..."
+ if [ "${PULSE_FORCE_TOKEN_ROTATE:-}" = "1" ]; then
+ echo "Existing token '$TOKEN_NAME' found. Rotating in place (PULSE_FORCE_TOKEN_ROTATE=1)."
+ if ! proxmox-backup-manager user delete-token pulse-monitor@pbs "$TOKEN_NAME" >/dev/null 2>&1; then
+ echo "⚠️ Failed to remove existing token '$TOKEN_NAME'. Attempting create anyway..."
+ fi
+ else
+ TOKEN_ROTATION_SKIPPED=true
+ echo "Existing token '$TOKEN_NAME' found. Keeping it unchanged to avoid breaking existing Pulse credentials."
+ echo "Set PULSE_FORCE_TOKEN_ROTATE=1 to rotate this token and issue a new secret."
fi
fi
-echo ""
-echo "================================================================"
-echo "IMPORTANT: Copy the token value below - it's only shown once!"
-echo "================================================================"
-TOKEN_OUTPUT=$(proxmox-backup-manager user generate-token pulse-monitor@pbs "$TOKEN_NAME" 2>&1)
-TOKEN_CREATE_RC=$?
-if [ "$TOKEN_CREATE_RC" -ne 0 ]; then
- echo "❌ Failed to create token '$TOKEN_NAME'"
- echo "$TOKEN_OUTPUT"
- echo ""
- echo "Manual registration may be required."
+if [ "$TOKEN_ROTATION_SKIPPED" != true ]; then
echo ""
-else
- echo "$TOKEN_OUTPUT"
-
- # Extract the token value for auto-registration
- TOKEN_VALUE=$(echo "$TOKEN_OUTPUT" | grep '"value"' | sed 's/.*"value"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')
-
- if [ -z "$TOKEN_VALUE" ]; then
- echo "⚠️ Failed to extract token value from output."
- echo " Manual registration may be required."
+ echo "================================================================"
+ echo "IMPORTANT: Copy the token value below - it's only shown once!"
+ echo "================================================================"
+ TOKEN_OUTPUT=$(proxmox-backup-manager user generate-token pulse-monitor@pbs "$TOKEN_NAME" 2>&1)
+ TOKEN_CREATE_RC=$?
+ if [ "$TOKEN_CREATE_RC" -ne 0 ]; then
+ echo "❌ Failed to create token '$TOKEN_NAME'"
+ echo "$TOKEN_OUTPUT"
+ echo ""
+ echo "Manual registration may be required."
echo ""
else
- if [ "$TOKEN_EXISTED" = true ]; then
- echo "✅ Token rotated for Pulse monitoring"
+ echo "$TOKEN_OUTPUT"
+
+ # Extract the token value for auto-registration
+ TOKEN_VALUE=$(echo "$TOKEN_OUTPUT" | grep '"value"' | sed 's/.*"value"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')
+
+ if [ -z "$TOKEN_VALUE" ]; then
+ echo "⚠️ Failed to extract token value from output."
+ echo " Manual registration may be required."
+ echo ""
else
- echo "✅ Token created for Pulse monitoring"
+ if [ "$TOKEN_EXISTED" = true ]; then
+ echo "✅ Token rotated for Pulse monitoring"
+ else
+ echo "✅ Token created for Pulse monitoring"
+ fi
+ echo ""
fi
- echo ""
- fi
- # Try auto-registration
- echo "🔄 Attempting auto-registration with Pulse..."
- echo ""
+ # Try auto-registration
+ echo "🔄 Attempting auto-registration with Pulse..."
+ echo ""
- # Use auth token from URL parameter when provided (automation workflows)
- AUTH_TOKEN="%s"
+ # Use auth token from URL parameter when provided (automation workflows)
+ AUTH_TOKEN="%s"
- # Allow non-interactive override via environment variable
- if [ -z "$AUTH_TOKEN" ] && [ -n "$PULSE_SETUP_TOKEN" ]; then
- AUTH_TOKEN="$PULSE_SETUP_TOKEN"
- fi
+ # Allow non-interactive override via environment variable
+ if [ -z "$AUTH_TOKEN" ] && [ -n "$PULSE_SETUP_TOKEN" ]; then
+ AUTH_TOKEN="$PULSE_SETUP_TOKEN"
+ fi
- # Prompt the operator if we still don't have a token and a TTY is available
- if [ -z "$AUTH_TOKEN" ]; then
- if [ -t 0 ]; then
- printf "Pulse setup token: "
- if command -v stty >/dev/null 2>&1; then stty -echo; fi
- IFS= read -r AUTH_TOKEN
- if command -v stty >/dev/null 2>&1; then stty echo; fi
- printf "\n"
+ # Prompt the operator if we still don't have a token and a TTY is available
+ if [ -z "$AUTH_TOKEN" ]; then
+ if [ -t 0 ]; then
+ printf "Pulse setup token: "
+ if command -v stty >/dev/null 2>&1; then stty -echo; fi
+ IFS= read -r AUTH_TOKEN
+ if command -v stty >/dev/null 2>&1; then stty echo; fi
+ printf "\n"
elif [ -c /dev/tty ] && [ -r /dev/tty ] && [ -w /dev/tty ]; then
printf "Pulse setup token: " >/dev/tty
if command -v stty >/dev/null 2>&1; then stty -echo </dev/tty 2>/dev/null || true; fi
IFS= read -r AUTH_TOKEN </dev/tty || true
if command -v stty >/dev/null 2>&1; then stty echo </dev/tty 2>/dev/null || true; fi
printf "\n" >/dev/tty
+ fi
fi
- fi
- # Only proceed with auto-registration if we have an auth token
- if [ -n "$AUTH_TOKEN" ]; then
+ # Only proceed with auto-registration if we have an auth token
+ if [ -n "$AUTH_TOKEN" ]; then
# Get the server's hostname (short form to match Pulse node names)
SERVER_HOSTNAME=$(hostname -s 2>/dev/null || hostname)
SERVER_IP=$(hostname -I | awk '{print $1}')
@@ -4773,39 +4800,39 @@ EOF
REGISTER_JSON=$(echo "$REGISTER_JSON" | tr -d '\n')
# Send registration with setup code
- REGISTER_RESPONSE=$(curl -s -X POST "$PULSE_URL/api/auto-register" \
- -H "Content-Type: application/json" \
- -d "$REGISTER_JSON" 2>&1)
- else
- echo "⚠️ Auto-registration skipped: no setup token provided"
+ REGISTER_RESPONSE=$(curl -s -X POST "$PULSE_URL/api/auto-register" \
+ -H "Content-Type: application/json" \
+ -d "$REGISTER_JSON" 2>&1)
+ else
+ echo "⚠️ Auto-registration skipped: no setup token provided"
+ AUTO_REG_SUCCESS=false
+ REGISTER_RESPONSE=""
+ fi
+
AUTO_REG_SUCCESS=false
- REGISTER_RESPONSE=""
- fi
-
- AUTO_REG_SUCCESS=false
- if echo "$REGISTER_RESPONSE" | grep -q "success"; then
- AUTO_REG_SUCCESS=true
- echo "✅ Successfully registered with Pulse!"
- else
- if echo "$REGISTER_RESPONSE" | grep -q "Authentication required"; then
- echo "Error: Auto-registration failed - authentication required"
- echo ""
- if [ -z "$PULSE_API_TOKEN" ]; then
- echo "To enable auto-registration, add your API token to the setup URL"
- echo "You can find your API token in Pulse Settings → Security"
+ if echo "$REGISTER_RESPONSE" | grep -q "success"; then
+ AUTO_REG_SUCCESS=true
+ echo "✅ Successfully registered with Pulse!"
+ else
+ if echo "$REGISTER_RESPONSE" | grep -q "Authentication required"; then
+ echo "Error: Auto-registration failed - authentication required"
+ echo ""
+ if [ -z "$PULSE_API_TOKEN" ]; then
+ echo "To enable auto-registration, add your API token to the setup URL"
+ echo "You can find your API token in Pulse Settings → Security"
+ else
+ echo "The provided API token was invalid"
+ fi
else
- echo "The provided API token was invalid"
+ echo "⚠️ Auto-registration failed. Manual configuration may be needed."
+ echo " Response: $REGISTER_RESPONSE"
fi
- else
- echo "⚠️ Auto-registration failed. Manual configuration may be needed."
- echo " Response: $REGISTER_RESPONSE"
+ echo ""
+ echo "📝 For manual setup:"
+ echo " 1. Copy the token value shown above"
+ echo " 2. Add this node manually in Pulse Settings"
fi
- echo ""
- echo "📝 For manual setup:"
- echo " 1. Copy the token value shown above"
- echo " 2. Add this node manually in Pulse Settings"
fi
- echo ""
fi
echo "================================================================"
echo ""
@@ -4823,7 +4850,9 @@ echo ""
if [ "$AUTO_REG_SUCCESS" != true ]; then
echo "Add this server to Pulse with:"
echo " Token ID: $PULSE_TOKEN_ID"
- if [ -n "$TOKEN_VALUE" ]; then
+ if [ "$TOKEN_ROTATION_SKIPPED" = true ]; then
+ echo " Token Value: [unchanged - existing token secret preserved]"
+ elif [ -n "$TOKEN_VALUE" ]; then
echo " Token Value: $TOKEN_VALUE"
else
echo " Token Value: [Check the output above for the token or instructions]"
diff --git a/internal/api/config_handlers_setup_script_integration_test.go b/internal/api/config_handlers_setup_script_integration_test.go
new file mode 100644
index 0000000000..4d69011106
--- /dev/null
+++ b/internal/api/config_handlers_setup_script_integration_test.go
@@ -0,0 +1,315 @@
+package api
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+const integrationSetupAuthToken = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
+
+func TestSetupScriptTokenLifecycleIntegration_PVE(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("requires bash-compatible environment")
+ }
+
+ script := generateSetupScriptForIntegration(t, "pve")
+ section := extractSetupScriptSection(t, script, "SETUP_AUTH_TOKEN=\"", "# Set up permissions")
+
+ harness := fmt.Sprintf(`#!/usr/bin/env bash
+set -eo pipefail
+PULSE_URL="http://SENTINEL_URL:7656"
+SERVER_HOST="http://SENTINEL_HOST:8006"
+TOKEN_NAME="pulse-sentinel-url"
+PULSE_TOKEN_ID="pulse-monitor@pam!${TOKEN_NAME}"
+PULSE_API_TOKEN=""
+%s
+attempt_auto_registration
+echo "STATE AUTO_REG_SUCCESS=${AUTO_REG_SUCCESS} TOKEN_ROTATION_SKIPPED=${TOKEN_ROTATION_SKIPPED} TOKEN_VALUE=${TOKEN_VALUE}"
+`, section)
+
+ mocks := pveHarnessMockBinaries()
+
+ t.Run("preserves_existing_token_by_default", func(t *testing.T) {
+ output, trace := runSetupHarness(t, harness, mocks, map[string]string{
+ "MOCK_TOKEN_EXISTS": "1",
+ })
+
+ assertContains(t, output, "Keeping it unchanged to avoid breaking existing Pulse credentials")
+ assertContains(t, output, "Auto-registration skipped: existing token preserved to avoid credential drift")
+ assertContains(t, output, "STATE AUTO_REG_SUCCESS=false TOKEN_ROTATION_SKIPPED=true TOKEN_VALUE=")
+
+ assertContains(t, trace, "pveum user token list pulse-monitor@pam")
+ assertNotContains(t, trace, "pveum user token remove pulse-monitor@pam pulse-sentinel-url")
+ assertNotContains(t, trace, "pveum user token add pulse-monitor@pam pulse-sentinel-url --privsep 0")
+ assertNotContains(t, trace, "curl -s -X POST")
+ })
+
+ t.Run("force_rotate_rotates_and_auto_registers", func(t *testing.T) {
+ output, trace := runSetupHarness(t, harness, mocks, map[string]string{
+ "MOCK_TOKEN_EXISTS": "1",
+ "PULSE_FORCE_TOKEN_ROTATE": "1",
+ })
+
+ assertContains(t, output, "API token rotated successfully")
+ assertContains(t, output, "Node registered successfully")
+ assertContains(t, output, "STATE AUTO_REG_SUCCESS=true TOKEN_ROTATION_SKIPPED=false TOKEN_VALUE=mocked-pve-secret")
+
+ assertContains(t, trace, "pveum user token remove pulse-monitor@pam pulse-sentinel-url")
+ assertContains(t, trace, "pveum user token add pulse-monitor@pam pulse-sentinel-url --privsep 0")
+ assertContains(t, trace, "curl -s -X POST")
+ })
+}
+
+func TestSetupScriptTokenLifecycleIntegration_PBS(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("requires bash-compatible environment")
+ }
+
+ script := generateSetupScriptForIntegration(t, "pbs")
+ section := extractSetupScriptSection(t, script, "# Generate API token", "# Set up permissions")
+
+ harness := fmt.Sprintf(`#!/usr/bin/env bash
+set -eo pipefail
+TOKEN_NAME="pulse-sentinel-url"
+PULSE_TOKEN_ID="pulse-monitor@pbs!${TOKEN_NAME}"
+PULSE_API_TOKEN=""
+%s
+echo "STATE AUTO_REG_SUCCESS=${AUTO_REG_SUCCESS} TOKEN_ROTATION_SKIPPED=${TOKEN_ROTATION_SKIPPED} TOKEN_VALUE=${TOKEN_VALUE}"
+`, section)
+
+ mocks := pbsHarnessMockBinaries()
+
+ t.Run("preserves_existing_token_by_default", func(t *testing.T) {
+ output, trace := runSetupHarness(t, harness, mocks, map[string]string{
+ "MOCK_TOKEN_EXISTS": "1",
+ })
+
+ assertContains(t, output, "Keeping it unchanged to avoid breaking existing Pulse credentials")
+ assertContains(t, output, "STATE AUTO_REG_SUCCESS=false TOKEN_ROTATION_SKIPPED=true TOKEN_VALUE=")
+
+ assertContains(t, trace, "proxmox-backup-manager user list-tokens pulse-monitor@pbs")
+ assertNotContains(t, trace, "proxmox-backup-manager user delete-token pulse-monitor@pbs pulse-sentinel-url")
+ assertNotContains(t, trace, "proxmox-backup-manager user generate-token pulse-monitor@pbs pulse-sentinel-url")
+ assertNotContains(t, trace, "curl -s -X POST")
+ })
+
+ t.Run("force_rotate_rotates_and_auto_registers", func(t *testing.T) {
+ output, trace := runSetupHarness(t, harness, mocks, map[string]string{
+ "MOCK_TOKEN_EXISTS": "1",
+ "PULSE_FORCE_TOKEN_ROTATE": "1",
+ })
+
+ assertContains(t, output, "Token rotated for Pulse monitoring")
+ assertContains(t, output, "Successfully registered with Pulse")
+ assertContains(t, output, "STATE AUTO_REG_SUCCESS=true TOKEN_ROTATION_SKIPPED=false TOKEN_VALUE=mocked-pbs-secret")
+
+ assertContains(t, trace, "proxmox-backup-manager user delete-token pulse-monitor@pbs pulse-sentinel-url")
+ assertContains(t, trace, "proxmox-backup-manager user generate-token pulse-monitor@pbs pulse-sentinel-url")
+ assertContains(t, trace, "curl -s -X POST")
+ })
+}
+
+func generateSetupScriptForIntegration(t *testing.T, nodeType string) string {
+ t.Helper()
+
+ tempDir := t.TempDir()
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ }
+ handlers := newTestConfigHandlers(t, cfg)
+
+ var reqPath string
+ switch nodeType {
+ case "pve":
+ reqPath = fmt.Sprintf("/api/setup-script?type=pve&host=http://SENTINEL_HOST:8006&pulse_url=http://SENTINEL_URL:7656&auth_token=%s", integrationSetupAuthToken)
+ case "pbs":
+ reqPath = fmt.Sprintf("/api/setup-script?type=pbs&host=https://192.168.0.10:8007&pulse_url=http://SENTINEL_URL:7656&auth_token=%s", integrationSetupAuthToken)
+ default:
+ t.Fatalf("unsupported node type: %s", nodeType)
+ }
+
+ req := httptest.NewRequest(http.MethodGet, reqPath, nil)
+ rr := httptest.NewRecorder()
+ handlers.HandleSetupScript(rr, req)
+
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected 200 OK, got %d (%s)", rr.Code, rr.Body.String())
+ }
+
+ return rr.Body.String()
+}
+
+func extractSetupScriptSection(t *testing.T, script, startMarker, endMarker string) string {
+ t.Helper()
+
+ start := strings.Index(script, startMarker)
+ if start == -1 {
+ t.Fatalf("start marker not found: %q", startMarker)
+ }
+
+ remainder := script[start:]
+ end := strings.Index(remainder, endMarker)
+ if end == -1 {
+ t.Fatalf("end marker not found: %q", endMarker)
+ }
+
+ return remainder[:end]
+}
+
+func runSetupHarness(t *testing.T, harness string, mockBinaries map[string]string, extraEnv map[string]string) (output string, trace string) {
+ t.Helper()
+
+ root := t.TempDir()
+ binDir := filepath.Join(root, "bin")
+ if err := os.MkdirAll(binDir, 0o755); err != nil {
+ t.Fatalf("mkdir bin dir: %v", err)
+ }
+
+ for name, content := range mockBinaries {
+ path := filepath.Join(binDir, name)
+ if err := os.WriteFile(path, []byte(content), 0o755); err != nil {
+ t.Fatalf("write mock %s: %v", name, err)
+ }
+ }
+
+ harnessPath := filepath.Join(root, "harness.sh")
+ if err := os.WriteFile(harnessPath, []byte(harness), 0o755); err != nil {
+ t.Fatalf("write harness: %v", err)
+ }
+
+ tracePath := filepath.Join(root, "trace.log")
+ cmd := exec.Command("bash", harnessPath)
+ env := append(os.Environ(),
+ "PATH="+binDir+":/usr/bin:/bin",
+ "TRACE_FILE="+tracePath,
+ )
+ for k, v := range extraEnv {
+ env = append(env, k+"="+v)
+ }
+ cmd.Env = env
+
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("harness execution failed: %v\noutput:\n%s", err, string(out))
+ }
+
+ traceBytes, err := os.ReadFile(tracePath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ traceBytes = []byte{}
+ } else {
+ t.Fatalf("read trace: %v", err)
+ }
+ }
+
+ return string(out), string(traceBytes)
+}
+
+func pveHarnessMockBinaries() map[string]string {
+ return map[string]string{
+ "pveum": `#!/usr/bin/env bash
+set -e
+printf 'pveum %s\n' "$*" >> "$TRACE_FILE"
+case "$*" in
+ "user token list pulse-monitor@pam")
+ if [ "${MOCK_TOKEN_EXISTS:-0}" = "1" ]; then
+ echo "pulse-sentinel-url"
+ fi
+ ;;
+ "user token remove pulse-monitor@pam pulse-sentinel-url")
+ ;;
+ "user token add pulse-monitor@pam pulse-sentinel-url --privsep 0")
+ # Emit the box-drawing format parsed by the setup script (│ value │ secret │)
+ printf '\342\224\202 value \342\224\202 mocked-pve-secret \342\224\202\n'
+ ;;
+ *)
+ echo "unexpected pveum args: $*" >&2
+ exit 1
+ ;;
+esac
+`,
+ "hostname": `#!/usr/bin/env bash
+set -e
+if [ "${1:-}" = "-s" ]; then
+ echo "pve-node"
+ exit 0
+fi
+if [ "${1:-}" = "-I" ]; then
+ echo "192.0.2.50"
+ exit 0
+fi
+echo "pve-node"
+`,
+ "curl": `#!/usr/bin/env bash
+set -e
+printf 'curl %s\n' "$*" >> "$TRACE_FILE"
+echo '{"success":true}'
+`,
+ }
+}
+
+func pbsHarnessMockBinaries() map[string]string {
+ return map[string]string{
+ "proxmox-backup-manager": `#!/usr/bin/env bash
+set -e
+printf 'proxmox-backup-manager %s\n' "$*" >> "$TRACE_FILE"
+case "$*" in
+ "user list-tokens pulse-monitor@pbs")
+ if [ "${MOCK_TOKEN_EXISTS:-0}" = "1" ]; then
+ echo "pulse-sentinel-url"
+ fi
+ ;;
+ "user delete-token pulse-monitor@pbs pulse-sentinel-url")
+ ;;
+ "user generate-token pulse-monitor@pbs pulse-sentinel-url")
+ echo '{"tokenid":"pulse-monitor@pbs!pulse-sentinel-url","value":"mocked-pbs-secret"}'
+ ;;
+ *)
+ echo "unexpected proxmox-backup-manager args: $*" >&2
+ exit 1
+ ;;
+esac
+`,
+ "hostname": `#!/usr/bin/env bash
+set -e
+if [ "${1:-}" = "-s" ]; then
+ echo "pbs-node"
+ exit 0
+fi
+if [ "${1:-}" = "-I" ]; then
+ echo "192.0.2.60"
+ exit 0
+fi
+echo "pbs-node"
+`,
+ "curl": `#!/usr/bin/env bash
+set -e
+printf 'curl %s\n' "$*" >> "$TRACE_FILE"
+echo '{"success":true}'
+`,
+ }
+}
+
+func assertContains(t *testing.T, value, needle string) {
+ t.Helper()
+ if !strings.Contains(value, needle) {
+ t.Fatalf("expected to find %q\nvalue:\n%s", needle, value)
+ }
+}
+
+func assertNotContains(t *testing.T, value, needle string) {
+ t.Helper()
+ if strings.Contains(value, needle) {
+ t.Fatalf("did not expect to find %q\nvalue:\n%s", needle, value)
+ }
+}
diff --git a/internal/api/config_handlers_setup_script_test.go b/internal/api/config_handlers_setup_script_test.go
index 5657fbbae4..99f0e91477 100644
--- a/internal/api/config_handlers_setup_script_test.go
+++ b/internal/api/config_handlers_setup_script_test.go
@@ -90,6 +90,11 @@ func TestPVESetupScriptArgumentAlignment(t *testing.T) {
contains: `TOKEN_NAME="pulse-sentinel-url"`,
desc: "Bash variable TOKEN_NAME should be deterministic for the Pulse server",
},
+ {
+ name: "existing_token_not_rotated_by_default",
+ contains: `Set PULSE_FORCE_TOKEN_ROTATE=1 to rotate this token and issue a new secret.`,
+ desc: "Existing tokens should be preserved by default to avoid credential drift",
+ },
}
for _, tt := range tests {
@@ -269,6 +274,11 @@ func TestHandleSetupScript_PBSTypeGeneratesScript(t *testing.T) {
contains: "proxmox-backup-manager acl update",
desc: "Should set PBS ACLs",
},
+ {
+ name: "pbs_existing_token_guard",
+ contains: "Set PULSE_FORCE_TOKEN_ROTATE=1 to rotate this token and issue a new secret.",
+ desc: "PBS script should preserve existing tokens unless rotation is explicitly forced",
+ },
}
for _, tt := range tests {