Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix: Prevent re-migration of deleted env-based API tokens

rcourtmancb3444dd9b12
diff --git a/internal/api/security_tokens.go b/internal/api/security_tokens.go
index 1d4009d37a..55a5c48bb0 100644
--- a/internal/api/security_tokens.go
+++ b/internal/api/security_tokens.go
@@ -187,11 +187,21 @@ func (r *Router) handleDeleteAPIToken(w http.ResponseWriter, req *http.Request)
defer config.Mu.Unlock()
removed := r.config.RemoveAPIToken(id)
- if !removed {
+ if removed == nil {
http.Error(w, "Token not found", http.StatusNotFound)
return
}
+ // If this was a migrated env token, suppress re-migration on restart
+ if strings.HasPrefix(removed.Name, "Migrated from .env") {
+ r.config.SuppressEnvMigration(removed.Hash)
+ if r.persistence != nil {
+ if err := r.persistence.SaveEnvTokenSuppressions(r.config.SuppressedEnvMigrations); err != nil {
+ log.Warn().Err(err).Msg("Failed to persist env token suppression list")
+ }
+ }
+ }
+
r.config.SortAPITokens()
r.config.APITokenEnabled = r.config.HasAPITokens()
diff --git a/internal/config/api_tokens.go b/internal/config/api_tokens.go
index c5b8539740..3cb7d6c57a 100644
--- a/internal/config/api_tokens.go
+++ b/internal/config/api_tokens.go
@@ -171,6 +171,25 @@ func (c *Config) HasAPITokenHash(hash string) bool {
return false
}
+// IsEnvMigrationSuppressed returns true if the given hash was a migrated env token
+// that the user explicitly deleted (and should not be re-migrated on restart).
+func (c *Config) IsEnvMigrationSuppressed(hash string) bool {
+ for _, h := range c.SuppressedEnvMigrations {
+ if h == hash {
+ return true
+ }
+ }
+ return false
+}
+
+// SuppressEnvMigration adds a hash to the suppression list to prevent re-migration.
+func (c *Config) SuppressEnvMigration(hash string) {
+ if c.IsEnvMigrationSuppressed(hash) {
+ return
+ }
+ c.SuppressedEnvMigrations = append(c.SuppressedEnvMigrations, hash)
+}
+
// PrimaryAPITokenHash returns the newest token hash, if any.
func (c *Config) PrimaryAPITokenHash() string {
if len(c.APITokens) == 0 {
@@ -225,15 +244,16 @@ func (c *Config) UpsertAPIToken(record APITokenRecord) {
c.SortAPITokens()
}
-// RemoveAPIToken removes a token by ID.
-func (c *Config) RemoveAPIToken(id string) bool {
+// RemoveAPIToken removes a token by ID and returns the removed record (if any).
+func (c *Config) RemoveAPIToken(id string) *APITokenRecord {
for idx, record := range c.APITokens {
if record.ID == id {
+ removed := record
c.APITokens = append(c.APITokens[:idx], c.APITokens[idx+1:]...)
- return true
+ return &removed
}
}
- return false
+ return nil
}
// SortAPITokens keeps tokens ordered newest-first and syncs the legacy APIToken field.
diff --git a/internal/config/api_tokens_test.go b/internal/config/api_tokens_test.go
index 8b94b70158..dcd352f213 100644
--- a/internal/config/api_tokens_test.go
+++ b/internal/config/api_tokens_test.go
@@ -905,7 +905,7 @@ func TestUpsertAPIToken(t *testing.T) {
}
func TestRemoveAPIToken(t *testing.T) {
- t.Run("remove existing returns true", func(t *testing.T) {
+ t.Run("remove existing returns record", func(t *testing.T) {
cfg := &Config{
APITokens: []APITokenRecord{
{ID: "keep", Hash: "hash1"},
@@ -915,8 +915,11 @@ func TestRemoveAPIToken(t *testing.T) {
}
removed := cfg.RemoveAPIToken("remove")
- if !removed {
- t.Error("expected true when removing existing token")
+ if removed == nil {
+ t.Error("expected record when removing existing token")
+ }
+ if removed.ID != "remove" || removed.Hash != "hash2" {
+ t.Errorf("unexpected removed record: %+v", removed)
}
if len(cfg.APITokens) != 2 {
t.Fatalf("expected 2 tokens remaining, got %d", len(cfg.APITokens))
@@ -929,7 +932,7 @@ func TestRemoveAPIToken(t *testing.T) {
}
})
- t.Run("remove non-existing returns false", func(t *testing.T) {
+ t.Run("remove non-existing returns nil", func(t *testing.T) {
cfg := &Config{
APITokens: []APITokenRecord{
{ID: "existing", Hash: "hash1"},
@@ -937,19 +940,69 @@ func TestRemoveAPIToken(t *testing.T) {
}
removed := cfg.RemoveAPIToken("nonexistent")
- if removed {
- t.Error("expected false when removing nonexistent token")
+ if removed != nil {
+ t.Error("expected nil when removing nonexistent token")
}
if len(cfg.APITokens) != 1 {
t.Errorf("token count should be unchanged, got %d", len(cfg.APITokens))
}
})
- t.Run("remove from empty returns false", func(t *testing.T) {
+ t.Run("remove from empty returns nil", func(t *testing.T) {
cfg := &Config{}
removed := cfg.RemoveAPIToken("any")
- if removed {
- t.Error("expected false when removing from empty config")
+ if removed != nil {
+ t.Error("expected nil when removing from empty config")
+ }
+ })
+}
+
+func TestEnvMigrationSuppression(t *testing.T) {
+ t.Run("IsEnvMigrationSuppressed returns false for empty list", func(t *testing.T) {
+ cfg := &Config{}
+ if cfg.IsEnvMigrationSuppressed("any-hash") {
+ t.Error("expected false for empty suppression list")
+ }
+ })
+
+ t.Run("IsEnvMigrationSuppressed returns true for suppressed hash", func(t *testing.T) {
+ cfg := &Config{
+ SuppressedEnvMigrations: []string{"hash1", "hash2"},
+ }
+ if !cfg.IsEnvMigrationSuppressed("hash1") {
+ t.Error("expected true for suppressed hash")
+ }
+ if !cfg.IsEnvMigrationSuppressed("hash2") {
+ t.Error("expected true for suppressed hash")
+ }
+ })
+
+ t.Run("IsEnvMigrationSuppressed returns false for non-suppressed hash", func(t *testing.T) {
+ cfg := &Config{
+ SuppressedEnvMigrations: []string{"hash1", "hash2"},
+ }
+ if cfg.IsEnvMigrationSuppressed("hash3") {
+ t.Error("expected false for non-suppressed hash")
+ }
+ })
+
+ t.Run("SuppressEnvMigration adds new hash", func(t *testing.T) {
+ cfg := &Config{}
+ cfg.SuppressEnvMigration("hash1")
+ if len(cfg.SuppressedEnvMigrations) != 1 {
+ t.Errorf("expected 1 suppressed hash, got %d", len(cfg.SuppressedEnvMigrations))
+ }
+ if !cfg.IsEnvMigrationSuppressed("hash1") {
+ t.Error("hash1 should be suppressed")
+ }
+ })
+
+ t.Run("SuppressEnvMigration is idempotent", func(t *testing.T) {
+ cfg := &Config{}
+ cfg.SuppressEnvMigration("hash1")
+ cfg.SuppressEnvMigration("hash1")
+ if len(cfg.SuppressedEnvMigrations) != 1 {
+ t.Errorf("expected 1 suppressed hash after duplicate add, got %d", len(cfg.SuppressedEnvMigrations))
}
})
}
diff --git a/internal/config/config.go b/internal/config/config.go
index a54da55f50..79f82aeb40 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -129,9 +129,10 @@ type Config struct {
LogCompress bool `envconfig:"LOG_COMPRESS" default:"true"`
// Security settings
- APIToken string `envconfig:"API_TOKEN"`
- APITokenEnabled bool `envconfig:"API_TOKEN_ENABLED" default:"false"`
- APITokens []APITokenRecord `json:"-"`
+ APIToken string `envconfig:"API_TOKEN"`
+ APITokenEnabled bool `envconfig:"API_TOKEN_ENABLED" default:"false"`
+ APITokens []APITokenRecord `json:"-"`
+ SuppressedEnvMigrations []string `json:"-"` // Hashes of env tokens deleted by user (prevent re-migration)
AuthUser string `envconfig:"PULSE_AUTH_USER"`
AuthPass string `envconfig:"PULSE_AUTH_PASS"`
DisableAuthEnvDetected bool `json:"-"`
@@ -735,6 +736,16 @@ func Load() (*Config, error) {
log.Warn().Err(err).Msg("Failed to load API tokens from persistence")
}
+ // Load suppressed env token migrations (tokens user deleted that came from .env)
+ if suppressions, err := persistence.LoadEnvTokenSuppressions(); err == nil {
+ cfg.SuppressedEnvMigrations = suppressions
+ if len(suppressions) > 0 {
+ log.Debug().Int("count", len(suppressions)).Msg("Loaded env token suppression list")
+ }
+ } else {
+ log.Warn().Err(err).Msg("Failed to load env token suppressions")
+ }
+
// Ensure polling intervals have sane defaults if not set
if cfg.PVEPollingInterval <= 0 {
cfg.PVEPollingInterval = 10 * time.Second
@@ -1041,6 +1052,11 @@ func Load() (*Config, error) {
continue
}
+ // Check if user previously deleted this migrated token (prevent re-migration)
+ if cfg.IsEnvMigrationSuppressed(hashed) {
+ continue
+ }
+
// Migrate env token to api_tokens.json
record := APITokenRecord{
ID: uuid.NewString(),
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index ed4f65c193..39313ac0e0 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -30,8 +30,9 @@ type ConfigPersistence struct {
nodesFile string
systemFile string
oidcFile string
- apiTokensFile string
- aiFile string
+ apiTokensFile string
+ envTokenSuppressionsFile string
+ aiFile string
aiFindingsFile string
aiPatrolRunsFile string
aiUsageHistoryFile string
@@ -76,8 +77,9 @@ func newConfigPersistence(configDir string) (*ConfigPersistence, error) {
nodesFile: filepath.Join(configDir, "nodes.enc"),
systemFile: filepath.Join(configDir, "system.json"),
oidcFile: filepath.Join(configDir, "oidc.enc"),
- apiTokensFile: filepath.Join(configDir, "api_tokens.json"),
- aiFile: filepath.Join(configDir, "ai.enc"),
+ apiTokensFile: filepath.Join(configDir, "api_tokens.json"),
+ envTokenSuppressionsFile: filepath.Join(configDir, "env_token_suppressions.json"),
+ aiFile: filepath.Join(configDir, "ai.enc"),
aiFindingsFile: filepath.Join(configDir, "ai_findings.json"),
aiPatrolRunsFile: filepath.Join(configDir, "ai_patrol_runs.json"),
aiUsageHistoryFile: filepath.Join(configDir, "ai_usage_history.json"),
@@ -169,6 +171,48 @@ func (c *ConfigPersistence) LoadAPITokens() ([]APITokenRecord, error) {
return tokens, nil
}
+// LoadEnvTokenSuppressions loads the list of suppressed env token hashes.
+func (c *ConfigPersistence) LoadEnvTokenSuppressions() ([]string, error) {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+
+ data, err := os.ReadFile(c.envTokenSuppressionsFile)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return []string{}, nil
+ }
+ return nil, err
+ }
+
+ if len(data) == 0 {
+ return []string{}, nil
+ }
+
+ var hashes []string
+ if err := json.Unmarshal(data, &hashes); err != nil {
+ return nil, err
+ }
+
+ return hashes, nil
+}
+
+// SaveEnvTokenSuppressions persists the suppressed env token hashes to disk.
+func (c *ConfigPersistence) SaveEnvTokenSuppressions(hashes []string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if err := c.EnsureConfigDir(); err != nil {
+ return err
+ }
+
+ data, err := json.Marshal(hashes)
+ if err != nil {
+ return err
+ }
+
+ return c.writeConfigFileLocked(c.envTokenSuppressionsFile, data, 0600)
+}
+
// SaveAPITokens persists API token metadata to disk.
func (c *ConfigPersistence) SaveAPITokens(tokens []APITokenRecord) error {
c.mu.Lock()
diff --git a/internal/monitoring/kubernetes_agents.go b/internal/monitoring/kubernetes_agents.go
index 2ecb36293c..381a0ada41 100644
--- a/internal/monitoring/kubernetes_agents.go
+++ b/internal/monitoring/kubernetes_agents.go
@@ -239,7 +239,7 @@ func (m *Monitor) RemoveKubernetesCluster(clusterID string) (models.KubernetesCl
// Revoke the API token associated with this Kubernetes cluster
if cluster.TokenID != "" {
tokenRemoved := m.config.RemoveAPIToken(cluster.TokenID)
- if tokenRemoved {
+ if tokenRemoved != nil {
m.config.SortAPITokens()
m.config.APITokenEnabled = m.config.HasAPITokens()
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index ecdd7f51ca..efcc98660c 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -1057,7 +1057,7 @@ func (m *Monitor) RemoveDockerHost(hostID string) (models.DockerHost, error) {
// Revoke the API token associated with this Docker host
if host.TokenID != "" {
tokenRemoved := m.config.RemoveAPIToken(host.TokenID)
- if tokenRemoved {
+ if tokenRemoved != nil {
m.config.SortAPITokens()
m.config.APITokenEnabled = m.config.HasAPITokens()
@@ -1151,10 +1151,10 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
}
}
- tokenRevoked := false
+ var tokenRemoved *config.APITokenRecord
if tokenID != "" && !tokenStillUsed {
- tokenRevoked = m.config.RemoveAPIToken(tokenID)
- if tokenRevoked {
+ tokenRemoved = m.config.RemoveAPIToken(tokenID)
+ if tokenRemoved != nil {
m.config.SortAPITokens()
m.config.APITokenEnabled = m.config.HasAPITokens()
@@ -1190,7 +1190,7 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
}
}
- if tokenRevoked {
+ if tokenRemoved != nil {
prefix := tokenID + ":"
for key := range m.hostTokenBindings {
if strings.HasPrefix(key, prefix) {
@@ -1203,7 +1203,7 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
log.Debug().
Str("tokenID", tokenID).
Str("hostID", hostID).
- Bool("revoked", tokenRevoked).
+ Bool("revoked", tokenRemoved != nil).
Msg("Unbound host agent token bindings after host removal")
}