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 bootstrap persistence off stale temporary paths

pulse-triage[bot]0f786322f940
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 9fd849c60c..1f6c457037 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -2901,6 +2901,23 @@ plaintext secret file on disk. Canonical runtime persistence must keep the
token encrypted at rest, and any legacy plaintext bootstrap-token file must be
treated only as migration input that is rewritten immediately into the
encrypted canonical format on load.
+Bootstrap ciphertext persistence uses the existing secure storage writer's
+exclusive, uniquely named owner-only temporary file in the resolved data
+directory, followed by rename. It must not open, truncate or remove a stale
+`.bootstrap_token.tmp` file, link or directory, or inherit that path's modes.
+Successful direct writes and legacy migration preserve the existing encryption
+key and unrelated files; failed replacement cleans up only the writer's own
+temporary file and returns an error. Concurrent writes with an established key
+remain complete records, not a shared-temporary-file collision. The encrypted
+format, token hash, creation timestamp, local reveal command, initial key
+creation and first-run authentication contract are unchanged.
+`internal/bootstrap/token_store_atomic_test.go` covers stale regular files,
+symlinks, hardlinks and directories through both persistence and migration,
+failed replacement/state preservation, private final modes and independent
+concurrent writes. The ordinary API bootstrap tests retain actual creation,
+reload, rejection and setup validation; a stale temporary directory is not an
+authoritative failure injection. This is local filesystem safety, not evidence
+of installed exposure or a change to rendered setup fields or policy.
Operator guidance for recovering that token, in the startup log and on the
first-run unlock screen, must name the supported command and never the token
file, because the file holds ciphertext. The unlock screen lists the host,
diff --git a/internal/api/bootstrap_token_test.go b/internal/api/bootstrap_token_test.go
index 8ac7920ddb..06f4589254 100644
--- a/internal/api/bootstrap_token_test.go
+++ b/internal/api/bootstrap_token_test.go
@@ -80,7 +80,7 @@ func TestLoadOrCreateBootstrapToken_MkdirAllFailure(t *testing.T) {
}
}
-func TestLoadOrCreateBootstrapToken_WriteFileFailure(t *testing.T) {
+func TestLoadOrCreateBootstrapToken_IgnoresStaleTemporaryDirectory(t *testing.T) {
tmpDir := t.TempDir()
tmpFileBlocker := filepath.Join(tmpDir, bootstrapTokenFilename+".tmp")
if err := os.MkdirAll(tmpFileBlocker, 0o700); err != nil {
@@ -88,20 +88,23 @@ func TestLoadOrCreateBootstrapToken_WriteFileFailure(t *testing.T) {
}
token, created, fullPath, err := loadOrCreateBootstrapToken(tmpDir)
- if err == nil {
- t.Error("expected error when WriteFile fails, got nil")
+ if err != nil {
+ t.Fatalf("stale temporary directory must not block token creation: %v", err)
}
- if token != "" {
- t.Errorf("expected empty token, got %q", token)
+ if token == "" || !created {
+ t.Fatal("expected a newly created token")
}
- if created {
- t.Error("expected created=false")
+ if info, err := os.Stat(tmpFileBlocker); err != nil || !info.IsDir() {
+ t.Fatalf("stale directory was changed: %v", err)
}
- // fullPath should be set even on write failure (path was computed before write)
expectedPath := filepath.Join(tmpDir, bootstrapTokenFilename)
if fullPath != expectedPath {
t.Errorf("expected fullPath=%q, got %q", expectedPath, fullPath)
}
+ loaded, loadedPath, migrated, err := bootstrap.Load(tmpDir)
+ if err != nil || loaded != token || loadedPath != fullPath || migrated {
+ t.Fatalf("new encrypted token cannot be reloaded: migrated=%t path=%q error=%v", migrated, loadedPath, err)
+ }
}
func TestLoadOrCreateBootstrapToken_EmptyFileContents(t *testing.T) {
diff --git a/internal/bootstrap/token_store.go b/internal/bootstrap/token_store.go
index 0304eb0e22..a70dedb282 100644
--- a/internal/bootstrap/token_store.go
+++ b/internal/bootstrap/token_store.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/crypto"
+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
@@ -121,17 +122,11 @@ func Persist(dataPath, token string, createdAt time.Time) (string, error) {
return path, fmt.Errorf("marshal bootstrap token: %w", err)
}
- tmpFile := path + ".tmp"
- if err := os.WriteFile(tmpFile, data, 0o600); err != nil {
+ // Reuse the private writer used for the encryption key: a unique, exclusive
+ // temporary file cannot follow a stale link or inherit its permissions.
+ if err := securityutil.WriteSecureStorageFile(path, data, 0o700, 0o600); err != nil {
return path, fmt.Errorf("persist bootstrap token: %w", err)
}
- if err := os.Rename(tmpFile, path); err != nil {
- _ = os.Remove(tmpFile)
- return path, fmt.Errorf("persist bootstrap token: %w", err)
- }
- if err := os.Chmod(path, 0o600); err != nil {
- return path, fmt.Errorf("harden bootstrap token file: %w", err)
- }
return path, nil
}
diff --git a/internal/bootstrap/token_store_atomic_test.go b/internal/bootstrap/token_store_atomic_test.go
new file mode 100644
index 0000000000..b3cae1fbc8
--- /dev/null
+++ b/internal/bootstrap/token_store_atomic_test.go
@@ -0,0 +1,201 @@
+package bootstrap
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sync"
+ "testing"
+ "time"
+)
+
+// These paths and credentials belong only to each test's temporary directory.
+// A stale predictable temp path must not be a write target, even during legacy
+// migration, and must not lend its permissions to the new canonical record.
+func TestPersistProtectsStaleTemporaryPaths(t *testing.T) {
+ for _, migrate := range []bool{false, true} {
+ for _, kind := range []string{"regular", "symlink", "hardlink", "directory"} {
+ t.Run(fmt.Sprintf("migration_%t/%s", migrate, kind), func(t *testing.T) {
+ root := t.TempDir()
+ dir := filepath.Join(root, "data")
+ path, err := Persist(dir, "initial-synthetic-setup-token", time.Unix(1700000000, 0))
+ if err != nil {
+ t.Fatal(err)
+ }
+ keyPath := filepath.Join(dir, ".encryption.key")
+ keyBefore, err := os.ReadFile(keyPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ unrelated := filepath.Join(root, "unrelated-state")
+ const untouched = "unrelated state must remain intact"
+ if err := os.WriteFile(unrelated, []byte(untouched), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ stale := path + ".tmp"
+ switch kind {
+ case "regular":
+ err = os.WriteFile(stale, []byte(untouched), 0o600)
+ if err == nil {
+ err = os.Chmod(stale, 0o666)
+ }
+ case "symlink":
+ err = os.Symlink(unrelated, stale)
+ case "hardlink":
+ err = os.Link(unrelated, stale)
+ case "directory":
+ err = os.Mkdir(stale, 0o700)
+ }
+ if err != nil {
+ if runtime.GOOS == "windows" && (kind == "symlink" || kind == "hardlink") {
+ t.Skipf("test filesystem cannot create %s: %v", kind, err)
+ }
+ t.Fatal(err)
+ }
+ staleInfo, err := os.Lstat(stale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const token = "replacement-synthetic-setup-token"
+ createdAt := time.Unix(1700000100, 0).UTC()
+ if migrate {
+ if err := os.WriteFile(path, []byte(token+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ loaded, gotPath, migrated, err := Load(dir)
+ if err != nil || !migrated || gotPath != path || loaded != token {
+ t.Fatalf("legacy migration did not preserve the setup token: migrated=%t path=%q error=%v", migrated, gotPath, err)
+ }
+ } else if gotPath, err := Persist(dir, token, createdAt); err != nil || gotPath != path {
+ t.Fatalf("Persist() path=%q error=%v", gotPath, err)
+ }
+
+ if got, err := os.ReadFile(unrelated); err != nil || string(got) != untouched {
+ t.Errorf("persistence changed unrelated state: error=%v", err)
+ }
+ if got, err := os.Lstat(stale); err != nil {
+ t.Errorf("persistence removed the stale %s path: %v", kind, err)
+ } else if !os.SameFile(staleInfo, got) || got.Mode() != staleInfo.Mode() {
+ t.Errorf("persistence replaced or changed permissions of the stale %s path", kind)
+ }
+ if kind != "directory" {
+ if got, err := os.ReadFile(stale); err != nil || string(got) != untouched {
+ t.Errorf("persistence changed the stale %s contents: error=%v", kind, err)
+ }
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(data, []byte(token)) {
+ t.Error("canonical record contains the plaintext setup token")
+ }
+ var record persistedToken
+ if err := json.Unmarshal(data, &record); err != nil || record.Version != persistedFormatVersion || record.TokenCiphertext == "" || record.TokenHash == "" {
+ t.Fatalf("canonical encrypted record is incomplete: %v", err)
+ }
+ if !migrate && !record.CreatedAt.Equal(createdAt) {
+ t.Error("persistence changed the supplied creation time")
+ }
+ if got, gotPath, migrated, err := Load(dir); err != nil || got != token || gotPath != path || migrated {
+ t.Errorf("encrypted record did not round-trip: migrated=%t path=%q error=%v", migrated, gotPath, err)
+ }
+ if runtime.GOOS != "windows" {
+ if info, err := os.Stat(path); err != nil || info.Mode().Perm() != 0o600 {
+ t.Errorf("canonical record is not owner-only: error=%v", err)
+ }
+ }
+ if got, err := os.ReadFile(keyPath); err != nil || !bytes.Equal(got, keyBefore) {
+ t.Errorf("persistence changed the encryption key: error=%v", err)
+ }
+ assertNoBootstrapTemporaryFiles(t, dir)
+ })
+ }
+ }
+}
+
+func TestPersistFailedReplacementPreservesExistingState(t *testing.T) {
+ dir := t.TempDir()
+ path, err := Persist(dir, "initial-synthetic-setup-token", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ keyBefore, err := os.ReadFile(filepath.Join(dir, ".encryption.key"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(path); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir(path, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ marker := filepath.Join(path, "preserved-state")
+ if err := os.WriteFile(marker, []byte("keep"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ gotPath, err := Persist(dir, "replacement-synthetic-setup-token", time.Now())
+ if err == nil || gotPath != path {
+ t.Fatalf("replacement of a directory must fail with its resolved path: path=%q error=%v", gotPath, err)
+ }
+ if got, err := os.ReadFile(marker); err != nil || string(got) != "keep" {
+ t.Errorf("failed replacement changed existing state: error=%v", err)
+ }
+ if got, err := os.ReadFile(filepath.Join(dir, ".encryption.key")); err != nil || !bytes.Equal(got, keyBefore) {
+ t.Errorf("failed replacement changed the encryption key: error=%v", err)
+ }
+ assertNoBootstrapTemporaryFiles(t, dir)
+}
+
+func TestPersistConcurrentWritesUseIndependentTemporaryFiles(t *testing.T) {
+ dir := t.TempDir()
+ if _, err := Persist(dir, "initial-synthetic-setup-token", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ // Seed the existing key before concurrent writes. Key creation and
+ // cross-process first-run coordination are not this writer's contract.
+ const writers = 12
+ errors := make(chan error, writers)
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ for i := 0; i < writers; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ <-start
+ _, err := Persist(dir, fmt.Sprintf("concurrent-synthetic-setup-token-%02d", i), time.Now())
+ errors <- err
+ }(i)
+ }
+ close(start)
+ wg.Wait()
+ close(errors)
+ for err := range errors {
+ if err != nil {
+ t.Errorf("concurrent persistence failed: %v", err)
+ }
+ }
+ token, _, migrated, err := Load(dir)
+ if err != nil || migrated {
+ t.Fatalf("final encrypted record cannot be loaded: migrated=%t error=%v", migrated, err)
+ }
+ valid := false
+ for i := 0; i < writers; i++ {
+ valid = valid || token == fmt.Sprintf("concurrent-synthetic-setup-token-%02d", i)
+ }
+ if !valid {
+ t.Error("final record is not one complete successful write")
+ }
+ assertNoBootstrapTemporaryFiles(t, dir)
+}
+
+func assertNoBootstrapTemporaryFiles(t *testing.T, dir string) {
+ t.Helper()
+ paths, err := filepath.Glob(filepath.Join(dir, "."+TokenFilename+".*.tmp"))
+ if err != nil || len(paths) != 0 {
+ t.Errorf("private temporary files remain after persistence: count=%d error=%v", len(paths), err)
+ }
+}