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
Keep token migrations atomic
pulse-triage[bot]f58ff1addf12
diff --git a/internal/config/api_token_migration_atomic_test.go b/internal/config/api_token_migration_atomic_test.gonew file mode 100644index 0000000000..4db83a9a16--- /dev/null+++ b/internal/config/api_token_migration_atomic_test.go@@ -0,0 +1,113 @@+package config++import (+ "bytes"+ "encoding/json"+ "errors"+ "os"+ "sync/atomic"+ "testing"+ "time"++ "github.com/stretchr/testify/require"+)++func writeLegacyEncryptedAPITokens(t *testing.T, persistence *ConfigPersistence, tokens []APITokenRecord) []byte {+ t.Helper()++ data, err := json.Marshal(tokens)+ require.NoError(t, err)+ if persistence.crypto != nil {+ data, err = persistence.crypto.Encrypt(data)+ require.NoError(t, err)+ }+ require.NoError(t, os.WriteFile(persistence.apiTokensFile, data, 0o600))+ return data+}++func TestLoadAPITokensPersistsCanonicalAuthorizationStateBeforeReturning(t *testing.T) {+ persistence := NewConfigPersistence(t.TempDir())+ createdAt := time.Now().UTC().Add(-time.Hour)+ writeLegacyEncryptedAPITokens(t, persistence, []APITokenRecord{{+ Name: "legacy agent",+ Hash: "legacy-hash",+ CreatedAt: createdAt,+ Scopes: []string{"host-agent:report"},+ }})++ loaded, err := persistence.LoadAPITokens()+ require.NoError(t, err)+ require.Len(t, loaded, 1)+ require.NotEmpty(t, loaded[0].ID)+ require.Equal(t, []string{ScopeAgentReport}, loaded[0].Scopes)+ require.Equal(t, "default", loaded[0].OrgID)++ reloaded, err := persistence.LoadAPITokens()+ require.NoError(t, err)+ require.Len(t, reloaded, 1)+ require.Equal(t, loaded[0].ID, reloaded[0].ID, "the persisted revocation handle must be stable")+ require.Equal(t, loaded[0].Scopes, reloaded[0].Scopes)+ require.Equal(t, loaded[0].OrgID, reloaded[0].OrgID)+}++func TestLoadAPITokensRejectsUnpersistedCanonicalAuthorizationState(t *testing.T) {+ persistence := NewConfigPersistence(t.TempDir())+ original := writeLegacyEncryptedAPITokens(t, persistence, []APITokenRecord{{+ Name: "legacy agent",+ Hash: "legacy-hash",+ CreatedAt: time.Now().UTC().Add(-time.Hour),+ Scopes: []string{"host-agent:report"},+ }})+ persistence.SetFileSystem(&mockFSError{+ FileSystem: defaultFileSystem{},+ writeError: errors.New("forced migration write failure"),+ })++ loaded, err := persistence.LoadAPITokens()+ require.Error(t, err)+ require.Nil(t, loaded, "unpersisted authorization state must not be admitted")+ require.Contains(t, err.Error(), "persist canonical api tokens")++ after, readErr := os.ReadFile(persistence.apiTokensFile)+ require.NoError(t, readErr)+ require.True(t, bytes.Equal(original, after), "failed migration must leave the durable inventory unchanged")+}++func TestConfigWatcherPreservesLiveTokensWhenCanonicalMigrationCannotPersist(t *testing.T) {+ persistence := NewConfigPersistence(t.TempDir())+ writeLegacyEncryptedAPITokens(t, persistence, []APITokenRecord{{+ Name: "disk legacy token",+ Hash: "disk-hash",+ CreatedAt: time.Now().UTC().Add(-time.Hour),+ Scopes: []string{"host-agent:report"},+ }})+ persistence.SetFileSystem(&mockFSError{+ FileSystem: defaultFileSystem{},+ writeError: errors.New("forced migration write failure"),+ })++ live := APITokenRecord{+ ID: "live-token-id",+ Name: "live token",+ Hash: "live-hash",+ CreatedAt: time.Now().UTC(),+ Scopes: []string{ScopeWildcard},+ OrgID: "default",+ }+ cfg := &Config{APITokens: []APITokenRecord{live}}+ cfg.SortAPITokens()+ cw := &ConfigWatcher{+ config: cfg,+ apiTokensPath: persistence.apiTokensFile,+ persistence: persistence,+ stopChan: make(chan struct{}),+ }+ var callbackCalled atomic.Bool+ cw.SetAPITokenReloadCallback(func() { callbackCalled.Store(true) })++ cw.reloadAPITokens()++ require.Equal(t, []APITokenRecord{live}, cfg.APITokens)+ require.Equal(t, live.Hash, cfg.APIToken)+ require.False(t, callbackCalled.Load(), "failed reload must not advertise a credential change")+}diff --git a/internal/config/api_tokens.go b/internal/config/api_tokens.goindex 4b84f06ef0..a8fbd23fed 100644--- a/internal/config/api_tokens.go+++ b/internal/config/api_tokens.go@@ -2,6 +2,7 @@ package configimport ("errors"+ "slices""sort""strings""time"@@ -235,6 +236,35 @@ func bindMissingAPITokenIDs(tokens []APITokenRecord) int {return migrated}+type apiTokenMigrationSummary struct {+ missingIDs int+ legacyScopes int+ legacyOrgBindings int+}++func (s apiTokenMigrationSummary) changed() bool {+ return s.missingIDs > 0 || s.legacyScopes > 0 || s.legacyOrgBindings > 0+}++// canonicalizeAPITokens applies every migration required before token records+// are safe to admit to live configuration. Callers must persist the resulting+// inventory successfully before using it: IDs are revocation handles, scopes+// are authorization state, and organization bindings constrain tenancy.+func canonicalizeAPITokens(tokens []APITokenRecord) apiTokenMigrationSummary {+ summary := apiTokenMigrationSummary{+ missingIDs: bindMissingAPITokenIDs(tokens),+ legacyOrgBindings: bindLegacyAPITokensToDefault(tokens),+ }+ for i := range tokens {+ normalizedScopes := normalizeScopes(tokens[i].Scopes)+ if !slices.Equal(tokens[i].Scopes, normalizedScopes) {+ summary.legacyScopes+++ }+ tokens[i].Scopes = normalizedScopes+ }+ return summary+}+// tokenPrefix returns the first six characters suitable for hints.func tokenPrefix(value string) string {if len(value) >= 6 {diff --git a/internal/config/config.go b/internal/config/config.goindex 1c91a01eb2..9f15998749 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -989,28 +989,16 @@ func load(initLogging bool) (*Config, error) {}- // Load API tokens- if tokens, err := persistence.LoadAPITokens(); err == nil {- if migrated := bindMissingAPITokenIDs(tokens); migrated > 0 {- if err := persistence.SaveAPITokens(tokens); err != nil {- log.Error().Err(err).Int("count", migrated).Msg("Failed to persist API token ID migration")- } else {- log.Warn().Int("count", migrated).Msg("Migrated API tokens missing IDs")- }- }- if migrated := bindLegacyAPITokensToDefault(tokens); migrated > 0 {- if err := persistence.SaveAPITokens(tokens); err != nil {- log.Error().Err(err).Int("count", migrated).Msg("Failed to persist legacy API token org binding migration")- } else {- log.Warn().Int("count", migrated).Msg("Migrated legacy API tokens to default organization binding")- }- }- cfg.APITokens = tokens- cfg.SortAPITokens()- log.Info().Int("count", len(tokens)).Msg("Loaded API tokens from persistence")- } else {- log.Warn().Err(err).Msg("Failed to load API tokens from persistence")+ // API tokens are an authentication boundary. Starting with an unreadable or+ // unpersistable token inventory would silently turn token-only mode into an+ // unconfigured runtime. Fail startup/reload instead of weakening auth.+ tokens, err := persistence.LoadAPITokens()+ if err != nil {+ return nil, fmt.Errorf("load API tokens: %w", err)}+ cfg.APITokens = tokens+ cfg.SortAPITokens()+ log.Info().Int("count", len(tokens)).Msg("Loaded API tokens from persistence")// Ensure polling intervals have sane defaults if not setif cfg.PVEPollingInterval <= 0 {diff --git a/internal/config/config_load_extra_test.go b/internal/config/config_load_extra_test.goindex 553e162e35..25245385bc 100644--- a/internal/config/config_load_extra_test.go+++ b/internal/config/config_load_extra_test.go@@ -79,10 +79,12 @@ func TestLoad_Errors(t *testing.T) {tokensPath := filepath.Join(tempDir, "api_tokens.json")require.NoError(t, os.WriteFile(tokensPath, []byte("{invalid}"), 0644))- // Load should still proceed with defaults and log warnings+ // Non-credential files retain their recovery behavior, but a corrupted API+ // token inventory must stop startup rather than silently disable token auth.cfg, err := Load()- assert.NoError(t, err)- assert.NotNil(t, cfg)+ require.Error(t, err)+ assert.Nil(t, cfg)+ assert.Contains(t, err.Error(), "load API tokens")}func TestLoad_MockEnvErrors(t *testing.T) {diff --git a/internal/config/persistence.go b/internal/config/persistence.goindex 7a1e2d85f8..92aa33496d 100644--- a/internal/config/persistence.go+++ b/internal/config/persistence.go@@ -699,15 +699,17 @@ func (c *ConfigPersistence) LoadAPITokens() ([]APITokenRecord, error) {return nil, fmt.Errorf("decode api tokens file %s: %w", c.apiTokensFile, err)}- for i := range tokens {- tokens[i].ensureID()- tokens[i].ensureScopes()- }-- if migratedPlaintext && c.crypto != nil {+ migrations := canonicalizeAPITokens(tokens)+ if migratedPlaintext || migrations.changed() {if err := c.persistAPITokensLocked(tokens); err != nil {- return nil, fmt.Errorf("rewrite plaintext api tokens file %s: %w", c.apiTokensFile, err)+ return nil, fmt.Errorf("persist canonical api tokens file %s: %w", c.apiTokensFile, err)}+ log.Warn().+ Bool("encrypted_plaintext", migratedPlaintext && c.crypto != nil).+ Int("missing_ids", migrations.missingIDs).+ Int("legacy_scopes", migrations.legacyScopes).+ Int("legacy_org_bindings", migrations.legacyOrgBindings).+ Msg("Migrated API token metadata before loading")}return tokens, nildiff --git a/internal/config/persistence_test.go b/internal/config/persistence_test.goindex aff547e226..21ef33a6b2 100644--- a/internal/config/persistence_test.go+++ b/internal/config/persistence_test.go@@ -547,6 +547,7 @@ func TestExportConfigIncludesAPITokens(t *testing.T) {Suffix: "-0001",CreatedAt: createdAt,Scopes: []string{config.ScopeWildcard},+ OrgID: "default",},{ID: "token-2",@@ -556,6 +557,7 @@ func TestExportConfigIncludesAPITokens(t *testing.T) {Suffix: "-0002",CreatedAt: createdAt.Add(time.Hour),Scopes: []string{config.ScopeMonitoringRead},+ OrgID: "default",},}@@ -1053,6 +1055,7 @@ func TestImportAcceptsVersion40Bundle(t *testing.T) {Suffix: "-k",CreatedAt: time.Date(2022, 4, 4, 12, 0, 0, 0, time.UTC),Scopes: []string{config.ScopeWildcard},+ OrgID: "default",},}if err := target.SaveAPITokens(baselineTokens); err != nil {diff --git a/internal/config/watcher.go b/internal/config/watcher.goindex 39176e5e14..3d3add52a4 100644--- a/internal/config/watcher.go+++ b/internal/config/watcher.go@@ -559,33 +559,8 @@ func (cw *ConfigWatcher) reloadAPITokens() {return}- persistMutations := false- if migrated := bindMissingAPITokenIDs(tokens); migrated > 0 {- persistMutations = true- log.Warn().- Int("count", migrated).- Str("api_tokens_path", cw.apiTokensPath).- Msg("Migrated API tokens missing IDs during reload")- }-- if migrated := bindLegacyAPITokensToDefault(tokens); migrated > 0 {- persistMutations = true- log.Warn().- Int("count", migrated).- Str("api_tokens_path", cw.apiTokensPath).- Msg("Migrated legacy API tokens to default organization binding during reload")- }-- if persistMutations {- if err := cw.persistence.SaveAPITokens(tokens); err != nil {- log.Error().- Err(err).- Str("api_tokens_path", cw.apiTokensPath).- Msg("Failed to persist API token migrations during reload")- }- }-- // Only update if we successfully loaded tokens.+ // LoadAPITokens persists every authorization-relevant migration before it+ // returns. Only a durable canonical inventory may replace live credentials.cw.config.APITokens = tokenscw.config.SortAPITokens()