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: license persistence survives Docker container recreation

rcourtmanf1853e354b4e
diff --git a/internal/license/persistence.go b/internal/license/persistence.go
index cfbb20b899..54bc2b35c1 100644
--- a/internal/license/persistence.go
+++ b/internal/license/persistence.go
@@ -6,39 +6,98 @@ import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
+ "strings"
)
const (
// LicenseFileName is the name of the encrypted license file.
LicenseFileName = "license.enc"
+ // PersistentKeyFileName is the name of the persistent encryption key file.
+ // This file is stored in the config directory (e.g., /data/) and survives
+ // Docker container recreation, unlike /etc/machine-id.
+ PersistentKeyFileName = ".license-key"
)
// Persistence handles encrypted storage of license keys.
type Persistence struct {
- configDir string
- machineID string // Used as encryption key material
+ configDir string
+ encryptionKey string // Primary key for encryption (persistent or machine-id)
+ machineID string // Fallback for backwards compatibility
}
// NewPersistence creates a new license persistence handler.
+// It tries to use a persistent key stored in configDir first, then falls back
+// to machine-id for backwards compatibility with existing installations.
func NewPersistence(configDir string) (*Persistence, error) {
+ // Try to load persistent key from config directory first
+ persistentKey, _ := loadPersistentKey(configDir)
+
+ // Get machine-id as fallback for backwards compatibility
machineID, err := getMachineID()
if err != nil {
- // Fall back to a fixed key for development
machineID = "pulse-dev-fallback-machine-id"
}
+ // Use persistent key if available, otherwise machine-id
+ encryptionKey := persistentKey
+ if encryptionKey == "" {
+ encryptionKey = machineID
+ }
+
return &Persistence{
- configDir: configDir,
- machineID: machineID,
+ configDir: configDir,
+ encryptionKey: encryptionKey,
+ machineID: machineID,
}, nil
}
+// loadPersistentKey attempts to load the persistent encryption key from disk.
+func loadPersistentKey(configDir string) (string, error) {
+ keyPath := filepath.Join(configDir, PersistentKeyFileName)
+ data, err := os.ReadFile(keyPath)
+ if err != nil {
+ return "", err
+ }
+ return strings.TrimSpace(string(data)), nil
+}
+
+// ensurePersistentKey creates a persistent encryption key if one doesn't exist.
+// Returns the key (existing or newly created).
+func (p *Persistence) ensurePersistentKey() (string, error) {
+ keyPath := filepath.Join(p.configDir, PersistentKeyFileName)
+
+ // Check if key already exists
+ if data, err := os.ReadFile(keyPath); err == nil {
+ return strings.TrimSpace(string(data)), nil
+ }
+
+ // Generate a new random key (32 bytes = 64 hex chars)
+ keyBytes := make([]byte, 32)
+ if _, err := io.ReadFull(rand.Reader, keyBytes); err != nil {
+ return "", fmt.Errorf("failed to generate encryption key: %w", err)
+ }
+ key := hex.EncodeToString(keyBytes)
+
+ // Ensure config directory exists
+ if err := os.MkdirAll(p.configDir, 0700); err != nil {
+ return "", fmt.Errorf("failed to create config directory: %w", err)
+ }
+
+ // Save the key
+ if err := os.WriteFile(keyPath, []byte(key), 0600); err != nil {
+ return "", fmt.Errorf("failed to write encryption key: %w", err)
+ }
+
+ return key, nil
+}
+
// PersistedLicense contains the license key and metadata for storage.
type PersistedLicense struct {
LicenseKey string `json:"license_key"`
@@ -56,6 +115,14 @@ func (p *Persistence) SaveWithGracePeriod(licenseKey string, gracePeriodEnd *int
return errors.New("license key cannot be empty")
}
+ // Ensure we have a persistent encryption key for future-proofing.
+ // This creates .license-key in the config directory if it doesn't exist,
+ // ensuring Docker users don't lose their license on container recreation.
+ newKey, err := p.ensurePersistentKey()
+ if err == nil && newKey != "" {
+ p.encryptionKey = newKey
+ }
+
// Store as JSON with metadata
persisted := PersistedLicense{
LicenseKey: licenseKey,
@@ -96,6 +163,8 @@ func (p *Persistence) Load() (string, error) {
}
// LoadWithMetadata reads and decrypts a license with metadata from disk.
+// It tries to decrypt with the current encryption key first, then falls back
+// to machine-id for backwards compatibility with existing installations.
func (p *Persistence) LoadWithMetadata() (PersistedLicense, error) {
licensePath := filepath.Join(p.configDir, LicenseFileName)
@@ -112,7 +181,16 @@ func (p *Persistence) LoadWithMetadata() (PersistedLicense, error) {
return PersistedLicense{}, fmt.Errorf("failed to decode license file: %w", err)
}
+ // Try to decrypt with current encryption key
decrypted, err := p.decrypt(encrypted)
+
+ // If decryption failed and we have a different machine-id, try that as fallback
+ // This handles the case where an existing license was encrypted with machine-id
+ // before the persistent key feature was added
+ if err != nil && p.machineID != p.encryptionKey {
+ decrypted, err = p.decryptWithKey(encrypted, p.deriveKeyFrom(p.machineID))
+ }
+
if err != nil {
return PersistedLicense{}, fmt.Errorf("failed to decrypt license: %w", err)
}
@@ -167,10 +245,13 @@ func (p *Persistence) encrypt(plaintext []byte) ([]byte, error) {
return ciphertext, nil
}
-// decrypt uses AES-GCM to decrypt data.
+// decrypt uses AES-GCM to decrypt data with the current encryption key.
func (p *Persistence) decrypt(ciphertext []byte) ([]byte, error) {
- key := p.deriveKey()
+ return p.decryptWithKey(ciphertext, p.deriveKey())
+}
+// decryptWithKey uses AES-GCM to decrypt data with a specific key.
+func (p *Persistence) decryptWithKey(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
@@ -186,9 +267,9 @@ func (p *Persistence) decrypt(ciphertext []byte) ([]byte, error) {
}
nonce := ciphertext[:gcm.NonceSize()]
- ciphertext = ciphertext[gcm.NonceSize():]
+ data := ciphertext[gcm.NonceSize():]
- plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
+ plaintext, err := gcm.Open(nil, nonce, data, nil)
if err != nil {
return nil, err
}
@@ -196,9 +277,14 @@ func (p *Persistence) decrypt(ciphertext []byte) ([]byte, error) {
return plaintext, nil
}
-// deriveKey derives a 32-byte key from the machine ID.
+// deriveKey derives a 32-byte key from the current encryption key.
func (p *Persistence) deriveKey() []byte {
- hash := sha256.Sum256([]byte("pulse-license-" + p.machineID))
+ return p.deriveKeyFrom(p.encryptionKey)
+}
+
+// deriveKeyFrom derives a 32-byte key from a given key material.
+func (p *Persistence) deriveKeyFrom(keyMaterial string) []byte {
+ hash := sha256.Sum256([]byte("pulse-license-" + keyMaterial))
return hash[:]
}
diff --git a/internal/license/persistence_test.go b/internal/license/persistence_test.go
index b9da9ff074..d262b524bd 100644
--- a/internal/license/persistence_test.go
+++ b/internal/license/persistence_test.go
@@ -1,6 +1,8 @@
package license
import (
+ "encoding/base64"
+ "encoding/json"
"os"
"path/filepath"
"testing"
@@ -126,10 +128,11 @@ func TestPersistence(t *testing.T) {
t.Fatalf("Failed to save license: %v", err)
}
- // Create a new persistence with different machine ID
+ // Create a new persistence with different encryption key
pWrong := &Persistence{
- configDir: tmpDir,
- machineID: "different-machine-id",
+ configDir: tmpDir,
+ encryptionKey: "different-encryption-key",
+ machineID: "different-machine-id",
}
_, err = pWrong.Load()
@@ -137,4 +140,64 @@ func TestPersistence(t *testing.T) {
t.Error("Expected error when decrypting with wrong key material")
}
})
+
+ t.Run("Backwards compatibility with machine-id", func(t *testing.T) {
+ // This tests the scenario where a license was saved with machine-id
+ // (old behavior before persistent key feature) and we're now loading it
+ // with a different primary key but same machine-id as fallback
+
+ tmpDirCompat, _ := os.MkdirTemp("", "pulse-license-compat-*")
+ defer os.RemoveAll(tmpDirCompat)
+
+ testKey := "compat-test-key"
+ machineID := "test-machine-id-12345"
+
+ // Simulate old behavior: directly encrypt with machine-id (without calling Save
+ // which would create a persistent key). This is what old installations have.
+ pOld := &Persistence{
+ configDir: tmpDirCompat,
+ encryptionKey: machineID, // Old behavior used machine-id as encryption key
+ machineID: machineID,
+ }
+
+ // Manually encrypt and save without creating persistent key
+ persisted := PersistedLicense{LicenseKey: testKey}
+ jsonData, _ := json.Marshal(persisted)
+ encrypted, err := pOld.encrypt(jsonData)
+ if err != nil {
+ t.Fatalf("Failed to encrypt license: %v", err)
+ }
+
+ // Write directly to simulate old installation
+ os.MkdirAll(tmpDirCompat, 0700)
+ licensePath := filepath.Join(tmpDirCompat, LicenseFileName)
+ encoded := base64.StdEncoding.EncodeToString(encrypted)
+ os.WriteFile(licensePath, []byte(encoded), 0600)
+
+ // Verify no persistent key file exists (simulating old installation)
+ keyPath := filepath.Join(tmpDirCompat, PersistentKeyFileName)
+ if _, err := os.Stat(keyPath); err == nil {
+ t.Fatal("Persistent key should not exist for this test")
+ }
+
+ // Now try to load with a new primary key but same machine-id as fallback
+ // This simulates what happens when a Docker user upgrades and gets a
+ // persistent key file, but their old license was encrypted with machine-id
+ pNew := &Persistence{
+ configDir: tmpDirCompat,
+ encryptionKey: "new-persistent-key", // Different primary key (simulating new container)
+ machineID: machineID, // Same machine-id for fallback
+ }
+
+ loaded, err := pNew.LoadWithMetadata()
+ if err != nil {
+ t.Fatalf("Failed to load license with machine-id fallback: %v\n"+
+ "This means backwards compatibility is broken for existing Docker users", err)
+ }
+
+ if loaded.LicenseKey != testKey {
+ t.Errorf("Expected license key %s, got %s", testKey, loaded.LicenseKey)
+ }
+ })
}
+