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 API token watcher mutations ordered

pulse-triage[bot]b8d3a768bd21
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index dca1d33214..9e78d37550 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -22,6 +22,11 @@ API-token rename is an authenticated token-management mutation: blank labels
fail closed, successful changes are persisted and audited as `token_renamed`,
and neither the plaintext credential nor its stored hash is exposed or
rotated. Rename UI copy must state that connected agents remain unchanged.
+Live token-file reloads must serialize their disk snapshot with in-process
+rename, scope-update, rotate, create, and revoke mutations under `config.Mu`.
+An older watcher snapshot may never overwrite newer runtime and durable token
+state; `TestConfigWatcher_ReloadAPITokensDoesNotOverwriteConcurrentMutation`
+is the required concurrency proof.
Own Pulse's canonical privacy disclosures, outbound usage-data boundary,
and the security-facing settings surfaces that expose authentication posture,
@@ -1509,6 +1514,12 @@ legacy plaintext metadata file may only serve as migration input. Canonical
runtime persistence must rewrite plaintext API token metadata immediately into
encrypted-at-rest storage on load instead of continuing to run against the
unencrypted file as a normal primary path.
+Live `api_tokens.json` reloads and in-process token mutations share that same
+inventory authority. `internal/config/watcher.go` must serialize reading and
+applying a disk snapshot with rename, scope-update, rotate, create, and revoke
+mutations under `config.Mu`; an older snapshot may not be applied after a newer
+mutation has updated runtime state and durable storage. The concurrency proof
+is `TestConfigWatcher_ReloadAPITokensDoesNotOverwriteConcurrentMutation`.
That same trust boundary also governs API token scope identity: legacy
`host-agent:*` scopes may be accepted only at request-ingress or persistence/
migration boundaries, where they must be rewritten immediately into canonical
diff --git a/internal/config/watcher.go b/internal/config/watcher.go
index 802aa878ed..39176e5e14 100644
--- a/internal/config/watcher.go
+++ b/internal/config/watcher.go
@@ -510,6 +510,14 @@ func (cw *ConfigWatcher) reloadAPITokens() {
return
}
+ // Serialize the disk snapshot with every in-process API-token mutation.
+ // Without this lock a reload can read the old file, wait behind a rename or
+ // revoke that writes the new file, and then replace the newer runtime
+ // inventory with its stale snapshot. The final stat below would also record
+ // the new file's timestamp, leaving polling unable to repair the rollback.
+ Mu.Lock()
+ defer Mu.Unlock()
+
// Preserve existing tokens in case reload fails
existingTokens := cw.config.APITokens
existingCount := len(existingTokens)
@@ -577,11 +585,9 @@ func (cw *ConfigWatcher) reloadAPITokens() {
}
}
- // Only update if we successfully loaded tokens
- Mu.Lock()
+ // Only update if we successfully loaded tokens.
cw.config.APITokens = tokens
cw.config.SortAPITokens()
- Mu.Unlock()
if cw.apiTokensPath != "" {
if stat, err := os.Stat(cw.apiTokensPath); err == nil {
diff --git a/internal/config/watcher_test.go b/internal/config/watcher_test.go
index 7dd388055d..a8861adfcf 100644
--- a/internal/config/watcher_test.go
+++ b/internal/config/watcher_test.go
@@ -4,6 +4,7 @@ import (
"errors"
"os"
"path/filepath"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -12,6 +13,23 @@ import (
"github.com/stretchr/testify/require"
)
+type blockingTokenReadFileSystem struct {
+ FileSystem
+ target string
+ readStarted chan struct{}
+ releaseRead chan struct{}
+ once sync.Once
+}
+
+func (fs *blockingTokenReadFileSystem) ReadFile(name string) ([]byte, error) {
+ data, err := fs.FileSystem.ReadFile(name)
+ if name == fs.target {
+ fs.once.Do(func() { close(fs.readStarted) })
+ <-fs.releaseRead
+ }
+ return data, err
+}
+
func TestNewConfigWatcher_DirectoryPriority(t *testing.T) {
tempDir := t.TempDir()
dir1 := filepath.Join(tempDir, "dir1")
@@ -243,6 +261,101 @@ func TestConfigWatcher_ReloadAPITokens(t *testing.T) {
require.Eventually(t, func() bool { return callbackCalled.Load() }, 1*time.Second, 10*time.Millisecond)
}
+func TestConfigWatcher_ReloadAPITokensDoesNotOverwriteConcurrentMutation(t *testing.T) {
+ oldTokens := []APITokenRecord{{
+ ID: "token-1",
+ Name: "Old name",
+ Hash: "hash-1",
+ Scopes: []string{ScopeWildcard},
+ OrgID: "default",
+ CreatedAt: time.Now().UTC(),
+ }}
+
+ for _, tt := range []struct {
+ name string
+ newTokens []APITokenRecord
+ }{
+ {
+ name: "rename",
+ newTokens: []APITokenRecord{{
+ ID: "token-1",
+ Name: "Renamed token",
+ Hash: "hash-1",
+ Scopes: []string{ScopeWildcard},
+ OrgID: "default",
+ CreatedAt: oldTokens[0].CreatedAt,
+ }},
+ },
+ {name: "revoke", newTokens: []APITokenRecord{}},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ tempDir := t.TempDir()
+ watcherPersistence := NewConfigPersistence(tempDir)
+ require.NoError(t, watcherPersistence.SaveAPITokens(oldTokens))
+ writerPersistence := NewConfigPersistence(tempDir)
+ cfg := &Config{APITokens: append([]APITokenRecord(nil), oldTokens...)}
+ readFS := &blockingTokenReadFileSystem{
+ FileSystem: watcherPersistence.fs,
+ target: watcherPersistence.apiTokensFile,
+ readStarted: make(chan struct{}),
+ releaseRead: make(chan struct{}),
+ }
+ watcherPersistence.fs = readFS
+ cw := &ConfigWatcher{
+ config: cfg,
+ apiTokensPath: watcherPersistence.apiTokensFile,
+ persistence: watcherPersistence,
+ stopChan: make(chan struct{}),
+ }
+
+ reloadDone := make(chan struct{})
+ go func() {
+ cw.reloadAPITokens()
+ close(reloadDone)
+ }()
+ <-readFS.readStarted
+
+ writerLocked := make(chan struct{})
+ writerDone := make(chan error, 1)
+ go func() {
+ Mu.Lock()
+ close(writerLocked)
+ cfg.APITokens = append([]APITokenRecord(nil), tt.newTokens...)
+ err := writerPersistence.SaveAPITokens(cfg.APITokens)
+ Mu.Unlock()
+ writerDone <- err
+ }()
+
+ // On the regressed implementation the writer acquires Mu while the watcher
+ // is holding an old disk snapshot. On the fixed implementation it remains
+ // queued until that snapshot has been applied, so its newer mutation wins.
+ select {
+ case <-writerLocked:
+ case <-time.After(100 * time.Millisecond):
+ }
+ close(readFS.releaseRead)
+
+ require.NoError(t, <-writerDone)
+ <-reloadDone
+
+ Mu.RLock()
+ runtimeTokens := append([]APITokenRecord(nil), cfg.APITokens...)
+ Mu.RUnlock()
+ require.Len(t, runtimeTokens, len(tt.newTokens))
+ if len(tt.newTokens) > 0 {
+ assert.Equal(t, tt.newTokens, runtimeTokens)
+ }
+
+ persisted, err := writerPersistence.LoadAPITokens()
+ require.NoError(t, err)
+ require.Len(t, persisted, len(tt.newTokens))
+ if len(tt.newTokens) > 0 {
+ assert.Equal(t, tt.newTokens, persisted)
+ }
+ })
+ }
+}
+
func TestConfigWatcher_CalculateFileHash_Error(t *testing.T) {
cw := &ConfigWatcher{}
_, err := cw.calculateFileHash("/non/existent/file")