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
Add Proxmox setup doctor repair flow
rcourtmanf7a40f3a2219
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 0be2d45b0b..bfc9fd0dd9 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -231,6 +231,13 @@ The setup guide must also present the source strategy at action time: APIInventory is the recommended least-privilege API path, Host Telemetry Agent isthe optional full-host-telemetry root-agent path, and Manual Token Setup is anadvanced manual API-token escape hatch.+For existing Proxmox API sources, that same setup guide must expose the+non-destructive Audit/Repair rerun path before asking operators to rotate+credentials. Audit/Repair is the first lifecycle response to suspected setup+drift: it checks the Pulse-managed user, current token presence/expiry,+expected ACLs, and older Pulse-managed tokens without replacing the stored API+secret. Full Install/Configure remains the explicit token-rotation path when+the Proxmox-side token value is gone or no longer matches Pulse.That shared monitored-system impact preview boundary also owns the disabledplatform-connection lifecycle state. Once a TrueNAS or VMware setup form marksdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex a40231d783..e761dad49c 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1605,6 +1605,12 @@ the canonical monitored-system blocked payload.## Current State+Proxmox setup bootstrap now includes a non-destructive Audit/Repair path in the+generated PVE script and existing-source setup guide. That path audits token+presence, token expiry, Pulse-managed token drift, and expected ACLs, then+reapplies safe permissions without replacing the stored API token; full+Install/Configure remains the explicit rotation and re-registration path.+VMware vSphere phase-1 inventory now reaches the product through shared APIcontracts rather than provider-local read routes. `/api/vmware/connections`owns saved vCenter connection health and observed counts, while canonical@@ -3768,6 +3774,12 @@ the returned `url`, `downloadURL`, `scriptFileName`, `commandWithEnv`,`tokenHint`, and `expires` until that artifact expires or the operator changesthe endpoint, instead of rebuilding a second download request from lane-localform state or retaining the raw setup token inside frontend cache state.+For existing Proxmox API sources, that same setup surface must present the+rendered setup script's Audit/Repair action as the non-destructive repair path.+The frontend may tell operators to rerun the same canonical command and choose+Audit/Repair, but it must not imply the current API token is rotated during+repair. Install/Configure remains the explicit rotation and re-registration+path when the token value itself needs to be replaced.That same bootstrap artifact contract must also stay coherent in public-facingguidance: `docs/API.md` and operator setup guides may not describe`/api/setup-script-url` as if it only returned a token plus bare URL, and they@@ -3865,6 +3877,16 @@ That same payload must also use exact token-name matching for rerun rotationdetection, rather than broad substring checks over token-list output, so thecanonical managed token contract does not collide with unrelated partial-namematches.+That same PVE setup-script payload must provide an Audit/Repair menu action and+non-interactive `PULSE_SETUP_ACTION` selector that audit and reapply+Pulse-managed setup without rotating the API token. The repair path may create+the missing `pulse-monitor@pve` user, report the current token's Expire value,+inventory matching Pulse-managed tokens under the `pve` and legacy `pam`+realms, and reapply safe user/token ACLs, including the optional storage grant+when requested. If the current token is absent or Pulse still receives 401+after repair, the generated script must direct the operator to+Install/Configure for explicit token rotation and re-registration instead of+silently minting a replacement token from repair mode.That same payload must also keep PBS token-copy guidance truthful: theone-time token banner may only be emitted from the successful token-createbranch, not before the creation result is known.diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex c1b6fbe02d..1585648161 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -69,6 +69,10 @@ auto-registration changes that affect backup visibility permissions arestorage/recovery-adjacent: optional PVE `/storage` grants must remain effectivefor privilege-separated tokens by assigning the same `PVEDatastoreAdmin` role toboth the service user and the concrete token id.+The generated Proxmox Audit/Repair path is storage/recovery-adjacent for the+same reason: when backup visibility was requested, repair must reapply the+optional `/storage` grant to the service user and to the current concrete token+id if that token still exists, without rotating credentials from repair mode.PBS generated setup-script auto-registration is storage/recovery-adjacentbecause the registration result determines whether PBS backup evidence can flowwithout manual follow-up. The rendered script must post auto-registration to thediff --git a/frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx b/frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsxindex 76ffccb1c3..44e085a185 100644--- a/frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx+++ b/frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx@@ -175,12 +175,12 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro<Showwhen={state.agentInstallCommand().length > 0}fallback={- <code class="text-blue-400">+ <code class="text-muted">Click the copy button to generate the install command</code>}>- <code class="block text-blue-100 whitespace-pre-wrap break-words">+ <code class="block text-base-content whitespace-pre-wrap break-words">{state.agentInstallCommand()}</code></Show>@@ -205,6 +205,16 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionProagent-driven operations.</p></div>+ <Show when={state.isEditingExistingNode()}>+ <div class="rounded-md border border-blue-200 bg-blue-50 px-3 py-2 dark:border-blue-800 dark:bg-blue-950/30">+ <p class="text-xs text-blue-800 dark:text-blue-200">+ <strong>Existing source repair:</strong> rerun this command and choose+ Audit/Repair to recheck the Pulse-managed user, token expiry, ACLs, and old+ tokens without rotating the current API token. Choose Install/Configure only+ when the token value needs to be replaced.+ </p>+ </div>+ </Show><p class="text-blue-800 dark:text-blue-200">Just copy and run this one command on your Proxmox VE server:</p>@@ -238,14 +248,14 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro<Showwhen={state.quickSetupPreviewCommand().length > 0}fallback={- <code class="text-blue-400">+ <code class="text-muted">{state.formData().host? 'Click the copy button to generate the setup command': 'Please enter the Endpoint URL above first'}</code>}>- <code class="block text-blue-100 whitespace-pre-wrap break-words">+ <code class="block text-base-content whitespace-pre-wrap break-words">{state.quickSetupPreviewCommand()}</code></Show>@@ -608,7 +618,7 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro</svg></Show></button>- <code class="text-green-400 whitespace-pre-wrap break-all pr-10">+ <code class="block text-base-content whitespace-pre-wrap break-all pr-10">{state.agentInstallCommand() ||'Click the copy button to generate and copy the install command'}</code>@@ -668,14 +678,14 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro<Showwhen={state.quickSetupPreviewCommand().length > 0}fallback={- <code class="text-blue-400">+ <code class="text-muted">{state.formData().host? 'Click the copy button to generate the setup command': 'Please enter the Endpoint URL above first'}</code>}>- <code class="block text-blue-100 whitespace-pre-wrap break-words">+ <code class="block text-base-content whitespace-pre-wrap break-words">{state.quickSetupPreviewCommand()}</code></Show>diff --git a/frontend-modern/src/components/Settings/__tests__/NodeModalSetupGuideSection.test.tsx b/frontend-modern/src/components/Settings/__tests__/NodeModalSetupGuideSection.test.tsxindex 2e65169aae..d07a8753eb 100644--- a/frontend-modern/src/components/Settings/__tests__/NodeModalSetupGuideSection.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/NodeModalSetupGuideSection.test.tsx@@ -5,7 +5,10 @@ import type { NodeModalNodeType, NodeModalSetupMode } from '@/utils/nodeModalPreimport type { NodeModalState } from '../useNodeModalState';import { NodeModalSetupGuideSection } from '../NodeModalSetupGuideSection';-const renderSetupGuide = (nodeType: NodeModalNodeType = 'pve') => {+const renderSetupGuide = (+ nodeType: NodeModalNodeType = 'pve',+ options: { isEditingExistingNode?: boolean } = {},+) => {const Harness = () => {const [setupMode, setSetupMode] = createSignal<NodeModalSetupMode>('auto');const updateField = vi.fn((field: string, value: string | boolean | number) => {@@ -23,6 +26,7 @@ const renderSetupGuide = (nodeType: NodeModalNodeType = 'pve') => {downloadProxmoxSetupScript: vi.fn(),formData: () => ({ setupMode: setupMode(), host: '' }),isAdvancedSetupMode: () => setupMode() === 'manual',+ isEditingExistingNode: () => Boolean(options.isEditingExistingNode),loadingAgentCommand: () => false,quickSetupExpiry: () => null,quickSetupExpiryLabel: () => '',@@ -72,6 +76,15 @@ describe('NodeModalSetupGuideSection', () => {expect(screen.getByText(/Advanced escape hatch: use this only when/i)).toBeInTheDocument();});+ it('surfaces non-destructive repair guidance for existing Proxmox API sources', () => {+ renderSetupGuide('pve', { isEditingExistingNode: true });++ expect(screen.getByText('Existing source repair:')).toBeInTheDocument();+ expect(screen.getByText(/choose Audit\/Repair/i)).toBeInTheDocument();+ expect(screen.getByText(/without rotating the current API token/i)).toBeInTheDocument();+ expect(screen.getByText(/Choose Install\/Configure only when/i)).toBeInTheDocument();+ });+it('applies the same API-first strategy language to PBS', () => {renderSetupGuide('pbs');diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.tsindex 620a6888b9..7b48ecb0e1 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts@@ -777,6 +777,9 @@ describe('settings architecture guardrails', () => {expect(nodeModalSetupGuideSectionSource).toContain('API inventory');expect(nodeModalSetupGuideSectionSource).toContain('Manual API token');expect(nodeModalSetupGuideSectionSource).toContain('Recommended least-privilege path');+ expect(nodeModalSetupGuideSectionSource).toContain('Existing source repair');+ expect(nodeModalSetupGuideSectionSource).toContain('Audit/Repair');+ expect(nodeModalSetupGuideSectionSource).toContain('without rotating the current API token');expect(nodeModalStatusFooterSource).toContain('guidedSetupOnlyMode');expect(nodeModalStateSource).toContain('data.setupMode !==');diff --git a/internal/api/config_handlers_setup_script_test.go b/internal/api/config_handlers_setup_script_test.goindex 6ea52074b4..641aafe32e 100644--- a/internal/api/config_handlers_setup_script_test.go+++ b/internal/api/config_handlers_setup_script_test.go@@ -441,6 +441,47 @@ func TestPVESetupScript_RemovesDiscoveredOldTokensFromBothUsers(t *testing.T) {}}+func TestPVESetupScript_IncludesNonDestructiveSetupDoctor(t *testing.T) {+ tempDir := t.TempDir()+ cfg := &config.Config{+ DataPath: tempDir,+ ConfigPath: tempDir,+ }++ handlers := newTestConfigHandlers(t, cfg)++ req := httptest.NewRequest(http.MethodGet,+ "/api/setup-script?type=pve&host=http://sentinel-host:8006&pulse_url=http://sentinel-url:7656&backup_perms=true",+ 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())+ }++ script := rr.Body.String()+ required := []string{+ `echo " [2] Audit/Repair - Check and repair Pulse-managed Proxmox setup"`,+ `MAIN_ACTION="${PULSE_SETUP_ACTION:-}"`,+ `run_pve_setup_doctor() {`,+ `echo "This mode does not rotate the API token."`,+ `echo " Expire: $(pulse_pve_token_expire_label)"`,+ `pveum aclmod / -user pulse-monitor@pve -role PVEAuditor`,+ `if pulse_pve_token_exists; then`,+ `pveum aclmod /storage -token "$PULSE_TOKEN_ID" -role PVEDatastoreAdmin`,+ `configure_pve_pulse_monitor_role "$token_exists"`,+ `Choose Install/Configure to rotate the token and let Pulse re-register it.`,+ }+ for _, snippet := range required {+ if !containsString(script, snippet) {+ t.Fatalf("expected setup doctor snippet %q, got: %s", snippet, truncate(script, 2200))+ }+ }+}+func TestPVESetupScript_RemovesMatchingPulseConnectionBeforeLocalCleanup(t *testing.T) {tempDir := t.TempDir()cfg := &config.Config{@@ -559,7 +600,9 @@ func TestSetupScripts_UseExactTokenMatchForRotationDetection(t *testing.T) {t.Fatalf("expected 200 OK for PVE, got %d (%s)", pveRR.Code, pveRR.Body.String())}pveScript := pveRR.Body.String()- if !containsString(pveScript, `awk 'NR>3 {print $2}' | grep -Fx "$TOKEN_NAME" >/dev/null 2>&1`) {+ if !containsString(pveScript, `pulse_pve_token_exists() {`) ||+ !containsString(pveScript, `grep -Fx "$TOKEN_NAME" >/dev/null 2>&1`) ||+ !containsString(pveScript, `if pulse_pve_token_exists; then`) {t.Fatalf("expected PVE token rotation detection to use exact token-name matching, got: %s", truncate(pveScript, 900))}if containsString(pveScript, `grep -q "$TOKEN_NAME"`) {diff --git a/internal/api/config_setup_handlers.go b/internal/api/config_setup_handlers.goindex 9cc08e86cb..63eff63654 100644--- a/internal/api/config_setup_handlers.go+++ b/internal/api/config_setup_handlers.go@@ -136,24 +136,31 @@ func (h *ConfigHandlers) handleSetupScript(w http.ResponseWriter, r *http.RequessshKeys := h.getOrGenerateSSHKeys()storagePerms := ""+ storageRepairPerms := ""if backupPerms {storagePerms = `pveum aclmod /storage -user pulse-monitor@pve -role PVEDatastoreAdminif [ "$TOKEN_CREATED" = true ]; thenpveum aclmod /storage -token "$PULSE_TOKEN_ID" -role PVEDatastoreAdminfi`+ storageRepairPerms = `+ pveum aclmod /storage -user pulse-monitor@pve -role PVEDatastoreAdmin+ if pulse_pve_token_exists; then+ pveum aclmod /storage -token "$PULSE_TOKEN_ID" -role PVEDatastoreAdmin+ fi`}script := renderSetupScript(serverType, setupScriptRenderContext{- ServerName: serverName,- PulseURL: pulseURL,- ServerHost: serverHost,- SetupToken: setupToken,- TokenName: tokenName,- TokenMatchPrefix: tokenMatchPrefix,- StoragePerms: storagePerms,- SensorsPublicKey: sshKeys.SensorsPublicKey,- Artifact: artifact,+ ServerName: serverName,+ PulseURL: pulseURL,+ ServerHost: serverHost,+ SetupToken: setupToken,+ TokenName: tokenName,+ TokenMatchPrefix: tokenMatchPrefix,+ StoragePerms: storagePerms,+ StorageRepairPerms: storageRepairPerms,+ SensorsPublicKey: sshKeys.SensorsPublicKey,+ Artifact: artifact,})// Serve setup scripts as canonical shell-script downloads instead of generic text.diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex cb93e8dc2c..4e667f4259 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -5512,7 +5512,9 @@ func TestContract_SetupScriptEmbedsFailFastGuidance(t *testing.T) {if !strings.Contains(script, `grep -E "^${TOKEN_MATCH_PREFIX}(-[0-9]+)?$"`) {t.Fatalf("setup script missing canonical cleanup token discovery matcher: %s", script)}- if !strings.Contains(script, `awk 'NR>3 {print $2}' | grep -Fx "$TOKEN_NAME" >/dev/null 2>&1`) {+ if !strings.Contains(script, `pulse_pve_token_exists() {`) ||+ !strings.Contains(script, `grep -Fx "$TOKEN_NAME" >/dev/null 2>&1`) ||+ !strings.Contains(script, `if pulse_pve_token_exists; then`) {t.Fatalf("setup script missing exact PVE token rotation detection: %s", script)}if strings.Contains(script, `PULSE_IP_PATTERN=`) {diff --git a/internal/api/setup_script_render.go b/internal/api/setup_script_render.goindex 702bbf1aa2..96d004cb13 100644--- a/internal/api/setup_script_render.go+++ b/internal/api/setup_script_render.go@@ -7,15 +7,16 @@ import ()type setupScriptRenderContext struct {- ServerName string- PulseURL string- ServerHost string- SetupToken string- TokenName string- TokenMatchPrefix string- StoragePerms string- SensorsPublicKey string- Artifact setupScriptInstallArtifact+ ServerName string+ PulseURL string+ ServerHost string+ SetupToken string+ TokenName string+ TokenMatchPrefix string+ StoragePerms string+ StorageRepairPerms string+ SensorsPublicKey string+ Artifact setupScriptInstallArtifact}func deriveSetupScriptServerName(serverHost string) string {@@ -55,6 +56,7 @@ HOST_URL="$SERVER_HOST"PULSE_SETUP_TOKEN="${PULSE_SETUP_TOKEN:-%s}"SETUP_TOKEN_INVALID=falseTOKEN_NAME="%s"+TOKEN_MATCH_PREFIX="%s"PULSE_TOKEN_ID="pulse-monitor@pve!${TOKEN_NAME}"SETUP_SCRIPT_URL="%s"PULSE_BOOTSTRAP_COMMAND_WITH_ENV=%s@@ -178,6 +180,215 @@ case "$ENVIRONMENT" in;;esac+trim_field() {+ sed 's/^[[:space:]]*//;s/[[:space:]]*$//'+}++pulse_pve_user_exists() {+ pveum user list 2>/dev/null | grep -F "pulse-monitor@pve" >/dev/null 2>&1+}++pulse_pve_matching_tokens() {+ local user_id="$1"+ pveum user token list "$user_id" 2>/dev/null |+ awk -F'│' 'NR>3 {print $2}' |+ trim_field |+ grep -E "^${TOKEN_MATCH_PREFIX}(-[0-9]+)?$" || true+}++pulse_pve_token_exists() {+ pulse_pve_matching_tokens pulse-monitor@pve | grep -Fx "$TOKEN_NAME" >/dev/null 2>&1+}++pulse_pve_token_expire_label() {+ local expire+ expire=$(pveum user token list pulse-monitor@pve 2>/dev/null |+ awk -F'│' -v token="$TOKEN_NAME" '+ NR>3 {+ name=$2+ exp=$3+ gsub(/^[ \t]+|[ \t]+$/, "", name)+ gsub(/^[ \t]+|[ \t]+$/, "", exp)+ if (name == token) {+ print exp+ exit+ }+ }')+ if [ -z "$expire" ]; then+ echo "unknown"+ else+ echo "$expire"+ fi+}++pulse_pve_acl_has() {+ local acl_path="$1"+ local subject="$2"+ local role="$3"+ if pveum acl list 2>/dev/null |+ awk -F'│' -v acl_path="$acl_path" -v subject="$subject" -v role="$role" '+ NR>3 {+ path_field=$2+ subject_field=$3+ role_field=$4+ gsub(/^[ \t]+|[ \t]+$/, "", path_field)+ gsub(/^[ \t]+|[ \t]+$/, "", subject_field)+ gsub(/^[ \t]+|[ \t]+$/, "", role_field)+ if (path_field == acl_path && subject_field == subject && role_field == role) {+ found=1+ }+ }+ END { exit found ? 0 : 1 }'; then+ return 0+ fi++ pveum acl list 2>/dev/null | grep -F "$acl_path" | grep -F "$subject" | grep -F "$role" >/dev/null 2>&1+}++print_pve_acl_status() {+ local acl_path="$1"+ local subject="$2"+ local role="$3"+ local label="$4"+ if pulse_pve_acl_has "$acl_path" "$subject" "$role"; then+ echo " ✓ $label"+ else+ echo " ⚠ Missing: $label"+ fi+}++configure_pve_pulse_monitor_role() {+ local apply_token_acl="$1"+ local HAS_VM_MONITOR=false+ local HAS_VM_GUEST_AGENT_AUDIT=false+ local HAS_SYS_AUDIT=false+ local PVE_VERSION=""+ local EXTRA_PRIVS=()++ if pveum role list 2>/dev/null | grep -q "VM.Monitor" ||+ pveum role add TestMonitor -privs VM.Monitor 2>/dev/null; then+ HAS_VM_MONITOR=true+ pveum role delete TestMonitor 2>/dev/null || true+ fi++ if pveum role list 2>/dev/null | grep -q "VM.GuestAgent.Audit"; then+ HAS_VM_GUEST_AGENT_AUDIT=true+ elif pveum role add TestGuestAgentAudit -privs VM.GuestAgent.Audit 2>/dev/null; then+ HAS_VM_GUEST_AGENT_AUDIT=true+ pveum role delete TestGuestAgentAudit 2>/dev/null || true+ fi++ if pveum role list 2>/dev/null | grep -q "Sys.Audit"; then+ HAS_SYS_AUDIT=true+ elif pveum role add TestSysAudit -privs Sys.Audit 2>/dev/null; then+ HAS_SYS_AUDIT=true+ pveum role delete TestSysAudit 2>/dev/null || true+ fi++ if command -v pveversion >/dev/null 2>&1; then+ PVE_VERSION=$(pveversion --verbose 2>/dev/null | grep "pve-manager" | awk -F'/' '{print $2}' | cut -d'.' -f1)+ fi++ if [ "$HAS_SYS_AUDIT" = true ]; then+ EXTRA_PRIVS+=("Sys.Audit")+ fi++ if [ "$HAS_VM_MONITOR" = true ]; then+ EXTRA_PRIVS+=("VM.Monitor")+ elif [ "$HAS_VM_GUEST_AGENT_AUDIT" = true ]; then+ EXTRA_PRIVS+=("VM.GuestAgent.Audit")+ fi++ if [ ${#EXTRA_PRIVS[@]} -gt 0 ]; then+ local PRIV_STRING+ PRIV_STRING="$(IFS=,; echo "${EXTRA_PRIVS[*]}")"++ if pveum role modify PulseMonitor -privs "$PRIV_STRING" 2>/dev/null || pveum role add PulseMonitor -privs "$PRIV_STRING" 2>/dev/null; then+ pveum aclmod / -user pulse-monitor@pve -role PulseMonitor+ if [ "$apply_token_acl" = true ]; then+ pveum aclmod / -token "$PULSE_TOKEN_ID" -role PulseMonitor+ fi+ echo " • Applied privileges: $PRIV_STRING"+ else+ echo " • Failed to configure PulseMonitor role with: $PRIV_STRING"+ echo " Assign these privileges manually if Pulse reports permission errors."+ fi+ else+ echo " • No additional privileges detected. Pulse may show limited VM metrics."+ if [ -n "$PVE_VERSION" ]; then+ echo " Detected PVE major version: $PVE_VERSION"+ fi+ fi+}++run_pve_setup_doctor() {+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+ echo "Pulse Proxmox Setup Doctor"+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+ echo ""+ echo "Checking Pulse-managed Proxmox user, token, ACLs, and legacy token drift."+ echo "This mode does not rotate the API token."+ echo ""++ local token_exists=false+ if pulse_pve_user_exists; then+ echo " ✓ Monitoring user exists: pulse-monitor@pve"+ else+ echo " ⚠ Missing monitoring user: pulse-monitor@pve"+ echo " Creating monitoring user..."+ pveum user add pulse-monitor@pve --comment "Pulse monitoring service" 2>/dev/null || true+ fi++ if pulse_pve_token_exists; then+ token_exists=true+ echo " ✓ Current token exists: $PULSE_TOKEN_ID"+ echo " Expire: $(pulse_pve_token_expire_label)"+ else+ echo " ⚠ Current token was not found: $PULSE_TOKEN_ID"+ echo " Choose Install/Configure to rotate the token and re-register Pulse with the new value."+ fi++ local old_tokens_pve old_tokens_pam old_count_pve old_count_pam+ old_tokens_pve=$(pulse_pve_matching_tokens pulse-monitor@pve)+ old_tokens_pam=$(pulse_pve_matching_tokens pulse-monitor@pam)+ old_count_pve=$(echo "$old_tokens_pve" | grep -c "pulse" || true)+ old_count_pam=$(echo "$old_tokens_pam" | grep -c "pulse" || true)+ echo ""+ echo "Pulse-managed token inventory:"+ if [ "$old_count_pve" -eq 0 ] && [ "$old_count_pam" -eq 0 ]; then+ echo " ✓ No matching Pulse-managed tokens found for this Pulse server scope."+ else+ [ -n "$old_tokens_pve" ] && echo "$old_tokens_pve" | sed 's/^/ • pulse-monitor@pve!/g'+ [ -n "$old_tokens_pam" ] && echo "$old_tokens_pam" | sed 's/^/ • pulse-monitor@pam!/g'+ echo " The current token is expected. Timestamp-suffixed entries are older Pulse-managed tokens."+ echo " ACL rows for both the user and current token are also expected."+ fi++ echo ""+ echo "Permission audit:"+ print_pve_acl_status "/" "pulse-monitor@pve" "PVEAuditor" "User has PVEAuditor at /"+ if [ "$token_exists" = true ]; then+ print_pve_acl_status "/" "$PULSE_TOKEN_ID" "PVEAuditor" "Token has PVEAuditor at /"+ print_pve_acl_status "/" "$PULSE_TOKEN_ID" "PulseMonitor" "Token has PulseMonitor at /"+ fi+ print_pve_acl_status "/" "pulse-monitor@pve" "PulseMonitor" "User has PulseMonitor at /"++ echo ""+ echo "Reapplying safe Pulse-managed permissions..."+ pveum aclmod / -user pulse-monitor@pve -role PVEAuditor+ if [ "$token_exists" = true ]; then+ pveum aclmod / -token "$PULSE_TOKEN_ID" -role PVEAuditor+ fi%s+ configure_pve_pulse_monitor_role "$token_exists"++ echo ""+ echo "Setup doctor complete."+ echo "If Pulse still shows 401 after this, the stored token value in Pulse no longer matches Proxmox."+ echo "Choose Install/Configure to rotate the token and let Pulse re-register it."+ echo ""+ exit 0+}+# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Main Menu# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━@@ -185,33 +396,42 @@ echo ""echo "What would you like to do?"echo ""echo " [1] Install/Configure - Set up Pulse monitoring"-echo " [2] Remove All - Uninstall everything Pulse has configured"-echo " [3] Cancel - Exit without changes"+echo " [2] Audit/Repair - Check and repair Pulse-managed Proxmox setup"+echo " [3] Remove All - Uninstall everything Pulse has configured"+echo " [4] Cancel - Exit without changes"echo ""-echo -n "Your choice [1/2/3]: "+echo -n "Your choice [1/2/3/4]: "-MAIN_ACTION=""+MAIN_ACTION="${PULSE_SETUP_ACTION:-}"if [ -t 0 ]; then- read -n 1 -r MAIN_ACTION+ if [ -z "$MAIN_ACTION" ]; then+ read -n 1 -r MAIN_ACTION+ fielse- if read -n 1 -r MAIN_ACTION </dev/tty 2>/dev/null; then- :- else- echo "(No terminal available - defaulting to Install)"- MAIN_ACTION="1"+ if [ -z "$MAIN_ACTION" ]; then+ if read -n 1 -r MAIN_ACTION </dev/tty 2>/dev/null; then+ :+ else+ echo "(No terminal available - defaulting to Install)"+ MAIN_ACTION="1"+ fififiecho ""echo ""# Handle Cancel-if [[ $MAIN_ACTION =~ ^[3Cc]$ ]]; then+if [[ $MAIN_ACTION =~ ^(4|[Cc]|cancel)$ ]]; thenecho "Cancelled. No changes made."exit 0fi+if [[ $MAIN_ACTION =~ ^(2|[Aa]|audit|repair)$ ]]; then+ run_pve_setup_doctor+fi+# Handle Remove All-if [[ $MAIN_ACTION =~ ^[2Rr]$ ]]; then+if [[ $MAIN_ACTION =~ ^(3|[Rr]|remove)$ ]]; thenecho "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"echo "🗑️ Complete Removal"echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"@@ -333,12 +553,9 @@ fiecho "Proceeding with installation..."echo ""-# Match canonical Pulse-managed token names for this Pulse server scope.-TOKEN_MATCH_PREFIX="%s"-# Check for old Pulse tokens from the same Pulse server and offer to clean them up-OLD_TOKENS_PVE=$(pveum user token list pulse-monitor@pve 2>/dev/null | awk -F'│' 'NR>3 {print $2}' | sed 's/^ *//;s/ *$//' | grep -E "^${TOKEN_MATCH_PREFIX}(-[0-9]+)?$" || true)-OLD_TOKENS_PAM=$(pveum user token list pulse-monitor@pam 2>/dev/null | awk -F'│' 'NR>3 {print $2}' | sed 's/^ *//;s/ *$//' | grep -E "^${TOKEN_MATCH_PREFIX}(-[0-9]+)?$" || true)+OLD_TOKENS_PVE=$(pulse_pve_matching_tokens pulse-monitor@pve)+OLD_TOKENS_PAM=$(pulse_pve_matching_tokens pulse-monitor@pam)if [ ! -z "$OLD_TOKENS_PVE" ] || [ ! -z "$OLD_TOKENS_PAM" ]; thenecho "Checking for existing Pulse monitoring tokens from this Pulse server..."TOKEN_COUNT_PVE=$(echo "$OLD_TOKENS_PVE" | grep -c "pulse" || true)@@ -471,7 +688,7 @@ TOKEN_OUTPUT=""TOKEN_VALUE=""TOKEN_CREATED=falseTOKEN_READY=false-if pveum user token list pulse-monitor@pve 2>/dev/null | awk 'NR>3 {print $2}' | grep -Fx "$TOKEN_NAME" >/dev/null 2>&1; then+if pulse_pve_token_exists; thenTOKEN_EXISTED=trueecho "Existing token '$TOKEN_NAME' found. Rotating in place..."if ! pveum user token remove pulse-monitor@pve "$TOKEN_NAME" >/dev/null 2>&1; then@@ -522,76 +739,7 @@ if [ "$TOKEN_CREATED" = true ]; thenpveum aclmod / -token "$PULSE_TOKEN_ID" -role PVEAuditorfi%s-# Detect Proxmox version and apply appropriate permissions-# Method 1: Try to check if VM.Monitor exists (reliable for PVE 8 and below)-HAS_VM_MONITOR=false-if pveum role list 2>/dev/null | grep -q "VM.Monitor" ||- pveum role add TestMonitor -privs VM.Monitor 2>/dev/null; then- HAS_VM_MONITOR=true- pveum role delete TestMonitor 2>/dev/null || true-fi--# Detect availability of newer guest agent privileges (PVE 9+)-HAS_VM_GUEST_AGENT_AUDIT=false-if pveum role list 2>/dev/null | grep -q "VM.GuestAgent.Audit"; then- HAS_VM_GUEST_AGENT_AUDIT=true-else- if pveum role add TestGuestAgentAudit -privs VM.GuestAgent.Audit 2>/dev/null; then- HAS_VM_GUEST_AGENT_AUDIT=true- pveum role delete TestGuestAgentAudit 2>/dev/null || true- fi-fi--# Detect availability of Sys.Audit (needed for Ceph metrics)-HAS_SYS_AUDIT=false-if pveum role list 2>/dev/null | grep -q "Sys.Audit"; then- HAS_SYS_AUDIT=true-else- if pveum role add TestSysAudit -privs Sys.Audit 2>/dev/null; then- HAS_SYS_AUDIT=true- pveum role delete TestSysAudit 2>/dev/null || true- fi-fi--# Method 2: Try to detect PVE version directly-PVE_VERSION=""-if command -v pveversion >/dev/null 2>&1; then- # Extract major version (e.g., "9" from "pve-manager/9.0.5/...")- PVE_VERSION=$(pveversion --verbose 2>/dev/null | grep "pve-manager" | awk -F'/' '{print $2}' | cut -d'.' -f1)-fi--EXTRA_PRIVS=()--if [ "$HAS_SYS_AUDIT" = true ]; then- EXTRA_PRIVS+=("Sys.Audit")-fi--if [ "$HAS_VM_MONITOR" = true ]; then- # PVE 8 or below - VM.Monitor exists- EXTRA_PRIVS+=("VM.Monitor")-elif [ "$HAS_VM_GUEST_AGENT_AUDIT" = true ]; then- # PVE 9+ - VM.Monitor removed, prefer VM.GuestAgent.Audit for guest data- EXTRA_PRIVS+=("VM.GuestAgent.Audit")-fi--if [ ${#EXTRA_PRIVS[@]} -gt 0 ]; then- # Join as comma-separated list (pveum expects comma-separated privilege names).- PRIV_STRING="$(IFS=,; echo "${EXTRA_PRIVS[*]}")"-- # Prefer modify (non-destructive) in case PulseMonitor already exists.- if pveum role modify PulseMonitor -privs "$PRIV_STRING" 2>/dev/null || pveum role add PulseMonitor -privs "$PRIV_STRING" 2>/dev/null; then- pveum aclmod / -user pulse-monitor@pve -role PulseMonitor- if [ "$TOKEN_CREATED" = true ]; then- pveum aclmod / -token "$PULSE_TOKEN_ID" -role PulseMonitor- fi- echo " • Applied privileges: $PRIV_STRING"- else- echo " • Failed to configure PulseMonitor role with: $PRIV_STRING"- echo " Assign these privileges manually if Pulse reports permission errors."- fi-else- echo " • No additional privileges detected. Pulse may show limited VM metrics."-fi+configure_pve_pulse_monitor_role "$TOKEN_CREATED"if [ "$TOKEN_READY" = true ]; thenattempt_auto_registration@@ -1071,8 +1219,8 @@ if [ "$AUTO_REG_SUCCESS" != true ] && [ "$SETUP_TOKEN_INVALID" != true ]; thenfifi`, ctx.ServerName, time.Now().Format("2006-01-02 15:04:05"),- ctx.PulseURL, ctx.ServerHost, ctx.SetupToken, ctx.TokenName, ctx.Artifact.URL, posixShellQuote(ctx.Artifact.CommandWithEnv),- ctx.TokenMatchPrefix,+ ctx.PulseURL, ctx.ServerHost, ctx.SetupToken, ctx.TokenName, ctx.TokenMatchPrefix, ctx.Artifact.URL, posixShellQuote(ctx.Artifact.CommandWithEnv),+ ctx.StorageRepairPerms,ctx.StoragePerms,ctx.SensorsPublicKey)}