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
fix(proxmox): stabilize pulse monitor token lifecycle
rcourtmanb38488f2dafa
diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.goindex 16876f9910..bf42297534 100644--- a/internal/api/config_handlers.go+++ b/internal/api/config_handlers.go@@ -40,6 +40,7 @@ import (var (setupAuthTokenPattern = regexp.MustCompile(`^[A-Fa-f0-9]{32,128}$`)+ pulseTokenSlugPattern = regexp.MustCompile(`[^a-z0-9]+`))func sanitizeInstallerURL(raw string) (string, error) {@@ -78,6 +79,69 @@ func sanitizeSetupAuthToken(token string) (string, error) {return trimmed, nil}+// buildPulseMonitorTokenName returns a deterministic Pulse-managed token name.+// The result is stable across reruns for the same Pulse instance.+func buildPulseMonitorTokenName(candidates ...string) string {+ return "pulse-" + pulseTokenSuffix(candidates...)+}++func pulseTokenSuffix(candidates ...string) string {+ for _, candidate := range candidates {+ host := pulseTokenHostCandidate(candidate)+ if host == "" {+ continue+ }+ slug := pulseTokenSlug(host)+ if slug != "" {+ return slug+ }+ }+ return "server"+}++func pulseTokenHostCandidate(candidate string) string {+ raw := strings.TrimSpace(candidate)+ if raw == "" {+ return ""+ }++ if strings.Contains(raw, "://") {+ if parsed, err := url.Parse(raw); err == nil && parsed.Hostname() != "" {+ return parsed.Hostname()+ }+ }++ if host, _, err := net.SplitHostPort(raw); err == nil {+ return strings.Trim(host, "[]")+ }++ if parsed, err := url.Parse("https://" + raw); err == nil && parsed.Hostname() != "" {+ return parsed.Hostname()+ }++ return strings.Trim(raw, "[]")+}++func pulseTokenSlug(raw string) string {+ trimmed := strings.Trim(strings.ToLower(strings.TrimSpace(raw)), ".")+ if trimmed == "" {+ return ""+ }++ slug := pulseTokenSlugPattern.ReplaceAllString(trimmed, "-")+ slug = strings.Trim(slug, "-")+ if slug == "" {+ return ""+ }++ const maxSlugLen = 48+ if len(slug) > maxSlugLen {+ slug = strings.Trim(slug[:maxSlugLen], "-")+ }++ return slug+}+// SetupCode represents a one-time setup code for secure node registrationtype SetupCode struct {ExpiresAt time.Time@@ -1380,8 +1444,9 @@ func normalizeNodeHost(rawHost, nodeType string) (string, error) {// extractHostIP extracts the IP address from a host URL if it's an IP-based URL.// Returns empty string if the URL uses a hostname instead of an IP.// isPulseAgentToken returns true if the token ID was created by the Pulse agent.-// Agent tokens follow the pattern "pulse-monitor@pam!pulse-<timestamp>" (PVE)-// or "pulse-monitor@pbs!pulse-<timestamp>" (PBS).+// Agent tokens follow the pattern "pulse-monitor@pam!pulse-<scope>" (PVE)+// or "pulse-monitor@pbs!pulse-<scope>" (PBS).+// Legacy agent tokens may include an additional "-<timestamp>" suffix.func isPulseAgentToken(tokenID string) bool {return strings.HasPrefix(tokenID, "pulse-monitor@pam!pulse-") ||strings.HasPrefix(tokenID, "pulse-monitor@pbs!pulse-")@@ -1797,13 +1862,8 @@ func (h *ConfigHandlers) HandleAddNode(w http.ResponseWriter, r *http.Request) {// Fallback to password authpbsPassword = req.Password} else {- // Generate a unique token namehostname, _ := os.Hostname()- if hostname == "" {- hostname = "pulse"- }- timestamp := time.Now().Unix()- tokenName := fmt.Sprintf("pulse-%s-%d", hostname, timestamp)+ tokenName := buildPulseMonitorTokenName(r.Host, hostname)tokenID, tokenSecret, err := pbsClient.SetupMonitoringAccess(context.Background(), tokenName)if err != nil {@@ -3801,32 +3861,15 @@ func (h *ConfigHandlers) HandleSetupScript(w http.ResponseWriter, r *http.Reques}}- // Extract Pulse IP from the pulse URL to make token name unique- pulseIP := "pulse"- if pulseURL != "" {- // Extract IP/hostname from Pulse URL- if match := strings.Contains(pulseURL, "://"); match {- parts := strings.Split(pulseURL, "://")- if len(parts) > 1 {- hostPart := strings.Split(parts[1], ":")[0]- // Replace dots with dashes for token name compatibility- pulseIP = strings.ReplaceAll(hostPart, ".", "-")- }- }- }-- // Create unique token name based on Pulse IP and timestamp- // Adding timestamp ensures truly unique tokens even when running from same Pulse server- timestamp := time.Now().Unix()- tokenName := fmt.Sprintf("pulse-%s-%d", pulseIP, timestamp)+ pulseTokenScope := pulseTokenSuffix(pulseURL, r.Host)+ tokenName := buildPulseMonitorTokenName(pulseURL, r.Host)// Log the token name for debugginglog.Info().Str("pulseURL", pulseURL).- Str("pulseIP", pulseIP).+ Str("pulseTokenScope", pulseTokenScope).Str("tokenName", tokenName).- Int64("timestamp", timestamp).- Msg("Generated unique token name for setup script")+ Msg("Generated deterministic token name for setup script")// Get or generate SSH public key for temperature monitoringsshKeys := h.getOrGenerateSSHKeys()@@ -4215,33 +4258,31 @@ attempt_auto_registration() {# Generate API tokenecho "Generating API token..."-# Check if token already exists+# Rotate token if it already exists so reruns remain idempotentTOKEN_EXISTED=false+TOKEN_OUTPUT=""+TOKEN_VALUE=""if pveum user token list pulse-monitor@pam 2>/dev/null | grep -q "$TOKEN_NAME"; thenTOKEN_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..."+ 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 "================================================================"- echo "WARNING: Token '$TOKEN_NAME' already exists!"- echo "================================================================"- echo ""- echo "To create a new token, first remove the existing one:"- echo " pveum user token remove pulse-monitor@pam $TOKEN_NAME"- echo ""- echo "Or create a token with a different name:"- echo " pveum user token add pulse-monitor@pam ${TOKEN_NAME}-$(date +%%s) --privsep 0"- echo ""- echo "Then use the new token ID in Pulse (e.g., ${PULSE_TOKEN_ID}-1234567890)"- echo "================================================================"+ echo "Manual registration may be required."echo ""else- # Create token silently first- TOKEN_OUTPUT=$(pveum user token add pulse-monitor@pam "$TOKEN_NAME" --privsep 0)-- # Extract the token value for auto-registrationTOKEN_VALUE=$(echo "$TOKEN_OUTPUT" | grep "│ value" | awk -F'│' '{print $3}' | tr -d ' ' | tail -1)-+if [ -z "$TOKEN_VALUE" ]; then- # If we can't extract the token, show it to the userecho ""echo "================================================================"echo "IMPORTANT: Copy the token value below - it's only shown once!"@@ -4253,8 +4294,11 @@ elseecho " Manual registration may be required."echo ""else- # Token created successfully- echo "API token generated successfully"+ if [ "$TOKEN_EXISTED" = true ]; then+ echo "API token rotated successfully"+ else+ echo "API token generated successfully"+ fiecho ""fi@@ -4505,9 +4549,7 @@ echo ""if [ "$AUTO_REG_SUCCESS" != true ]; thenecho "Manual setup instructions:"echo " Token ID: $PULSE_TOKEN_ID"- if [ "$TOKEN_EXISTED" = true ]; then- echo " Token Value: [Use your existing token or create a new one as shown above]"- elif [ -n "$TOKEN_VALUE" ]; then+ if [ -n "$TOKEN_VALUE" ]; thenecho " Token Value: $TOKEN_VALUE"elseecho " Token Value: [See token output above]"@@ -4517,7 +4559,7 @@ echo ""fi`, serverName, time.Now().Format("2006-01-02 15:04:05"),pulseURL, serverHost, tokenName,- pulseIP,+ pulseTokenScope,authToken,storagePerms,sshKeys.SensorsPublicKey)@@ -4559,6 +4601,8 @@ fi# Extract Pulse server IP from the URL for token matchingPULSE_IP_PATTERN=$(echo "%s" | sed 's/\./\-/g')+TOKEN_NAME="%s"+PULSE_TOKEN_ID="pulse-monitor@pbs!${TOKEN_NAME}"# Check for old Pulse tokens from the same Pulse server and offer to clean them upecho "Checking for existing Pulse monitoring tokens from this Pulse server..."@@ -4612,38 +4656,49 @@ proxmox-backup-manager user create pulse-monitor@pbs 2>/dev/null || echo "User a# Generate API tokenecho "Generating API token..."-# Check if token already exists (PBS tokens can be regenerated with same name)+# Rotate token if it already exists so reruns remain idempotent+TOKEN_EXISTED=false+TOKEN_OUTPUT=""+TOKEN_VALUE=""+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..."+ 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 %s 2>&1)-if echo "$TOKEN_OUTPUT" | grep -q "already exists"; then- echo "WARNING: Token '%s' already exists!"- echo ""- echo "You can either:"- echo "1. Delete the existing token first:"- echo " proxmox-backup-manager user delete-token pulse-monitor@pbs %s"+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 "2. Or create a token with a different name:"- echo " proxmox-backup-manager user generate-token pulse-monitor@pbs %s-$(date +%%s)"+ echo "Manual registration may be required."echo ""- echo "Then use the new token ID in Pulse (e.g., pulse-monitor@pbs!%s-1234567890)"elseecho "$TOKEN_OUTPUT"-+# Extract the token value for auto-registrationTOKEN_VALUE=$(echo "$TOKEN_OUTPUT" | grep '"value"' | sed 's/.*"value"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')-+if [ -z "$TOKEN_VALUE" ]; thenecho "⚠️ 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"+ fiecho ""fi-+# Try auto-registrationecho "🔄 Attempting auto-registration with Pulse..."echo ""@@ -4696,7 +4751,7 @@ elseecho " curl -sSL \"$PULSE_URL/api/setup-script?type=pbs&host=https://192.168.0.8:8007&pulse_url=$PULSE_URL\" | bash"echo ""echo "📝 For manual setup, use the token created above with:"- echo " Token ID: pulse-monitor@pbs!%s"+ echo " Token ID: $PULSE_TOKEN_ID"echo " Token Value: [See above]"echo ""exit 1@@ -4708,7 +4763,7 @@ else"type": "pbs","host": "$HOST_URL","serverName": "$SERVER_HOSTNAME",- "tokenId": "pulse-monitor@pbs!%s",+ "tokenId": "$PULSE_TOKEN_ID","tokenValue": "$TOKEN_VALUE","authToken": "$AUTH_TOKEN"}@@ -4758,7 +4813,7 @@ echo ""# Set up permissionsecho "Setting up permissions..."proxmox-backup-manager acl update / Audit --auth-id pulse-monitor@pbs-proxmox-backup-manager acl update / Audit --auth-id 'pulse-monitor@pbs!%s'+proxmox-backup-manager acl update / Audit --auth-id "$PULSE_TOKEN_ID"echo ""echo "✅ Setup complete!"@@ -4767,8 +4822,12 @@ echo ""# Only show manual setup instructions if auto-registration failedif [ "$AUTO_REG_SUCCESS" != true ]; thenecho "Add this server to Pulse with:"- echo " Token ID: pulse-monitor@pbs!%s"- echo " Token Value: [Check the output above for the token or instructions]"+ echo " Token ID: $PULSE_TOKEN_ID"+ if [ -n "$TOKEN_VALUE" ]; then+ echo " Token Value: $TOKEN_VALUE"+ else+ echo " Token Value: [Check the output above for the token or instructions]"+ fiecho " Host URL: https://$SERVER_IP:8007"echo ""echo "If auto-registration is enabled but requires a token:"@@ -4776,9 +4835,8 @@ if [ "$AUTO_REG_SUCCESS" != true ]; thenecho " 2. Re-run this script with: PULSE_REG_TOKEN=your-token ./setup.sh"echo ""fi-`, serverName, time.Now().Format("2006-01-02 15:04:05"), pulseIP,- tokenName, tokenName, tokenName, tokenName, tokenName,- authToken, pulseURL, serverHost, tokenName, tokenName, tokenName, tokenName)+`, serverName, time.Now().Format("2006-01-02 15:04:05"), pulseTokenScope,+ tokenName, authToken, pulseURL, serverHost)}// Set headers for script download@@ -5748,13 +5806,14 @@ func (h *ConfigHandlers) handleSecureAutoRegister(w http.ResponseWriter, r *httpStr("username", req.Username).Msg("Processing secure auto-register request")- // Generate a unique token name based on Pulse's IP/hostname- hostname, _ := os.Hostname()- if hostname == "" {- hostname = strings.ReplaceAll(clientIP, ".", "-")+ host, err := normalizeNodeHost(req.Host, req.Type)+ if err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return}- timestamp := time.Now().Unix()- tokenName := fmt.Sprintf("pulse-%s-%d", hostname, timestamp)++ hostname, _ := os.Hostname()+ tokenName := buildPulseMonitorTokenName(r.Host, hostname, clientIP)// Generate a secure random token valuetokenBytes := make([]byte, 16)@@ -5766,12 +5825,6 @@ func (h *ConfigHandlers) handleSecureAutoRegister(w http.ResponseWriter, r *httptokenValue := fmt.Sprintf("%x-%x-%x-%x-%x",tokenBytes[0:4], tokenBytes[4:6], tokenBytes[6:8], tokenBytes[8:10], tokenBytes[10:16])- host, err := normalizeNodeHost(req.Host, req.Type)- if err != nil {- http.Error(w, err.Error(), http.StatusBadRequest)- return- }-fingerprint := ""if fp, err := tlsutil.FetchFingerprint(host); err != nil {log.Warn().Err(err).Str("host", host).Msg("Failed to fetch TLS fingerprint for auto-register")@@ -5780,11 +5833,35 @@ func (h *ConfigHandlers) handleSecureAutoRegister(w http.ResponseWriter, r *http}verifySSL := true- // Create the token on the remote server- var fullTokenID string- var createErr error-+ existingTokenID := ""+ existingTokenValue := ""if req.Type == "pve" {+ for _, node := range h.getConfig(r.Context()).PVEInstances {+ if node.Host == host && isPulseAgentToken(node.TokenName) && strings.TrimSpace(node.TokenValue) != "" {+ existingTokenID = node.TokenName+ existingTokenValue = node.TokenValue+ break+ }+ }+ } else if req.Type == "pbs" {+ for _, node := range h.getConfig(r.Context()).PBSInstances {+ if node.Host == host && isPulseAgentToken(node.TokenName) && strings.TrimSpace(node.TokenValue) != "" {+ existingTokenID = node.TokenName+ existingTokenValue = node.TokenValue+ break+ }+ }+ }++ var fullTokenID string+ if existingTokenID != "" {+ fullTokenID = existingTokenID+ tokenValue = existingTokenValue+ log.Info().+ Str("host", host).+ Str("tokenID", fullTokenID).+ Msg("Reusing existing Pulse-managed token for secure auto-register")+ } else if req.Type == "pve" {// For PVE, create token via APIfullTokenID = fmt.Sprintf("pulse-monitor@pam!%s", tokenName)// Note: This would require implementing token creation in the proxmox package@@ -5826,12 +5903,6 @@ func (h *ConfigHandlers) handleSecureAutoRegister(w http.ResponseWriter, r *httpMsg("Successfully created PBS token via API")}- if createErr != nil {- log.Error().Err(createErr).Msg("Failed to create token on remote server")- http.Error(w, "Failed to create token on remote server", http.StatusInternalServerError)- return- }-// Determine server nameserverName := req.ServerNameif serverName == "" {diff --git a/internal/api/config_handlers_setup_script_test.go b/internal/api/config_handlers_setup_script_test.goindex d3d2d76652..5657fbbae4 100644--- a/internal/api/config_handlers_setup_script_test.go+++ b/internal/api/config_handlers_setup_script_test.go@@ -87,8 +87,8 @@ func TestPVESetupScriptArgumentAlignment(t *testing.T) {},{name: "token_name_variable_defined",- contains: `TOKEN_NAME="pulse-SENTINEL_URL-`,- desc: "Bash variable TOKEN_NAME should be defined with correct format",+ contains: `TOKEN_NAME="pulse-sentinel-url"`,+ desc: "Bash variable TOKEN_NAME should be deterministic for the Pulse server",},}diff --git a/internal/api/config_handlers_token_helpers_test.go b/internal/api/config_handlers_token_helpers_test.gonew file mode 100644index 0000000000..2064c33846--- /dev/null+++ b/internal/api/config_handlers_token_helpers_test.go@@ -0,0 +1,67 @@+package api++import "testing"++func TestBuildPulseMonitorTokenName(t *testing.T) {+ tests := []struct {+ name string+ candidates []string+ want string+ }{+ {+ name: "uses url host when available",+ candidates: []string{"https://192.168.0.98:7655"},+ want: "pulse-192-168-0-98",+ },+ {+ name: "uses bare host with port",+ candidates: []string{"pulse.example.com:7655"},+ want: "pulse-pulse-example-com",+ },+ {+ name: "falls back to second candidate",+ candidates: []string{"", "tower.local"},+ want: "pulse-tower-local",+ },+ {+ name: "falls back to server when no valid candidates",+ candidates: []string{"", " "},+ want: "pulse-server",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := buildPulseMonitorTokenName(tc.candidates...)+ if got != tc.want {+ t.Fatalf("buildPulseMonitorTokenName(%v) = %q, want %q", tc.candidates, got, tc.want)+ }+ })+ }+}++func TestPulseTokenSlugTruncatesToMaxLen(t *testing.T) {+ raw := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"+ got := pulseTokenSlug(raw)+ if len(got) > 48 {+ t.Fatalf("pulseTokenSlug length = %d, want <= 48", len(got))+ }+}++func TestIsPulseAgentTokenHelpers(t *testing.T) {+ tests := []struct {+ tokenID string+ want bool+ }{+ {tokenID: "pulse-monitor@pam!pulse-192-168-0-98", want: true},+ {tokenID: "pulse-monitor@pbs!pulse-server", want: true},+ {tokenID: "root@pam!pulse-foo", want: false},+ {tokenID: "pulse-monitor@pam!other-token", want: false},+ }++ for _, tc := range tests {+ if got := isPulseAgentToken(tc.tokenID); got != tc.want {+ t.Fatalf("isPulseAgentToken(%q) = %v, want %v", tc.tokenID, got, tc.want)+ }+ }+}diff --git a/internal/hostagent/proxmox_setup.go b/internal/hostagent/proxmox_setup.goindex 9c9808241f..33c78d2b03 100644--- a/internal/hostagent/proxmox_setup.go+++ b/internal/hostagent/proxmox_setup.go@@ -34,7 +34,7 @@ type ProxmoxSetup struct {// ProxmoxSetupResult contains the result of a successful Proxmox setup.type ProxmoxSetupResult struct {ProxmoxType string // "pve" or "pbs"- TokenID string // Full token ID (e.g., "pulse-monitor@pam!pulse-1234567890")+ TokenID string // Full token ID (e.g., "pulse-monitor@pam!pulse-pulse-example-com")TokenValue string // The secret token valueNodeHost string // The host URL for auto-registrationRegistered bool // Whether the node was successfully registered with Pulse@@ -49,6 +49,73 @@ const (const proxmoxMonitorRole = "PulseMonitor"+var proxmoxTokenSlugPattern = regexp.MustCompile(`[^a-z0-9]+`)++func proxmoxTokenHostCandidate(candidate string) string {+ raw := strings.TrimSpace(candidate)+ if raw == "" {+ return ""+ }++ if strings.Contains(raw, "://") {+ if parsed, err := url.Parse(raw); err == nil && parsed.Hostname() != "" {+ return parsed.Hostname()+ }+ }++ if host, _, err := net.SplitHostPort(raw); err == nil {+ return strings.Trim(host, "[]")+ }++ if parsed, err := url.Parse("https://" + raw); err == nil && parsed.Hostname() != "" {+ return parsed.Hostname()+ }++ return strings.Trim(raw, "[]")+}++func proxmoxTokenSlug(raw string) string {+ trimmed := strings.Trim(strings.ToLower(strings.TrimSpace(raw)), ".")+ if trimmed == "" {+ return ""+ }++ slug := proxmoxTokenSlugPattern.ReplaceAllString(trimmed, "-")+ slug = strings.Trim(slug, "-")+ if slug == "" {+ return ""+ }++ const maxSlugLen = 48+ if len(slug) > maxSlugLen {+ slug = strings.Trim(slug[:maxSlugLen], "-")+ }+ return slug+}++func proxmoxTokenScope(candidates ...string) string {+ for _, candidate := range candidates {+ host := proxmoxTokenHostCandidate(candidate)+ if host == "" {+ continue+ }+ if slug := proxmoxTokenSlug(host); slug != "" {+ return slug+ }+ }+ return "server"+}++func (p *ProxmoxSetup) monitorTokenName() string {+ return "pulse-" + proxmoxTokenScope(p.pulseURL, p.hostname)+}++func tokenAlreadyExists(err error, output string) bool {+ lowerErr := strings.ToLower(fmt.Sprintf("%v", err))+ lowerOutput := strings.ToLower(output)+ return strings.Contains(lowerErr, "already exists") || strings.Contains(lowerOutput, "already exists")+}+func privProbeRoleName(priv string) string {// Keep role name deterministic (helps tests) and valid for pveum.// Replace characters that are likely to cause issues in role names.@@ -306,7 +373,7 @@ func (p *ProxmoxSetup) detectProxmoxTypes() []string {// setupToken creates the monitoring user and API token.func (p *ProxmoxSetup) setupToken(ctx context.Context, ptype string) (string, string, error) {- tokenName := fmt.Sprintf("pulse-%d", time.Now().Unix())+ tokenName := p.monitorTokenName()if ptype == "pve" {return p.setupPVEToken(ctx, tokenName)@@ -325,7 +392,16 @@ func (p *ProxmoxSetup) setupPVEToken(ctx context.Context, tokenName string) (str// Create token with privilege separation disabledoutput, err := p.collector.CommandCombinedOutput(ctx, "pveum", "user", "token", "add", proxmoxUserPVE, tokenName, "--privsep", "0")if err != nil {- return "", "", fmt.Errorf("failed to create token: %w", err)+ if tokenAlreadyExists(err, output) {+ p.logger.Info().Str("token", tokenName).Msg("PVE monitoring token already exists; rotating token in place")+ if _, deleteErr := p.collector.CommandCombinedOutput(ctx, "pveum", "user", "token", "remove", proxmoxUserPVE, tokenName); deleteErr != nil {+ return "", "", fmt.Errorf("failed to delete existing token before rotation: %w", deleteErr)+ }+ output, err = p.collector.CommandCombinedOutput(ctx, "pveum", "user", "token", "add", proxmoxUserPVE, tokenName, "--privsep", "0")+ }+ if err != nil {+ return "", "", fmt.Errorf("failed to create token: %w", err)+ }}// Parse token value from output@@ -349,7 +425,16 @@ func (p *ProxmoxSetup) setupPBSToken(ctx context.Context, tokenName string) (str// Create tokenoutput, err := p.collector.CommandCombinedOutput(ctx, "proxmox-backup-manager", "user", "generate-token", proxmoxUserPBS, tokenName)if err != nil {- return "", "", fmt.Errorf("failed to create token: %w", err)+ if tokenAlreadyExists(err, output) {+ p.logger.Info().Str("token", tokenName).Msg("PBS monitoring token already exists; rotating token in place")+ if _, deleteErr := p.collector.CommandCombinedOutput(ctx, "proxmox-backup-manager", "user", "delete-token", proxmoxUserPBS, tokenName); deleteErr != nil {+ return "", "", fmt.Errorf("failed to delete existing token before rotation: %w", deleteErr)+ }+ output, err = p.collector.CommandCombinedOutput(ctx, "proxmox-backup-manager", "user", "generate-token", proxmoxUserPBS, tokenName)+ }+ if err != nil {+ return "", "", fmt.Errorf("failed to create token: %w", err)+ }}// Parse token value from JSON outputdiff --git a/internal/hostagent/proxmox_setup_test.go b/internal/hostagent/proxmox_setup_test.goindex 395daac3e5..50208d5981 100644--- a/internal/hostagent/proxmox_setup_test.go+++ b/internal/hostagent/proxmox_setup_test.go@@ -40,6 +40,100 @@ func TestParsePBSTokenValue_RegexFallback(t *testing.T) {}}+func TestMonitorTokenName_Deterministic(t *testing.T) {+ p := &ProxmoxSetup{pulseURL: "https://Pulse.EXAMPLE.com:7655"}+ if got := p.monitorTokenName(); got != "pulse-pulse-example-com" {+ t.Fatalf("monitorTokenName() = %q", got)+ }++ p = &ProxmoxSetup{hostname: "Pulse Host"}+ if got := p.monitorTokenName(); got != "pulse-pulse-host" {+ t.Fatalf("monitorTokenName() with hostname fallback = %q", got)+ }+}++func TestSetupPVEToken_RotatesExistingToken(t *testing.T) {+ mc := &mockCollector{}+ createCalls := 0+ removeCalled := false+ mc.commandCombinedOutputFn = func(ctx context.Context, name string, arg ...string) (string, error) {+ if name == "pveum" && len(arg) > 2 && arg[0] == "user" && arg[1] == "token" && arg[2] == "add" {+ createCalls+++ if createCalls == 1 {+ return "already exists", fmt.Errorf("already exists")+ }+ return "│ value │ rotated-token │", nil+ }+ if name == "pveum" && len(arg) > 2 && arg[0] == "user" && arg[1] == "token" && arg[2] == "remove" {+ removeCalled = true+ return "", nil+ }+ return "", nil+ }++ p := &ProxmoxSetup{+ logger: zerolog.Nop(),+ collector: mc,+ }+ tokenID, tokenValue, err := p.setupPVEToken(context.Background(), "pulse-test")+ if err != nil {+ t.Fatalf("setupPVEToken: %v", err)+ }+ if tokenID != "pulse-monitor@pam!pulse-test" {+ t.Fatalf("tokenID = %q", tokenID)+ }+ if tokenValue != "rotated-token" {+ t.Fatalf("tokenValue = %q", tokenValue)+ }+ if !removeCalled {+ t.Fatal("expected existing token to be removed before recreate")+ }+ if createCalls != 2 {+ t.Fatalf("expected 2 create attempts, got %d", createCalls)+ }+}++func TestSetupPBSToken_RotatesExistingToken(t *testing.T) {+ mc := &mockCollector{}+ createCalls := 0+ deleteCalled := false+ mc.commandCombinedOutputFn = func(ctx context.Context, name string, arg ...string) (string, error) {+ if name == "proxmox-backup-manager" && len(arg) > 1 && arg[0] == "user" && arg[1] == "generate-token" {+ createCalls+++ if createCalls == 1 {+ return "already exists", fmt.Errorf("already exists")+ }+ return `{"value":"rotated-pbs-token"}`, nil+ }+ if name == "proxmox-backup-manager" && len(arg) > 1 && arg[0] == "user" && arg[1] == "delete-token" {+ deleteCalled = true+ return "", nil+ }+ return "", nil+ }++ p := &ProxmoxSetup{+ logger: zerolog.Nop(),+ collector: mc,+ }+ tokenID, tokenValue, err := p.setupPBSToken(context.Background(), "pulse-test")+ if err != nil {+ t.Fatalf("setupPBSToken: %v", err)+ }+ if tokenID != "pulse-monitor@pbs!pulse-test" {+ t.Fatalf("tokenID = %q", tokenID)+ }+ if tokenValue != "rotated-pbs-token" {+ t.Fatalf("tokenValue = %q", tokenValue)+ }+ if !deleteCalled {+ t.Fatal("expected existing token to be deleted before recreate")+ }+ if createCalls != 2 {+ t.Fatalf("expected 2 create attempts, got %d", createCalls)+ }+}+func TestSelectBestIP(t *testing.T) {tests := []struct {name stringdiff --git a/pkg/pbs/client.go b/pkg/pbs/client.goindex 0aaccffcc8..9693b6a167 100644--- a/pkg/pbs/client.go+++ b/pkg/pbs/client.go@@ -329,6 +329,11 @@ func (c *Client) post(ctx context.Context, path string, data url.Values) (*http.return c.request(ctx, "POST", path, data)}+// delete performs a DELETE request+func (c *Client) delete(ctx context.Context, path string) (*http.Response, error) {+ return c.request(ctx, "DELETE", path, nil)+}+// TokenResponse represents the response from token creationtype TokenResponse struct {TokenID string `json:"tokenid"`@@ -349,7 +354,7 @@ func (c *Client) CreateUser(ctx context.Context, userID, comment string) error {resp, err := c.post(ctx, "/access/users", data)if err != nil {// User might already exist, which is okay- if strings.Contains(err.Error(), "already exists") {+ if isAlreadyExistsError(err) {log.Debug().Str("userID", userID).Msg("PBS CreateUser: user already exists")return nil}@@ -361,6 +366,10 @@ func (c *Client) CreateUser(ctx context.Context, userID, comment string) error {return nil}+func isAlreadyExistsError(err error) bool {+ return strings.Contains(strings.ToLower(err.Error()), "already exists")+}+// SetUserACL sets ACL permissions for a userfunc (c *Client) SetUserACL(ctx context.Context, authID, path, role string) error {log.Debug().Str("authID", authID).Str("path", path).Str("role", role).Msg("PBS SetUserACL: setting ACL")@@ -424,6 +433,28 @@ func (c *Client) CreateUserToken(ctx context.Context, userID, tokenName string)return &result.Data, nil}+// DeleteUserToken deletes an existing API token for a user.+func (c *Client) DeleteUserToken(ctx context.Context, userID, tokenName string) error {+ log.Debug().Str("userID", userID).Str("tokenName", tokenName).Msg("PBS DeleteUserToken: deleting token")+ path := fmt.Sprintf("/access/users/%s/token/%s", url.PathEscape(userID), url.PathEscape(tokenName))++ resp, err := c.delete(ctx, path)+ if err != nil {+ // Deleting a missing token should be treated as already converged.+ if strings.Contains(err.Error(), "API error 404") {+ return nil+ }+ return fmt.Errorf("delete token: %w", err)+ }+ defer resp.Body.Close()++ log.Info().+ Str("userID", userID).+ Str("tokenName", tokenName).+ Msg("PBS DeleteUserToken: token deleted successfully")+ return nil+}+// SetupMonitoringAccess creates a monitoring user with Audit role and returns API token// This is the turnkey method for setting up PBS monitoring accessfunc (c *Client) SetupMonitoringAccess(ctx context.Context, tokenName string) (tokenID, tokenValue string, err error) {@@ -449,7 +480,16 @@ func (c *Client) SetupMonitoringAccess(ctx context.Context, tokenName string) (t// Step 3: Create API tokentoken, err := c.CreateUserToken(ctx, monitorUser, tokenName)if err != nil {- return "", "", fmt.Errorf("create token: %w", err)+ if isAlreadyExistsError(err) {+ log.Warn().Str("tokenName", tokenName).Msg("PBS SetupMonitoringAccess: token already exists; rotating in place")+ if deleteErr := c.DeleteUserToken(ctx, monitorUser, tokenName); deleteErr != nil {+ return "", "", fmt.Errorf("delete existing token: %w", deleteErr)+ }+ token, err = c.CreateUserToken(ctx, monitorUser, tokenName)+ }+ if err != nil {+ return "", "", fmt.Errorf("create token: %w", err)+ }}// Step 4: Grant Audit role to the token as welldiff --git a/pkg/pbs/client_full_coverage_test.go b/pkg/pbs/client_full_coverage_test.goindex c54468cd7b..423ad6c4aa 100644--- a/pkg/pbs/client_full_coverage_test.go+++ b/pkg/pbs/client_full_coverage_test.go@@ -255,6 +255,60 @@ func TestClient_SetupMonitoringAccess(t *testing.T) {}}+func TestClient_SetupMonitoringAccess_RotatesExistingToken(t *testing.T) {+ createAttempts := 0+ deleteCalled := false++ client, server := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api2/json/access/users":+ w.WriteHeader(http.StatusOK)+ case "/api2/json/access/acl":+ w.WriteHeader(http.StatusOK)+ case "/api2/json/access/users/pulse-monitor@pbs/token/monitor1":+ switch r.Method {+ case http.MethodPost:+ createAttempts+++ if createAttempts == 1 {+ http.Error(w, "token already exists", http.StatusBadRequest)+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "data": map[string]string{+ "tokenid": "pulse-monitor@pbs!monitor1",+ "value": "rotated-secret",+ },+ })+ case http.MethodDelete:+ deleteCalled = true+ w.WriteHeader(http.StatusOK)+ default:+ http.Error(w, "bad method", http.StatusMethodNotAllowed)+ }+ default:+ http.Error(w, "unknown path "+r.URL.Path, http.StatusNotFound)+ }+ })+ defer server.Close()++ id, val, err := client.SetupMonitoringAccess(context.Background(), "monitor1")+ if err != nil {+ t.Fatalf("SetupMonitoringAccess failed: %v", err)+ }+ if id != "pulse-monitor@pbs!monitor1" {+ t.Fatalf("token id = %q", id)+ }+ if val != "rotated-secret" {+ t.Fatalf("token value = %q", val)+ }+ if !deleteCalled {+ t.Fatal("expected existing token to be deleted before recreate")+ }+ if createAttempts != 2 {+ t.Fatalf("expected 2 token creation attempts, got %d", createAttempts)+ }+}+func TestClient_SetupMonitoringAccess_Errors(t *testing.T) {// 1. Fail at SetUserACL (user)client1, server1 := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {