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.

Keep token issuance atomic on persistence failure

pulse-triage[bot]56fc9b82555c
diff --git a/internal/api/router.go b/internal/api/router.go
index 833f8afb0c..1fdd5ee524 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -8118,12 +8118,14 @@ func (r *Router) handleDiagnosticsDockerPrepareToken(w http.ResponseWriter, req
}
config.Mu.Lock()
+ previousTokens := append([]config.APITokenRecord(nil), activeConfig.APITokens...)
activeConfig.APITokens = append(activeConfig.APITokens, *record)
activeConfig.SortAPITokens()
if activePersistence != nil {
if err := activePersistence.SaveAPITokens(activeConfig.APITokens); err != nil {
- activeConfig.RemoveAPIToken(record.ID)
+ activeConfig.APITokens = previousTokens
+ activeConfig.SortAPITokens()
config.Mu.Unlock()
log.Error().Err(err).Msg("Failed to persist API tokens after container runtime migration generation")
writeErrorResponse(w, http.StatusInternalServerError, "token_persist_failed", "Failed to persist API token", nil)
diff --git a/internal/api/router_low_coverage_additional_test.go b/internal/api/router_low_coverage_additional_test.go
index 5c704ea9c7..4b4def0615 100644
--- a/internal/api/router_low_coverage_additional_test.go
+++ b/internal/api/router_low_coverage_additional_test.go
@@ -5,6 +5,8 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"strings"
"testing"
@@ -198,6 +200,50 @@ func TestHandleDiagnosticsDockerPrepareToken_Success(t *testing.T) {
}
}
+func TestHandleDiagnosticsDockerPrepareToken_RollsBackWhenPersistenceFails(t *testing.T) {
+ monitor, state, _ := newTestMonitor(t)
+ state.DockerHosts = []models.DockerHost{{ID: "host-1", DisplayName: "Docker Host"}}
+
+ rawToken := "existing-container-runtime-token.12345678"
+ existing, err := config.NewAPITokenRecord(rawToken, "existing token", []string{config.ScopeSettingsWrite})
+ if err != nil {
+ t.Fatalf("new existing token: %v", err)
+ }
+ cfg := &config.Config{
+ PublicURL: "https://pulse.example.com",
+ APITokens: []config.APITokenRecord{*existing},
+ }
+ cfg.SortAPITokens()
+ previousPrimaryToken := cfg.APIToken
+
+ dataDir := filepath.Join(t.TempDir(), "state")
+ persistence := config.NewConfigPersistence(dataDir)
+ if err := os.RemoveAll(dataDir); err != nil {
+ t.Fatalf("remove persistence directory: %v", err)
+ }
+ if err := os.WriteFile(dataDir, []byte("not a directory"), 0o600); err != nil {
+ t.Fatalf("create persistence blocker: %v", err)
+ }
+ router := &Router{monitor: monitor, config: cfg, persistence: persistence}
+ req := httptest.NewRequest(http.MethodPost, "/api/diagnostics/docker/prepare-token", strings.NewReader(`{"agentId":"host-1"}`))
+ rec := httptest.NewRecorder()
+
+ router.handleDiagnosticsDockerPrepareToken(rec, req)
+
+ if rec.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusInternalServerError, rec.Body.String())
+ }
+ if len(cfg.APITokens) != 1 || cfg.APITokens[0].ID != existing.ID {
+ t.Fatalf("live token inventory changed after failed persistence: %+v", cfg.APITokens)
+ }
+ if cfg.APIToken != previousPrimaryToken {
+ t.Fatalf("legacy primary token = %q, want rollback to %q", cfg.APIToken, previousPrimaryToken)
+ }
+ if strings.Contains(rec.Body.String(), `"token"`) {
+ t.Fatalf("failed token preparation exposed an unpersisted token: %q", rec.Body.String())
+ }
+}
+
func TestHandleDiagnosticsDockerPrepareToken_PreservesExplicitWorkloadOnlyMode(t *testing.T) {
monitor, state, _ := newTestMonitor(t)
state.DockerHosts = []models.DockerHost{{ID: "host-1", DisplayName: "Docker Host"}}
diff --git a/internal/api/security_setup_fix.go b/internal/api/security_setup_fix.go
index 1b26dc2f1e..f17c4226d7 100644
--- a/internal/api/security_setup_fix.go
+++ b/internal/api/security_setup_fix.go
@@ -502,17 +502,22 @@ func handleQuickSecuritySetupFixed(r *Router) http.HandlerFunc {
// Update runtime config immediately with hashed token - no restart needed!
config.Mu.Lock()
+ previousTokens := append([]config.APITokenRecord(nil), r.config.APITokens...)
r.config.AuthUser = setupRequest.Username
r.config.AuthPass = hashedPassword
r.config.APITokens = []config.APITokenRecord{*tokenRecord}
r.config.SortAPITokens()
- config.Mu.Unlock()
-
if r.persistence != nil {
if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil {
- log.Warn().Err(err).Msg("Failed to persist API tokens during security setup")
+ r.config.APITokens = previousTokens
+ r.config.SortAPITokens()
+ config.Mu.Unlock()
+ log.Error().Err(err).Msg("Failed to persist API tokens during security setup")
+ http.Error(w, "Password authentication was saved, but the API token could not be saved", http.StatusInternalServerError)
+ return
}
}
+ config.Mu.Unlock()
log.Info().Msg("Runtime config updated with new security settings - active immediately")
if err := r.establishSession(w, req, setupRequest.Username); err != nil {
@@ -712,16 +717,21 @@ func (r *Router) HandleRegenerateAPIToken(w http.ResponseWriter, rq *http.Reques
setAPITokenOwnerUserID(tokenRecord, apiTokenOwnerUserIDForRequest(r.config, rq))
config.Mu.Lock()
+ previousTokens := append([]config.APITokenRecord(nil), r.config.APITokens...)
r.config.APITokens = []config.APITokenRecord{*tokenRecord}
r.config.SortAPITokens()
- config.Mu.Unlock()
- log.Info().Msg("Runtime config updated with new API token - active immediately")
-
if r.persistence != nil {
if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil {
- log.Warn().Err(err).Msg("Failed to persist regenerated API token")
+ r.config.APITokens = previousTokens
+ r.config.SortAPITokens()
+ config.Mu.Unlock()
+ log.Error().Err(err).Msg("Failed to persist regenerated API token")
+ http.Error(w, "Failed to save token", http.StatusInternalServerError)
+ return
}
}
+ config.Mu.Unlock()
+ log.Info().Msg("Runtime config updated with new API token - active immediately")
log.Info().Msg("API token regenerated successfully")
diff --git a/internal/api/security_setup_fix_additional_test.go b/internal/api/security_setup_fix_additional_test.go
index 98e670fec6..0eaf450f3a 100644
--- a/internal/api/security_setup_fix_additional_test.go
+++ b/internal/api/security_setup_fix_additional_test.go
@@ -15,6 +15,32 @@ import (
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
+type failingWriteFileSystem struct{}
+
+func (failingWriteFileSystem) ReadFile(name string) ([]byte, error) {
+ return os.ReadFile(name)
+}
+
+func (failingWriteFileSystem) WriteFile(string, []byte, os.FileMode) error {
+ return errors.New("forced write failure")
+}
+
+func (failingWriteFileSystem) Rename(oldPath, newPath string) error {
+ return os.Rename(oldPath, newPath)
+}
+
+func (failingWriteFileSystem) Remove(name string) error {
+ return os.Remove(name)
+}
+
+func (failingWriteFileSystem) Stat(name string) (os.FileInfo, error) {
+ return os.Stat(name)
+}
+
+func (failingWriteFileSystem) MkdirAll(path string, perm os.FileMode) error {
+ return os.MkdirAll(path, perm)
+}
+
func TestDetectServiceName_Default(t *testing.T) {
t.Setenv("PATH", "")
@@ -118,6 +144,57 @@ func TestHandleRegenerateAPITokenInheritsOwnerFromCallerToken(t *testing.T) {
}
}
+func TestHandleRegenerateAPITokenRollsBackWhenPersistenceFails(t *testing.T) {
+ dataDir := filepath.Join(t.TempDir(), "state")
+ rawCallerToken := "regen-persistence-token-123.12345678"
+ callerRecord, err := config.NewAPITokenRecord(rawCallerToken, "existing-admin-token", []string{config.ScopeSettingsWrite})
+ if err != nil {
+ t.Fatalf("new caller token record: %v", err)
+ }
+
+ cfg := &config.Config{
+ DataPath: dataDir,
+ ConfigPath: dataDir,
+ APITokens: []config.APITokenRecord{*callerRecord},
+ }
+ cfg.SortAPITokens()
+ previousPrimaryToken := cfg.APIToken
+
+ // Block persistence after construction so the handler must restore the
+ // complete live credential inventory rather than expose a transient token.
+ persistence := config.NewConfigPersistence(dataDir)
+ if err := os.RemoveAll(dataDir); err != nil {
+ t.Fatalf("remove persistence directory: %v", err)
+ }
+ if err := os.WriteFile(dataDir, []byte("not a directory"), 0o600); err != nil {
+ t.Fatalf("create persistence blocker: %v", err)
+ }
+ router := &Router{config: cfg, persistence: persistence}
+
+ authLimiter.Reset("127.0.0.1")
+ req := newLoopbackRequest(http.MethodPost, "/api/security/regenerate-token", nil)
+ req.Header.Set("X-API-Token", rawCallerToken)
+ rec := httptest.NewRecorder()
+
+ router.HandleRegenerateAPIToken(rec, req)
+
+ if rec.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusInternalServerError, rec.Body.String())
+ }
+ if len(cfg.APITokens) != 1 || cfg.APITokens[0].ID != callerRecord.ID {
+ t.Fatalf("live token inventory changed after failed persistence: %+v", cfg.APITokens)
+ }
+ if cfg.APIToken != previousPrimaryToken {
+ t.Fatalf("legacy primary token = %q, want rollback to %q", cfg.APIToken, previousPrimaryToken)
+ }
+ if strings.Contains(rec.Body.String(), `"token"`) {
+ t.Fatalf("failed regeneration exposed an unpersisted token: %q", rec.Body.String())
+ }
+ if !internalauth.CompareAPIToken(rawCallerToken, cfg.APITokens[0].Hash) {
+ t.Fatal("previous credential no longer authenticates after failed persistence")
+ }
+}
+
func TestHandleValidateAPIToken_InvalidJSON(t *testing.T) {
router := &Router{config: &config.Config{}}
handler := http.HandlerFunc(router.HandleValidateAPIToken)
@@ -477,6 +554,75 @@ func TestQuickSecuritySetupRotatesWithBasicAuth(t *testing.T) {
}
}
+func TestQuickSecuritySetupRestoresTokensWhenPersistenceFails(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")
+ resetTrustedProxyConfig()
+
+ dataDir := t.TempDir()
+ oldPasswordHash, err := internalauth.HashPassword("ExistingPassword!1")
+ if err != nil {
+ t.Fatalf("hash existing password: %v", err)
+ }
+ rawOldToken := strings.Repeat("ab", 32)
+ oldToken, err := config.NewAPITokenRecord(rawOldToken, "existing token", []string{config.ScopeSettingsWrite})
+ if err != nil {
+ t.Fatalf("new existing token: %v", err)
+ }
+ cfg := &config.Config{
+ AuthUser: "admin",
+ AuthPass: oldPasswordHash,
+ DataPath: dataDir,
+ ConfigPath: dataDir,
+ APITokens: []config.APITokenRecord{*oldToken},
+ }
+ cfg.SortAPITokens()
+ previousPrimaryToken := cfg.APIToken
+
+ persistence := config.NewConfigPersistence(dataDir)
+ if err := persistence.SaveAPITokens(cfg.APITokens); err != nil {
+ t.Fatalf("save existing tokens: %v", err)
+ }
+ persistence.SetFileSystem(failingWriteFileSystem{})
+ router := &Router{config: cfg, persistence: persistence}
+
+ authLimiter.Reset("198.51.100.17")
+ newRawToken := strings.Repeat("cd", 32)
+ payload := `{"username":"newadmin","password":"NewPassword!1","apiToken":"` + newRawToken + `","force":true}`
+ req := httptest.NewRequest(http.MethodPost, "/api/security/quick-setup", strings.NewReader(payload))
+ req.RemoteAddr = "198.51.100.17:54321"
+ req.Header.Set("X-API-Token", rawOldToken)
+ rec := httptest.NewRecorder()
+
+ handleQuickSecuritySetupFixed(router)(rec, req)
+
+ if rec.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusInternalServerError, rec.Body.String())
+ }
+ if len(cfg.APITokens) != 1 || cfg.APITokens[0].ID != oldToken.ID {
+ t.Fatalf("live token inventory changed after failed persistence: %+v", cfg.APITokens)
+ }
+ if cfg.APIToken != previousPrimaryToken {
+ t.Fatalf("legacy primary token = %q, want rollback to %q", cfg.APIToken, previousPrimaryToken)
+ }
+ if !internalauth.CompareAPIToken(rawOldToken, cfg.APITokens[0].Hash) {
+ t.Fatal("previous credential no longer authenticates after failed persistence")
+ }
+ if cfg.AuthUser != "newadmin" || !internalauth.CheckPasswordHash("NewPassword!1", cfg.AuthPass) {
+ t.Fatal("persisted password authentication was not applied to live state")
+ }
+ if strings.Contains(rec.Body.String(), newRawToken) {
+ t.Fatalf("failure response exposed API token: %q", rec.Body.String())
+ }
+
+ persisted, err := persistence.LoadAPITokens()
+ if err != nil {
+ t.Fatalf("load persisted tokens: %v", err)
+ }
+ if len(persisted) != 1 || persisted[0].ID != oldToken.ID {
+ t.Fatalf("persisted token inventory changed after failed write: %+v", persisted)
+ }
+}
+
func TestQuickSecuritySetupRateLimitEnforced(t *testing.T) {
t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")
resetTrustedProxyConfig()