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
Improve auto-register auth errors and setup token grace window (#1319)
rcourtmana6f6f6607825
diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.goindex 9c1b02c3c2..f14ca3e42b 100644--- a/internal/api/config_handlers.go+++ b/internal/api/config_handlers.go@@ -43,6 +43,16 @@ var (pulseTokenSlugPattern = regexp.MustCompile(`[^a-z0-9]+`))+const (+ autoRegisterAuthMissing = "Pulse requires authentication"+ autoRegisterAuthInvalidAPI = "Invalid API token"+ autoRegisterAuthMissingScope = "API token missing required scope; requires settings:write or host-agent:report"+ autoRegisterAuthExpiredSetup = "Expired setup token"+ autoRegisterAuthUsedSetup = "Setup token already used"+ autoRegisterAuthInvalidSetup = "Invalid setup token"+ autoRegisterAuthSetupNodeType = "Setup token is not valid for this node type"+)+func sanitizeInstallerURL(raw string) (string, error) {trimmed := strings.TrimSpace(raw)if trimmed == "" {@@ -151,6 +161,11 @@ type SetupCode struct {OrgID string // Organization ID creating this code}+type recentSetupToken struct {+ ExpiresAt time.Time+ NodeType string+}+// ConfigHandlers handles configuration-related API endpointstype ConfigHandlers struct {mtPersistence *config.MultiTenantPersistence@@ -164,9 +179,9 @@ type ConfigHandlers struct {reloadSystemSettingsFunc func() // Function to reload cached system settingswsHub *websocket.HubguestMetadataHandler *GuestMetadataHandler- setupCodes map[string]*SetupCode // Map of code hash -> setup code details- recentSetupTokens map[string]time.Time // Temporary map for recently used setup tokens (grace period)- codeMutex sync.RWMutex // Mutex for thread-safe code access+ setupCodes map[string]*SetupCode // Map of code hash -> setup code details+ recentSetupTokens map[string]recentSetupToken // Temporary map for recently used setup tokens (grace period)+ codeMutex sync.RWMutex // Mutex for thread-safe code accessclusterDetectMutex sync.MutexlastClusterDetection map[string]time.TimerecentAutoRegistered map[string]time.Time@@ -206,7 +221,7 @@ func NewConfigHandlers(mtp *config.MultiTenantPersistence, mtm *monitoring.MultiwsHub: wsHub,guestMetadataHandler: guestMetadataHandler,setupCodes: make(map[string]*SetupCode),- recentSetupTokens: make(map[string]time.Time),+ recentSetupTokens: make(map[string]recentSetupToken),lastClusterDetection: make(map[string]time.Time),recentAutoRegistered: make(map[string]time.Time),}@@ -308,8 +323,8 @@ func (h *ConfigHandlers) cleanupExpiredCodes() {log.Debug().Bool("was_used", code.Used).Msg("Cleaned up setup code")}}- for tokenHash, expiresAt := range h.recentSetupTokens {- if now.After(expiresAt) {+ for tokenHash, recent := range h.recentSetupTokens {+ if now.After(recent.ExpiresAt) {delete(h.recentSetupTokens, tokenHash)}}@@ -335,11 +350,51 @@ func (h *ConfigHandlers) ValidateSetupToken(token string) bool {}}- if expiresAt, ok := h.recentSetupTokens[tokenHash]; ok && now.Before(expiresAt) {- return true+ return false+}++func (h *ConfigHandlers) validateAutoRegisterSetupToken(token, nodeType string) (bool, string) {+ if strings.TrimSpace(token) == "" {+ return false, autoRegisterAuthInvalidSetup}- return false+ tokenHash := internalauth.HashAPIToken(token)+ now := time.Now()++ h.codeMutex.Lock()+ defer h.codeMutex.Unlock()++ if recent, ok := h.recentSetupTokens[tokenHash]; ok && now.Before(recent.ExpiresAt) {+ if recent.NodeType != "" && recent.NodeType != nodeType {+ return false, autoRegisterAuthSetupNodeType+ }+ return true, ""+ }++ setupCode, exists := h.setupCodes[tokenHash]+ if !exists {+ return false, autoRegisterAuthInvalidSetup+ }+ if !now.Before(setupCode.ExpiresAt) {+ return false, autoRegisterAuthExpiredSetup+ }+ if setupCode.NodeType != "" && setupCode.NodeType != nodeType {+ return false, autoRegisterAuthSetupNodeType+ }+ if setupCode.Used {+ return false, autoRegisterAuthUsedSetup+ }++ setupCode.Used = true+ graceExpiry := now.Add(1 * time.Minute)+ if setupCode.ExpiresAt.Before(graceExpiry) {+ graceExpiry = setupCode.ExpiresAt+ }+ h.recentSetupTokens[tokenHash] = recentSetupToken{+ ExpiresAt: graceExpiry,+ NodeType: setupCode.NodeType,+ }+ return true, ""}func (h *ConfigHandlers) markAutoRegistered(nodeType, nodeName string) {@@ -5195,6 +5250,7 @@ func (h *ConfigHandlers) HandleAutoRegister(w http.ResponseWriter, r *http.Reque// Check authentication - require either setup code or API token if auth is enabledauthenticated := false+ authFailureReason := ""// Support both setupCode (old) and authToken (new) fieldsauthCode := req.SetupCode@@ -5240,89 +5296,88 @@ func (h *ConfigHandlers) HandleAutoRegister(w http.ResponseWriter, r *http.Requereturn ""}+ setAuthFailure := func(reason string) {+ if reason == "" || authFailureReason != "" {+ return+ }+ authFailureReason = reason+ }+// First check for setup code/auth token in the requestif authCode != "" {+ authCode = strings.TrimSpace(authCode)+ authCodeLooksLikeSetupToken := setupAuthTokenPattern.MatchString(authCode)matchedAPIToken := falseif h.getConfig(r.Context()).HasAPITokens() {if record, ok := validateAPIToken(authCode); ok {+ matchedAPIToken = true// Accept settings:write (admin tokens) or host-agent:report (agent tokens)if record.HasScope(config.ScopeSettingsWrite) || record.HasScope(config.ScopeHostReport) {authenticated = true- matchedAPIToken = truelog.Info().Str("type", req.Type).Str("host", req.Host).Msg("Auto-register authenticated via direct API token")} else {+ setAuthFailure(autoRegisterAuthMissingScope)log.Warn().Str("type", req.Type).Str("host", req.Host).Msg("Auto-register rejected: API token missing required scope")}+ } else if !authCodeLooksLikeSetupToken {+ setAuthFailure(autoRegisterAuthInvalidAPI)}+ } else if !authCodeLooksLikeSetupToken {+ setAuthFailure(autoRegisterAuthInvalidAPI)}- if !matchedAPIToken {- // Not the API token, check if it's a temporary setup code+ if !authenticated && !matchedAPIToken && (authCodeLooksLikeSetupToken || !h.getConfig(r.Context()).HasAPITokens()) {codeHash := internalauth.HashAPIToken(authCode)log.Debug().Bool("hasAuthCode", true).Str("codeHash", safePrefixForLog(codeHash, 8)+"...").Msg("Checking auth token as setup code")- h.codeMutex.Lock()- setupCode, exists := h.setupCodes[codeHash]- log.Debug().- Bool("exists", exists).- Int("totalCodes", len(h.setupCodes)).- Msg("Setup code lookup result")- if exists && !setupCode.Used && time.Now().Before(setupCode.ExpiresAt) {- // Validate that the code matches the node type- // Note: We don't validate the host anymore as it may differ between- // what's entered in the UI and what's provided in the setup script URL- if setupCode.NodeType == req.Type {- setupCode.Used = true // Mark as used immediately-- // Allow a short grace period for follow-up actions without keeping tokens alive too long- graceExpiry := time.Now().Add(1 * time.Minute)- if setupCode.ExpiresAt.Before(graceExpiry) {- graceExpiry = setupCode.ExpiresAt- }- h.recentSetupTokens[codeHash] = graceExpiry- authenticated = true- log.Info().- Str("type", req.Type).- Str("host", req.Host).- Bool("via_authToken", req.AuthToken != "").- Msg("Auto-register authenticated via setup code/token")- } else {- log.Warn().- Str("expected_type", setupCode.NodeType).- Str("got_type", req.Type).- Msg("Setup code validation failed - type mismatch")- }- } else if exists && setupCode.Used {- log.Warn().Msg("Setup code already used")- } else if exists {- log.Warn().Msg("Setup code expired")++ if ok, reason := h.validateAutoRegisterSetupToken(authCode, req.Type); ok {+ authenticated = true+ log.Info().+ Str("type", req.Type).+ Str("host", req.Host).+ Bool("via_authToken", req.AuthToken != "").+ Msg("Auto-register authenticated via setup code/token")} else {- log.Warn().Msg("Invalid setup code/token - not in setup codes map")+ setAuthFailure(reason)+ log.Warn().+ Str("type", req.Type).+ Str("host", req.Host).+ Str("reason", reason).+ Msg("Auto-register rejected: setup token validation failed")}- h.codeMutex.Unlock()}}// If not authenticated via setup code, check API token if configuredif !authenticated && h.getConfig(r.Context()).HasAPITokens() {apiToken := requestAPIToken()- if record, ok := validateAPIToken(apiToken); ok {- // Accept settings:write (admin tokens) or host-agent:report (agent tokens)- if record.HasScope(config.ScopeSettingsWrite) || record.HasScope(config.ScopeHostReport) {- authenticated = true- log.Info().Msg("Auto-register authenticated via API token")+ if apiToken != "" {+ if record, ok := validateAPIToken(apiToken); ok {+ // Accept settings:write (admin tokens) or host-agent:report (agent tokens)+ if record.HasScope(config.ScopeSettingsWrite) || record.HasScope(config.ScopeHostReport) {+ authenticated = true+ log.Info().Msg("Auto-register authenticated via API token")+ } else {+ setAuthFailure(autoRegisterAuthMissingScope)+ log.Warn().Msg("Auto-register rejected: API token missing required scope")+ }} else {- log.Warn().Msg("Auto-register rejected: API token missing required scope")+ setAuthFailure(autoRegisterAuthInvalidAPI)}}+ } else if !authenticated {+ if apiToken := requestAPIToken(); apiToken != "" {+ setAuthFailure(autoRegisterAuthInvalidAPI)+ }}// Abort when no authentication succeeded. This applies even when API tokens@@ -5331,13 +5386,13 @@ func (h *ConfigHandlers) HandleAutoRegister(w http.ResponseWriter, r *http.Requelog.Warn().Str("ip", r.RemoteAddr).Bool("has_auth_code", authCode != "").+ Str("reason", authFailureReason).Msg("Unauthorized auto-register attempt rejected")- if authCode == "" && r.Header.Get("X-API-Token") == "" {- http.Error(w, "Pulse requires authentication", http.StatusUnauthorized)- } else {- http.Error(w, "Invalid or expired setup code", http.StatusUnauthorized)+ if authFailureReason == "" {+ authFailureReason = autoRegisterAuthMissing}+ http.Error(w, authFailureReason, http.StatusUnauthorized)return}diff --git a/internal/api/config_handlers_auto_register_test.go b/internal/api/config_handlers_auto_register_test.goindex dc78b098f3..826c3b70b1 100644--- a/internal/api/config_handlers_auto_register_test.go+++ b/internal/api/config_handlers_auto_register_test.go@@ -6,6 +6,7 @@ import ("encoding/json""net/http""net/http/httptest"+ "strings""testing""time"@@ -63,6 +64,9 @@ func TestHandleAutoRegisterRejectsWithoutAuth(t *testing.T) {if rec.Code != http.StatusUnauthorized {t.Fatalf("expected status 401, got %d, body=%s", rec.Code, rec.Body.String())}+ if !strings.Contains(rec.Body.String(), autoRegisterAuthMissing) {+ t.Fatalf("expected missing-auth error, got %q", rec.Body.String())+ }}func TestHandleAutoRegisterAcceptsWithSetupToken(t *testing.T) {@@ -113,6 +117,146 @@ func TestHandleAutoRegisterAcceptsWithSetupToken(t *testing.T) {}}+func TestHandleAutoRegisterAcceptsRecentlyUsedSetupToken(t *testing.T) {+ tempDir := t.TempDir()+ t.Setenv("PULSE_DATA_DIR", tempDir)++ cfg := &config.Config{+ DataPath: tempDir,+ ConfigPath: tempDir,+ }++ handler := newTestConfigHandlers(t, cfg)++ const tokenValue = "ABCDEF1234567890ABCDEF1234567890"+ tokenHash := internalauth.HashAPIToken(tokenValue)+ handler.codeMutex.Lock()+ handler.setupCodes[tokenHash] = &SetupCode{+ ExpiresAt: time.Now().Add(5 * time.Minute),+ Used: true,+ NodeType: "pve",+ }+ handler.recentSetupTokens[tokenHash] = recentSetupToken{+ ExpiresAt: time.Now().Add(30 * time.Second),+ NodeType: "pve",+ }+ handler.codeMutex.Unlock()++ reqBody := AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve.local:8006",+ TokenID: "pulse-monitor@pam!token",+ TokenValue: "secret-token",+ ServerName: "pve.local",+ AuthToken: tokenValue,+ }++ body, err := json.Marshal(reqBody)+ if err != nil {+ t.Fatalf("failed to marshal request: %v", err)+ }++ req := httptest.NewRequest(http.MethodPost, "/api/auto-register", bytes.NewReader(body))+ rec := httptest.NewRecorder()++ handler.HandleAutoRegister(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status 200, got %d, body=%s", rec.Code, rec.Body.String())+ }+}++func TestHandleAutoRegisterRejectsUsedSetupTokenOutsideGrace(t *testing.T) {+ tempDir := t.TempDir()+ t.Setenv("PULSE_DATA_DIR", tempDir)++ cfg := &config.Config{+ DataPath: tempDir,+ ConfigPath: tempDir,+ }++ handler := newTestConfigHandlers(t, cfg)++ const tokenValue = "1234567890ABCDEF1234567890ABCDEF"+ tokenHash := internalauth.HashAPIToken(tokenValue)+ handler.codeMutex.Lock()+ handler.setupCodes[tokenHash] = &SetupCode{+ ExpiresAt: time.Now().Add(5 * time.Minute),+ Used: true,+ NodeType: "pve",+ }+ handler.recentSetupTokens[tokenHash] = recentSetupToken{+ ExpiresAt: time.Now().Add(-30 * time.Second),+ NodeType: "pve",+ }+ handler.codeMutex.Unlock()++ reqBody := AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve.local:8006",+ TokenID: "pulse-monitor@pam!token",+ TokenValue: "secret-token",+ ServerName: "pve.local",+ AuthToken: tokenValue,+ }++ body, err := json.Marshal(reqBody)+ if err != nil {+ t.Fatalf("failed to marshal request: %v", err)+ }++ req := httptest.NewRequest(http.MethodPost, "/api/auto-register", bytes.NewReader(body))+ rec := httptest.NewRecorder()++ handler.HandleAutoRegister(rec, req)++ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("expected status 401, got %d, body=%s", rec.Code, rec.Body.String())+ }+ if !strings.Contains(rec.Body.String(), autoRegisterAuthUsedSetup) {+ t.Fatalf("expected used-setup-token error, got %q", rec.Body.String())+ }+}++func TestValidateAutoRegisterSetupTokenAcceptsGraceReplayAfterCleanupForMatchingType(t *testing.T) {+ const tokenValue = "ABCDEF1234567890ABCDEF1234567890"+ tokenHash := internalauth.HashAPIToken(tokenValue)++ handler := newTestConfigHandlers(t, &config.Config{DataPath: t.TempDir(), ConfigPath: t.TempDir()})+ handler.codeMutex.Lock()+ handler.recentSetupTokens[tokenHash] = recentSetupToken{+ ExpiresAt: time.Now().Add(30 * time.Second),+ NodeType: "pve",+ }+ handler.codeMutex.Unlock()++ ok, reason := handler.validateAutoRegisterSetupToken(tokenValue, "pve")+ if !ok {+ t.Fatalf("expected grace replay to succeed, got ok=%v reason=%q", ok, reason)+ }+}++func TestValidateAutoRegisterSetupTokenRejectsGraceReplayAfterCleanupForWrongType(t *testing.T) {+ const tokenValue = "1234567890ABCDEF1234567890ABCDEF"+ tokenHash := internalauth.HashAPIToken(tokenValue)++ handler := newTestConfigHandlers(t, &config.Config{DataPath: t.TempDir(), ConfigPath: t.TempDir()})+ handler.codeMutex.Lock()+ handler.recentSetupTokens[tokenHash] = recentSetupToken{+ ExpiresAt: time.Now().Add(30 * time.Second),+ NodeType: "pve",+ }+ handler.codeMutex.Unlock()++ ok, reason := handler.validateAutoRegisterSetupToken(tokenValue, "pbs")+ if ok {+ t.Fatalf("expected grace replay to be rejected for wrong node type")+ }+ if reason != autoRegisterAuthSetupNodeType {+ t.Fatalf("expected reason %q, got %q", autoRegisterAuthSetupNodeType, reason)+ }+}+// TestDisambiguateNodeName verifies that duplicate hostnames get disambiguated// with their IP address appended. Issue #891.func TestDisambiguateNodeName(t *testing.T) {diff --git a/internal/api/config_handlers_pve_user_test.go b/internal/api/config_handlers_pve_user_test.goindex 6758ee8918..968f37cbdd 100644--- a/internal/api/config_handlers_pve_user_test.go+++ b/internal/api/config_handlers_pve_user_test.go@@ -620,7 +620,7 @@ func TestValidateSetupToken(t *testing.T) {t.Run("empty token returns false", func(t *testing.T) {h := &ConfigHandlers{setupCodes: make(map[string]*SetupCode),- recentSetupTokens: make(map[string]time.Time),+ recentSetupTokens: make(map[string]recentSetupToken),}if h.ValidateSetupToken("") {@@ -639,7 +639,7 @@ func TestValidateSetupToken(t *testing.T) {Used: false,},},- recentSetupTokens: make(map[string]time.Time),+ recentSetupTokens: make(map[string]recentSetupToken),}if !h.ValidateSetupToken(token) {@@ -658,7 +658,7 @@ func TestValidateSetupToken(t *testing.T) {Used: false,},},- recentSetupTokens: make(map[string]time.Time),+ recentSetupTokens: make(map[string]recentSetupToken),}if h.ValidateSetupToken(token) {@@ -677,7 +677,7 @@ func TestValidateSetupToken(t *testing.T) {Used: true, // Already used},},- recentSetupTokens: make(map[string]time.Time),+ recentSetupTokens: make(map[string]recentSetupToken),}if h.ValidateSetupToken(token) {@@ -685,19 +685,21 @@ func TestValidateSetupToken(t *testing.T) {}})- t.Run("valid recent setup token", func(t *testing.T) {+ t.Run("valid recent setup token returns false", func(t *testing.T) {token := "recent-setup-token-12345"tokenHash := auth.HashAPIToken(token)h := &ConfigHandlers{setupCodes: make(map[string]*SetupCode),- recentSetupTokens: map[string]time.Time{- tokenHash: time.Now().Add(1 * time.Hour), // Valid for another hour+ recentSetupTokens: map[string]recentSetupToken{+ tokenHash: {+ ExpiresAt: time.Now().Add(1 * time.Hour), // Grace window is auto-register only+ },},}- if !h.ValidateSetupToken(token) {- t.Error("expected true for valid recent setup token")+ if h.ValidateSetupToken(token) {+ t.Error("expected false for recent setup token outside auto-register")}})@@ -707,8 +709,10 @@ func TestValidateSetupToken(t *testing.T) {h := &ConfigHandlers{setupCodes: make(map[string]*SetupCode),- recentSetupTokens: map[string]time.Time{- tokenHash: time.Now().Add(-1 * time.Hour), // Expired+ recentSetupTokens: map[string]recentSetupToken{+ tokenHash: {+ ExpiresAt: time.Now().Add(-1 * time.Hour), // Expired+ },},}@@ -720,7 +724,7 @@ func TestValidateSetupToken(t *testing.T) {t.Run("non-existent token returns false", func(t *testing.T) {h := &ConfigHandlers{setupCodes: make(map[string]*SetupCode),- recentSetupTokens: make(map[string]time.Time),+ recentSetupTokens: make(map[string]recentSetupToken),}if h.ValidateSetupToken("non-existent-token") {@@ -739,8 +743,10 @@ func TestValidateSetupToken(t *testing.T) {Used: false,},},- recentSetupTokens: map[string]time.Time{- tokenHash: time.Now().Add(1 * time.Hour),+ recentSetupTokens: map[string]recentSetupToken{+ tokenHash: {+ ExpiresAt: time.Now().Add(1 * time.Hour),+ },},}diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.goindex e2cab92381..8a7bc4a123 100644--- a/internal/api/security_regression_test.go+++ b/internal/api/security_regression_test.go@@ -1826,6 +1826,9 @@ func TestAutoRegisterRequiresAuth(t *testing.T) {if rec.Code != http.StatusUnauthorized {t.Fatalf("expected 401 without auth, got %d", rec.Code)}+ if !strings.Contains(rec.Body.String(), autoRegisterAuthMissing) {+ t.Fatalf("expected missing-auth error, got %q", rec.Body.String())+ }}func TestAutoRegisterRejectsTokenMissingRequiredScope(t *testing.T) {@@ -1842,6 +1845,26 @@ func TestAutoRegisterRejectsTokenMissingRequiredScope(t *testing.T) {if rec.Code != http.StatusUnauthorized {t.Fatalf("expected 401 for missing required scope, got %d", rec.Code)}+ if !strings.Contains(rec.Body.String(), autoRegisterAuthMissingScope) {+ t.Fatalf("expected scope error, got %q", rec.Body.String())+ }+}++func TestAutoRegisterRejectsInvalidAPIToken(t *testing.T) {+ cfg := newTestConfigWithTokens(t)+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")+ router.configHandlers.SetConfig(cfg)++ req := httptest.NewRequest(http.MethodPost, "/api/auto-register", strings.NewReader(`{}`))+ req.Header.Set("X-API-Token", "invalid-token-123.12345678")+ rec := httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401 for invalid API token, got %d", rec.Code)+ }+ if !strings.Contains(rec.Body.String(), autoRegisterAuthInvalidAPI) {+ t.Fatalf("expected invalid API token error, got %q", rec.Body.String())+ }}func TestAutoRegisterAcceptsAgentToken(t *testing.T) {