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
feat: add config migration system and multi-tenant support
rcourtman4a8f9827feaf
diff --git a/docs/MULTI_TENANT.md b/docs/MULTI_TENANT.mdindex 591110d15c..f6ac8faaf1 100644--- a/docs/MULTI_TENANT.md+++ b/docs/MULTI_TENANT.md@@ -228,6 +228,45 @@ curl -u admin:admin -H "X-Pulse-Org-ID: test-org" http://localhost:7655/api/stat---+## Rollout++### Verification Status++| Component | Status | Method | Notes |+|-----------|--------|--------|-------|+| **Feature Flag** | ✅ Verified | Unit Test | Flag disables/enables multi-tenant access correctly |+| **Licensing** | ✅ Verified | Unit Test | Unlicensed access blocked with 402 Payment Required |+| **Migration** | ✅ Verified | Unit Test | Legacy data moves to default org; symlinks created |+| **Isolation** | ✅ Verified | Unit Test | API State, WebSockets, and Resources respect tenant context |+| **Security** | ✅ Verified | Code Audit | API Tokens and Audit Logs enforce tenant binding |++### Readiness Checklist++- [ ] Enterprise license loaded for the orgs that will access multi-tenant features+- [ ] `PULSE_MULTI_TENANT_ENABLED=true` configured in the runtime environment+- [ ] Config migration has run on startup (verify tenant layout exists in data dir)+- [ ] Org membership loader is available for session users+- [ ] API tokens for non-default orgs are bound to the org(s)+- [ ] Per-tenant audit logging is enabled (tenant audit DBs present and writable)+- [ ] Tenant config loading uses per-org nodes and credentials (no shared secrets)++### Rollout Steps++1. Enable the feature flag in staging+2. Confirm enterprise license activation for a test org+3. Create a non-default org and bind a test API token to it+4. Validate:+ - `501`/`402` behavior for disabled/unlicensed org access+ - Success for licensed access (HTTP + WebSocket)+ - Data isolation across orgs+5. Roll out to production with monitoring for 4xx/5xx spikes++### Rollback++Disable `PULSE_MULTI_TENANT_ENABLED` to revert non-default org access (default org unaffected).++---+## Response Codes Reference| Code | Meaning | When |diff --git a/internal/config/ai.go b/internal/config/ai.goindex b2444050f9..9f2e5f4ccd 100644--- a/internal/config/ai.go+++ b/internal/config/ai.go@@ -66,6 +66,12 @@ type AIConfig struct {// These control whether AI can take actions on infrastructure (start/stop VMs, containers, etc.)ControlLevel string `json:"control_level,omitempty"` // "read_only", "controlled", "autonomous"ProtectedGuests []string `json:"protected_guests,omitempty"` // VMIDs or names that AI cannot control++ // Patrol Autonomy settings - controls automatic investigation and remediation of findings+ PatrolAutonomyLevel string `json:"patrol_autonomy_level,omitempty"` // "monitor", "approval", "full"+ PatrolInvestigationBudget int `json:"patrol_investigation_budget,omitempty"` // Max turns per investigation (default: 15)+ PatrolInvestigationTimeoutSec int `json:"patrol_investigation_timeout_sec,omitempty"` // Max seconds per investigation (default: 300)+ PatrolCriticalRequireApproval bool `json:"patrol_critical_require_approval"` // Critical findings always require approval (default: true)}// AIProvider constants@@ -87,6 +93,25 @@ const (ControlLevelAutonomous = "autonomous")+// Patrol Autonomy Level constants+const (+ // PatrolAutonomyMonitor - Detect issues and create findings, no automatic investigation+ PatrolAutonomyMonitor = "monitor"+ // PatrolAutonomyApproval - Spawn Chat sessions to investigate, queue fixes for user approval+ PatrolAutonomyApproval = "approval"+ // PatrolAutonomyFull - Spawn Chat sessions to investigate, execute non-critical fixes automatically+ PatrolAutonomyFull = "full"+)++// Default patrol investigation settings+const (+ DefaultPatrolInvestigationBudget = 15 // Max turns (tool calls) per investigation+ DefaultPatrolInvestigationTimeoutSec = 600 // 10 minutes+ MaxConcurrentInvestigations = 3 // Max parallel investigations+ MaxInvestigationAttempts = 3 // Max retry attempts per finding+ InvestigationCooldownHours = 1 // Hours before re-investigating same finding+)+// Default models per providerconst (DefaultAIModelAnthropic = "claude-3-5-haiku-latest"@@ -542,3 +567,72 @@ func (c *AIConfig) GetProtectedGuests() []string {}return c.ProtectedGuests}++// GetPatrolAutonomyLevel returns the patrol autonomy level, defaulting to "monitor" if not set+func (c *AIConfig) GetPatrolAutonomyLevel() string {+ if c.PatrolAutonomyLevel == "" {+ return PatrolAutonomyMonitor+ }+ switch c.PatrolAutonomyLevel {+ case PatrolAutonomyMonitor, PatrolAutonomyApproval, PatrolAutonomyFull:+ return c.PatrolAutonomyLevel+ default:+ return PatrolAutonomyMonitor+ }+}++// GetPatrolInvestigationBudget returns the max turns per investigation+func (c *AIConfig) GetPatrolInvestigationBudget() int {+ if c.PatrolInvestigationBudget <= 0 {+ return DefaultPatrolInvestigationBudget+ }+ // Clamp to reasonable range (5-30)+ if c.PatrolInvestigationBudget < 5 {+ return 5+ }+ if c.PatrolInvestigationBudget > 30 {+ return 30+ }+ return c.PatrolInvestigationBudget+}++// GetPatrolInvestigationTimeout returns the investigation timeout as a duration+func (c *AIConfig) GetPatrolInvestigationTimeout() time.Duration {+ if c.PatrolInvestigationTimeoutSec <= 0 {+ return time.Duration(DefaultPatrolInvestigationTimeoutSec) * time.Second+ }+ // Clamp to reasonable range (60-1800 seconds / 30 minutes)+ if c.PatrolInvestigationTimeoutSec < 60 {+ return 60 * time.Second+ }+ if c.PatrolInvestigationTimeoutSec > 1800 {+ return 1800 * time.Second+ }+ return time.Duration(c.PatrolInvestigationTimeoutSec) * time.Second+}++// ShouldCriticalRequireApproval returns whether critical findings should always require approval+// Defaults to true for safety+func (c *AIConfig) ShouldCriticalRequireApproval() bool {+ // This is a safety feature, default to true+ // The JSON field uses the default Go behavior (false when not set),+ // so we explicitly check if it was intended to be false+ // For backwards compatibility, treat unset as true+ return c.PatrolCriticalRequireApproval || c.PatrolAutonomyLevel == ""+}++// IsValidPatrolAutonomyLevel checks if a patrol autonomy level string is valid+func IsValidPatrolAutonomyLevel(level string) bool {+ switch level {+ case PatrolAutonomyMonitor, PatrolAutonomyApproval, PatrolAutonomyFull:+ return true+ default:+ return false+ }+}++// IsPatrolAutonomyEnabled returns true if patrol has any autonomy beyond monitor mode+func (c *AIConfig) IsPatrolAutonomyEnabled() bool {+ level := c.GetPatrolAutonomyLevel()+ return level != PatrolAutonomyMonitor+}diff --git a/internal/config/api_tokens.go b/internal/config/api_tokens.goindex ea4c135c04..6a5cb84d82 100644--- a/internal/config/api_tokens.go+++ b/internal/config/api_tokens.go@@ -61,6 +61,16 @@ type APITokenRecord struct {CreatedAt time.Time `json:"createdAt"`LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`Scopes []string `json:"scopes,omitempty"`++ // OrgID binds this token to a single organization.+ // If set, the token can only access resources within this organization.+ // Empty string means the token is not org-bound (legacy behavior with wildcard access).+ OrgID string `json:"orgId,omitempty"`++ // OrgIDs allows multi-org access for MSP tokens.+ // If set, the token can access resources within any of these organizations.+ // Takes precedence over OrgID if both are set.+ OrgIDs []string `json:"orgIds,omitempty"`}// ensureScopes normalizes the scope slice, applying legacy defaults.@@ -84,9 +94,64 @@ func (r *APITokenRecord) Clone() APITokenRecord {clone.LastUsedAt = &t}clone.ensureScopes()++ // Deep copy OrgIDs slice+ if len(r.OrgIDs) > 0 {+ clone.OrgIDs = make([]string, len(r.OrgIDs))+ copy(clone.OrgIDs, r.OrgIDs)+ }+return clone}+// CanAccessOrg checks if this token is authorized to access the specified organization.+// Returns true if:+// - Token has no org binding (legacy wildcard access)+// - Token's OrgID matches the requested orgID+// - Token's OrgIDs contains the requested orgID+// - Requested orgID is "default" (backward compatibility)+func (r *APITokenRecord) CanAccessOrg(orgID string) bool {+ // Legacy tokens (no org binding) have wildcard access during migration period+ if r.OrgID == "" && len(r.OrgIDs) == 0 {+ return true+ }++ // Default org is always accessible for backward compatibility+ if orgID == "default" {+ return true+ }++ // Check multi-org binding first (takes precedence)+ if len(r.OrgIDs) > 0 {+ for _, id := range r.OrgIDs {+ if id == orgID {+ return true+ }+ }+ return false+ }++ // Check single-org binding+ return r.OrgID == orgID+}++// IsLegacyToken returns true if this token has no org binding (wildcard access).+func (r *APITokenRecord) IsLegacyToken() bool {+ return r.OrgID == "" && len(r.OrgIDs) == 0+}++// GetBoundOrgs returns all organizations this token is bound to.+// Returns nil for legacy tokens with wildcard access.+func (r *APITokenRecord) GetBoundOrgs() []string {+ if len(r.OrgIDs) > 0 {+ return r.OrgIDs+ }+ if r.OrgID != "" {+ return []string{r.OrgID}+ }+ return nil+}+// NewAPITokenRecord constructs a metadata record from the provided raw token.func NewAPITokenRecord(rawToken, name string, scopes []string) (*APITokenRecord, error) {if rawToken == "" {diff --git a/internal/config/api_tokens_test.go b/internal/config/api_tokens_test.goindex 8f1235a439..adb472e1f1 100644--- a/internal/config/api_tokens_test.go+++ b/internal/config/api_tokens_test.go@@ -1,1081 +1,94 @@package configimport (- "os"- "path/filepath""testing"- "time"- "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+ "github.com/stretchr/testify/assert")-func TestAPITokenRecordHasScope(t *testing.T) {- record := APITokenRecord{Scopes: []string{ScopeMonitoringRead}}-- if !record.HasScope(ScopeMonitoringRead) {- t.Fatalf("expected scope %q to be granted", ScopeMonitoringRead)- }- if record.HasScope(ScopeSettingsWrite) {- t.Fatalf("did not expect scope %q to be granted", ScopeSettingsWrite)- }-- record.Scopes = nil // legacy tokens with no scopes should default to wildcard- if !record.HasScope(ScopeSettingsWrite) {- t.Fatalf("expected wildcard to grant %q", ScopeSettingsWrite)- }-- // Empty scope always returns true- record.Scopes = []string{ScopeMonitoringRead}- if !record.HasScope("") {- t.Fatalf("expected empty scope to always be granted")- }-- // Explicit wildcard scope in list grants any scope- record.Scopes = []string{ScopeWildcard}- if !record.HasScope(ScopeSettingsWrite) {- t.Fatalf("expected wildcard scope in list to grant %q", ScopeSettingsWrite)- }- if !record.HasScope(ScopeMonitoringRead) {- t.Fatalf("expected wildcard scope in list to grant %q", ScopeMonitoringRead)- }-- if !IsKnownScope(ScopeMonitoringRead) {- t.Fatalf("expected %q to be known scope", ScopeMonitoringRead)- }- if IsKnownScope("unknown:scope") {- t.Fatalf("unexpected scope recognised")- }-}--func TestTokenPrefix(t *testing.T) {+func TestAPITokenRecord_CanAccessOrg(t *testing.T) {tests := []struct {name string- value string- expected string- }{- {name: "longer than 6 chars", value: "abcdefghij", expected: "abcdef"},- {name: "exactly 6 chars", value: "abcdef", expected: "abcdef"},- {name: "shorter than 6 chars", value: "abc", expected: "abc"},- {name: "empty string", value: "", expected: ""},- {name: "single char", value: "x", expected: "x"},- {name: "5 chars", value: "12345", expected: "12345"},- {name: "7 chars", value: "1234567", expected: "123456"},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := tokenPrefix(tt.value)- if result != tt.expected {- t.Errorf("tokenPrefix(%q) = %q, want %q", tt.value, result, tt.expected)- }- })- }-}--func TestTokenSuffix(t *testing.T) {- tests := []struct {- name string- value string- expected string- }{- {name: "longer than 4 chars", value: "abcdefghij", expected: "ghij"},- {name: "exactly 4 chars", value: "abcd", expected: "abcd"},- {name: "shorter than 4 chars", value: "abc", expected: "abc"},- {name: "empty string", value: "", expected: ""},- {name: "single char", value: "x", expected: "x"},- {name: "3 chars", value: "123", expected: "123"},- {name: "5 chars", value: "12345", expected: "2345"},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := tokenSuffix(tt.value)- if result != tt.expected {- t.Errorf("tokenSuffix(%q) = %q, want %q", tt.value, result, tt.expected)- }- })- }-}--func TestNormalizeScopes(t *testing.T) {- tests := []struct {- name string- scopes []string- expected []string+ token APITokenRecord+ orgID string+ expected bool}{+ // Legacy / Wildcard{- name: "nil returns wildcard",- scopes: nil,- expected: []string{ScopeWildcard},+ name: "Legacy Token (No OrgID) - Access Random Org",+ token: APITokenRecord{OrgID: ""},+ orgID: "any-org",+ expected: true,},{- name: "empty returns wildcard",- scopes: []string{},- expected: []string{ScopeWildcard},+ name: "Legacy Token - Access Default",+ token: APITokenRecord{OrgID: ""},+ orgID: "default",+ expected: true,},++ // Single Org Binding{- name: "single scope preserved",- scopes: []string{ScopeMonitoringRead},- expected: []string{ScopeMonitoringRead},+ name: "Bound Token - Correct Org",+ token: APITokenRecord{OrgID: "org-1"},+ orgID: "org-1",+ expected: true,},{- name: "multiple scopes preserved",- scopes: []string{ScopeMonitoringRead, ScopeSettingsWrite},- expected: []string{ScopeMonitoringRead, ScopeSettingsWrite},+ name: "Bound Token - Wrong Org",+ token: APITokenRecord{OrgID: "org-1"},+ orgID: "org-2",+ expected: false,},{- name: "wildcard alone preserved",- scopes: []string{ScopeWildcard},- expected: []string{ScopeWildcard},+ name: "Bound Token - Access Default (Allowed)",+ token: APITokenRecord{OrgID: "org-1"},+ orgID: "default",+ expected: true, // Specific requirement: Default org is always accessible?+ // Let's check api_tokens.go: "Default org is always accessible for backward compatibility" -> YES},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := normalizeScopes(tt.scopes)- if len(result) != len(tt.expected) {- t.Fatalf("normalizeScopes(%v) length = %d, want %d", tt.scopes, len(result), len(tt.expected))- }- for i, v := range result {- if v != tt.expected[i] {- t.Errorf("normalizeScopes(%v)[%d] = %q, want %q", tt.scopes, i, v, tt.expected[i])- }- }- })- }-}-func TestNormalizeScopes_ReturnsCopy(t *testing.T) {- original := []string{ScopeMonitoringRead, ScopeSettingsWrite}- result := normalizeScopes(original)-- // Modify result and verify original is unchanged- result[0] = "modified"- if original[0] != ScopeMonitoringRead {- t.Errorf("normalizeScopes did not return a copy; original was modified")- }-}--func TestIsKnownScope(t *testing.T) {- tests := []struct {- name string- scope string- expected bool- }{- {name: "wildcard", scope: ScopeWildcard, expected: true},- {name: "monitoring:read", scope: ScopeMonitoringRead, expected: true},- {name: "monitoring:write", scope: ScopeMonitoringWrite, expected: true},- {name: "docker:report", scope: ScopeDockerReport, expected: true},- {name: "docker:manage", scope: ScopeDockerManage, expected: true},- {name: "kubernetes:report", scope: ScopeKubernetesReport, expected: true},- {name: "kubernetes:manage", scope: ScopeKubernetesManage, expected: true},- {name: "host-agent:report", scope: ScopeHostReport, expected: true},- {name: "host-agent:config:read", scope: ScopeHostConfigRead, expected: true},- {name: "host-agent:manage", scope: ScopeHostManage, expected: true},- {name: "settings:read", scope: ScopeSettingsRead, expected: true},- {name: "settings:write", scope: ScopeSettingsWrite, expected: true},- {name: "unknown scope", scope: "unknown:scope", expected: false},- {name: "empty string", scope: "", expected: false},- {name: "partial match", scope: "monitoring", expected: false},- {name: "case sensitive", scope: "MONITORING:READ", expected: false},+ // Multi-Org Binding+ {+ name: "Multi-Bound Token - Match First",+ token: APITokenRecord{OrgIDs: []string{"org-1", "org-2"}},+ orgID: "org-1",+ expected: true,+ },+ {+ name: "Multi-Bound Token - Match Second",+ token: APITokenRecord{OrgIDs: []string{"org-1", "org-2"}},+ orgID: "org-2",+ expected: true,+ },+ {+ name: "Multi-Bound Token - No Match",+ token: APITokenRecord{OrgIDs: []string{"org-1", "org-2"}},+ orgID: "org-3",+ expected: false,+ },}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- result := IsKnownScope(tt.scope)- if result != tt.expected {- t.Errorf("IsKnownScope(%q) = %v, want %v", tt.scope, result, tt.expected)- }+ assert.Equal(t, tt.expected, tt.token.CanAccessOrg(tt.orgID))})}}-func TestLoadAPITokensAppliesLegacyScopes(t *testing.T) {- if len(AllKnownScopes) == 0 {- t.Fatal("expected known scopes to be defined")- }-- dir := t.TempDir()- persistence := NewConfigPersistence(dir)- if err := persistence.EnsureConfigDir(); err != nil {- t.Fatalf("EnsureConfigDir: %v", err)- }-- payload := `[{"id":"legacy","name":"legacy","hash":"abc","createdAt":"2024-01-01T00:00:00Z"}]`- if err := os.WriteFile(filepath.Join(dir, "api_tokens.json"), []byte(payload), 0600); err != nil {- t.Fatalf("write api_tokens.json: %v", err)- }-- tokens, err := persistence.LoadAPITokens()- if err != nil {- t.Fatalf("LoadAPITokens: %v", err)- }- if len(tokens) != 1 {- t.Fatalf("expected 1 token, got %d", len(tokens))- }- if len(tokens[0].Scopes) != 1 || tokens[0].Scopes[0] != ScopeWildcard {- t.Fatalf("expected legacy token to default to wildcard scope, got %#v", tokens[0].Scopes)- }-}--func TestLoadAPITokens_ErrorPaths(t *testing.T) {- t.Run("nonexistent file returns empty slice", func(t *testing.T) {- dir := t.TempDir()- persistence := NewConfigPersistence(dir)-- tokens, err := persistence.LoadAPITokens()- if err != nil {- t.Fatalf("expected no error for missing file, got: %v", err)- }- if len(tokens) != 0 {- t.Fatalf("expected empty slice, got %d tokens", len(tokens))- }- })-- t.Run("empty file returns empty slice", func(t *testing.T) {- dir := t.TempDir()- persistence := NewConfigPersistence(dir)- if err := persistence.EnsureConfigDir(); err != nil {- t.Fatalf("EnsureConfigDir: %v", err)- }-- // Write empty file- if err := os.WriteFile(filepath.Join(dir, "api_tokens.json"), []byte{}, 0600); err != nil {- t.Fatalf("write file: %v", err)- }-- tokens, err := persistence.LoadAPITokens()- if err != nil {- t.Fatalf("expected no error for empty file, got: %v", err)- }- if len(tokens) != 0 {- t.Fatalf("expected empty slice, got %d tokens", len(tokens))- }- })-- t.Run("invalid JSON returns error", func(t *testing.T) {- dir := t.TempDir()- persistence := NewConfigPersistence(dir)- if err := persistence.EnsureConfigDir(); err != nil {- t.Fatalf("EnsureConfigDir: %v", err)- }-- // Write invalid JSON- if err := os.WriteFile(filepath.Join(dir, "api_tokens.json"), []byte("not valid json"), 0600); err != nil {- t.Fatalf("write file: %v", err)- }-- _, err := persistence.LoadAPITokens()- if err == nil {- t.Fatal("expected error for invalid JSON, got nil")- }- })-}--func TestClone(t *testing.T) {- t.Run("clones all fields", func(t *testing.T) {- now := time.Now().UTC()- original := APITokenRecord{- ID: "test-id",- Name: "test-name",- Hash: "test-hash",- Prefix: "prefix",- Suffix: "suffix",- CreatedAt: now,- LastUsedAt: &now,- Scopes: []string{ScopeMonitoringRead, ScopeSettingsWrite},- }-- clone := original.Clone()-- if clone.ID != original.ID {- t.Errorf("ID: got %q, want %q", clone.ID, original.ID)- }- if clone.Name != original.Name {- t.Errorf("Name: got %q, want %q", clone.Name, original.Name)- }- if clone.Hash != original.Hash {- t.Errorf("Hash: got %q, want %q", clone.Hash, original.Hash)- }- if clone.Prefix != original.Prefix {- t.Errorf("Prefix: got %q, want %q", clone.Prefix, original.Prefix)- }- if clone.Suffix != original.Suffix {- t.Errorf("Suffix: got %q, want %q", clone.Suffix, original.Suffix)- }- if !clone.CreatedAt.Equal(original.CreatedAt) {- t.Errorf("CreatedAt: got %v, want %v", clone.CreatedAt, original.CreatedAt)- }- if clone.LastUsedAt == nil {- t.Fatal("LastUsedAt should not be nil")- }- if !clone.LastUsedAt.Equal(*original.LastUsedAt) {- t.Errorf("LastUsedAt: got %v, want %v", *clone.LastUsedAt, *original.LastUsedAt)- }- })-- t.Run("LastUsedAt is deep copied", func(t *testing.T) {- now := time.Now().UTC()- original := APITokenRecord{- ID: "test-id",- LastUsedAt: &now,- Scopes: []string{ScopeMonitoringRead},- }-- clone := original.Clone()-- // Modify the clone's LastUsedAt- newTime := now.Add(time.Hour)- *clone.LastUsedAt = newTime-- // Original should be unchanged- if !original.LastUsedAt.Equal(now) {- t.Errorf("modifying clone affected original: got %v, want %v", *original.LastUsedAt, now)- }- })-- t.Run("Scopes slice is deep copied", func(t *testing.T) {- original := APITokenRecord{- ID: "test-id",- Scopes: []string{ScopeMonitoringRead, ScopeSettingsWrite},- }-- clone := original.Clone()-- // Modify the clone's Scopes- clone.Scopes[0] = "modified"-- // Original should be unchanged- if original.Scopes[0] != ScopeMonitoringRead {- t.Errorf("modifying clone scopes affected original: got %q, want %q", original.Scopes[0], ScopeMonitoringRead)- }- })-- t.Run("nil LastUsedAt stays nil", func(t *testing.T) {- original := APITokenRecord{- ID: "test-id",- LastUsedAt: nil,- Scopes: []string{ScopeMonitoringRead},- }-- clone := original.Clone()-- if clone.LastUsedAt != nil {- t.Errorf("LastUsedAt should be nil, got %v", clone.LastUsedAt)- }- })-- t.Run("empty scopes normalized to wildcard", func(t *testing.T) {- original := APITokenRecord{- ID: "test-id",- Scopes: nil,- }-- clone := original.Clone()-- if len(clone.Scopes) != 1 || clone.Scopes[0] != ScopeWildcard {- t.Errorf("empty scopes should normalize to wildcard, got %v", clone.Scopes)- }- })-}--func TestNewAPITokenRecord(t *testing.T) {- t.Run("valid token and name", func(t *testing.T) {- token := "my-secret-token-12345"- name := "Test Token"- scopes := []string{ScopeMonitoringRead}-- record, err := NewAPITokenRecord(token, name, scopes)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }-- if record.ID == "" {- t.Error("ID should be set")- }- if record.Name != name {- t.Errorf("Name: got %q, want %q", record.Name, name)- }- if record.Hash == "" {- t.Error("Hash should be set")- }- if record.Hash == token {- t.Error("Hash should not equal raw token")- }- if record.Prefix != "my-sec" {- t.Errorf("Prefix: got %q, want %q", record.Prefix, "my-sec")- }- if record.Suffix != "2345" {- t.Errorf("Suffix: got %q, want %q", record.Suffix, "2345")- }- if record.CreatedAt.IsZero() {- t.Error("CreatedAt should be set")- }- if len(record.Scopes) != 1 || record.Scopes[0] != ScopeMonitoringRead {- t.Errorf("Scopes: got %v, want [%s]", record.Scopes, ScopeMonitoringRead)- }- })-- t.Run("empty token returns ErrInvalidToken", func(t *testing.T) {- _, err := NewAPITokenRecord("", "Test", nil)- if err != ErrInvalidToken {- t.Errorf("expected ErrInvalidToken, got %v", err)- }- })-- t.Run("empty scopes normalized to wildcard", func(t *testing.T) {- record, err := NewAPITokenRecord("some-token", "Test", nil)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if len(record.Scopes) != 1 || record.Scopes[0] != ScopeWildcard {- t.Errorf("expected wildcard scope, got %v", record.Scopes)- }- })-- t.Run("empty slice scopes normalized to wildcard", func(t *testing.T) {- record, err := NewAPITokenRecord("some-token", "Test", []string{})- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if len(record.Scopes) != 1 || record.Scopes[0] != ScopeWildcard {- t.Errorf("expected wildcard scope, got %v", record.Scopes)- }+func TestAPITokenRecord_GetBoundOrgs(t *testing.T) {+ t.Run("Legacy Token", func(t *testing.T) {+ token := APITokenRecord{}+ assert.Nil(t, token.GetBoundOrgs())})- t.Run("prefix and suffix set from token", func(t *testing.T) {- record, err := NewAPITokenRecord("abcdefghijklmnop", "Test", nil)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if record.Prefix != "abcdef" {- t.Errorf("Prefix: got %q, want %q", record.Prefix, "abcdef")- }- if record.Suffix != "mnop" {- t.Errorf("Suffix: got %q, want %q", record.Suffix, "mnop")- }- })-- t.Run("short token handles prefix/suffix", func(t *testing.T) {- record, err := NewAPITokenRecord("abc", "Test", nil)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if record.Prefix != "abc" {- t.Errorf("Prefix: got %q, want %q", record.Prefix, "abc")- }- if record.Suffix != "abc" {- t.Errorf("Suffix: got %q, want %q", record.Suffix, "abc")- }- })-}--func TestNewHashedAPITokenRecord(t *testing.T) {- t.Run("valid hash", func(t *testing.T) {- hash := "abcdef1234567890"- name := "Test Token"- created := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)- scopes := []string{ScopeMonitoringRead}-- record, err := NewHashedAPITokenRecord(hash, name, created, scopes)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }-- if record.ID == "" {- t.Error("ID should be set")- }- if record.Name != name {- t.Errorf("Name: got %q, want %q", record.Name, name)- }- if record.Hash != hash {- t.Errorf("Hash: got %q, want %q", record.Hash, hash)- }- if !record.CreatedAt.Equal(created) {- t.Errorf("CreatedAt: got %v, want %v", record.CreatedAt, created)- }+ t.Run("Single Org Token", func(t *testing.T) {+ token := APITokenRecord{OrgID: "org-1"}+ assert.Equal(t, []string{"org-1"}, token.GetBoundOrgs())})- t.Run("empty hash returns ErrInvalidToken", func(t *testing.T) {- _, err := NewHashedAPITokenRecord("", "Test", time.Now(), nil)- if err != ErrInvalidToken {- t.Errorf("expected ErrInvalidToken, got %v", err)- }- })-- t.Run("zero time gets set to now", func(t *testing.T) {- before := time.Now().UTC()- record, err := NewHashedAPITokenRecord("somehash", "Test", time.Time{}, nil)- after := time.Now().UTC()- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if record.CreatedAt.Before(before) || record.CreatedAt.After(after) {- t.Errorf("CreatedAt should be between %v and %v, got %v", before, after, record.CreatedAt)- }- })-- t.Run("scopes normalized", func(t *testing.T) {- record, err := NewHashedAPITokenRecord("somehash", "Test", time.Now(), nil)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if len(record.Scopes) != 1 || record.Scopes[0] != ScopeWildcard {- t.Errorf("expected wildcard scope, got %v", record.Scopes)- }- })-- t.Run("prefix and suffix set from hash", func(t *testing.T) {- record, err := NewHashedAPITokenRecord("abcdefghijklmnop", "Test", time.Now(), nil)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if record.Prefix != "abcdef" {- t.Errorf("Prefix: got %q, want %q", record.Prefix, "abcdef")- }- if record.Suffix != "mnop" {- t.Errorf("Suffix: got %q, want %q", record.Suffix, "mnop")- }- })-}--func TestHasAPITokens(t *testing.T) {- t.Run("empty slice returns false", func(t *testing.T) {- cfg := &Config{APITokens: nil}- if cfg.HasAPITokens() {- t.Error("expected false for nil tokens")- }-- cfg.APITokens = []APITokenRecord{}- if cfg.HasAPITokens() {- t.Error("expected false for empty tokens")- }- })-- t.Run("non-empty slice returns true", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "test", Hash: "hash"},- },- }- if !cfg.HasAPITokens() {- t.Error("expected true for non-empty tokens")- }- })-}--func TestAPITokenCount(t *testing.T) {- t.Run("empty returns 0", func(t *testing.T) {- cfg := &Config{APITokens: nil}- if cfg.APITokenCount() != 0 {- t.Errorf("expected 0, got %d", cfg.APITokenCount())- }- })-- t.Run("returns correct count", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: "hash1"},- {ID: "2", Hash: "hash2"},- {ID: "3", Hash: "hash3"},- },- }- if cfg.APITokenCount() != 3 {- t.Errorf("expected 3, got %d", cfg.APITokenCount())- }- })-}--func TestActiveAPITokenHashes(t *testing.T) {- t.Run("empty tokens returns empty slice", func(t *testing.T) {- cfg := &Config{APITokens: nil}- hashes := cfg.ActiveAPITokenHashes()- if len(hashes) != 0 {- t.Errorf("expected empty slice, got %v", hashes)- }- })-- t.Run("skips records with empty hash", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: "hash1"},- {ID: "2", Hash: ""},- {ID: "3", Hash: "hash3"},- },- }- hashes := cfg.ActiveAPITokenHashes()- if len(hashes) != 2 {- t.Fatalf("expected 2 hashes, got %d", len(hashes))- }- if hashes[0] != "hash1" || hashes[1] != "hash3" {- t.Errorf("expected [hash1, hash3], got %v", hashes)- }- })-- t.Run("returns all valid hashes", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: "hash1"},- {ID: "2", Hash: "hash2"},- },- }- hashes := cfg.ActiveAPITokenHashes()- if len(hashes) != 2 {- t.Fatalf("expected 2 hashes, got %d", len(hashes))- }- })-}--func TestHasAPITokenHash(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: "existing-hash"},- {ID: "2", Hash: "another-hash"},- },- }-- t.Run("returns true when hash exists", func(t *testing.T) {- if !cfg.HasAPITokenHash("existing-hash") {- t.Error("expected true for existing hash")- }- if !cfg.HasAPITokenHash("another-hash") {- t.Error("expected true for another existing hash")- }- })-- t.Run("returns false when hash doesn't exist", func(t *testing.T) {- if cfg.HasAPITokenHash("nonexistent") {- t.Error("expected false for nonexistent hash")- }- })-- t.Run("returns false for empty config", func(t *testing.T) {- emptyCfg := &Config{}- if emptyCfg.HasAPITokenHash("any-hash") {- t.Error("expected false for empty config")- }- })-}--func TestPrimaryAPITokenHash(t *testing.T) {- t.Run("empty tokens returns empty string", func(t *testing.T) {- cfg := &Config{APITokens: nil}- if cfg.PrimaryAPITokenHash() != "" {- t.Errorf("expected empty string, got %q", cfg.PrimaryAPITokenHash())- }- })-- t.Run("returns first token's hash", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: "first-hash"},- {ID: "2", Hash: "second-hash"},- },- }- if cfg.PrimaryAPITokenHash() != "first-hash" {- t.Errorf("expected first-hash, got %q", cfg.PrimaryAPITokenHash())- }- })-}--func TestPrimaryAPITokenHint(t *testing.T) {- t.Run("empty tokens returns empty string", func(t *testing.T) {- cfg := &Config{APITokens: nil}- if cfg.PrimaryAPITokenHint() != "" {- t.Errorf("expected empty string, got %q", cfg.PrimaryAPITokenHint())- }- })-- t.Run("returns prefix...suffix format when both exist", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Prefix: "abcdef", Suffix: "wxyz"},- },- }- expected := "abcdef...wxyz"- if cfg.PrimaryAPITokenHint() != expected {- t.Errorf("expected %q, got %q", expected, cfg.PrimaryAPITokenHint())- }- })-- t.Run("falls back to hash truncation when no prefix", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: "12345678abcdefgh", Prefix: "", Suffix: "wxyz"},- },- }- expected := "1234...efgh"- if cfg.PrimaryAPITokenHint() != expected {- t.Errorf("expected %q, got %q", expected, cfg.PrimaryAPITokenHint())- }- })-- t.Run("falls back to hash truncation when no suffix", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: "12345678abcdefgh", Prefix: "abcdef", Suffix: ""},- },- }- expected := "1234...efgh"- if cfg.PrimaryAPITokenHint() != expected {- t.Errorf("expected %q, got %q", expected, cfg.PrimaryAPITokenHint())- }- })-- t.Run("returns empty for short hash without prefix/suffix", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: "short", Prefix: "", Suffix: ""},- },- }- if cfg.PrimaryAPITokenHint() != "" {- t.Errorf("expected empty string for short hash, got %q", cfg.PrimaryAPITokenHint())- }- })-}--func TestValidateAPIToken(t *testing.T) {- rawToken := "my-secret-api-token-123"- hashedToken := auth.HashAPIToken(rawToken)-- t.Run("empty token returns nil, false", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: hashedToken, Scopes: []string{ScopeWildcard}},- },- }- record, valid := cfg.ValidateAPIToken("")- if record != nil || valid {- t.Error("expected nil, false for empty token")- }- })-- t.Run("invalid token returns nil, false", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: hashedToken, Scopes: []string{ScopeWildcard}},- },- }- record, valid := cfg.ValidateAPIToken("wrong-token")- if record != nil || valid {- t.Error("expected nil, false for invalid token")- }- })-- t.Run("valid token returns record, true and updates LastUsedAt", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: hashedToken, Scopes: []string{ScopeMonitoringRead}},- },- }-- before := time.Now().UTC()- record, valid := cfg.ValidateAPIToken(rawToken)- after := time.Now().UTC()-- if !valid {- t.Fatal("expected valid=true")- }- if record == nil {- t.Fatal("expected non-nil record")- }- if record.ID != "1" {- t.Errorf("expected ID=1, got %q", record.ID)- }- if record.LastUsedAt == nil {- t.Fatal("LastUsedAt should be set")- }- if record.LastUsedAt.Before(before) || record.LastUsedAt.After(after) {- t.Errorf("LastUsedAt should be between %v and %v, got %v", before, after, *record.LastUsedAt)- }-- // Verify the config's record was also updated- if cfg.APITokens[0].LastUsedAt == nil {- t.Error("config's record LastUsedAt should be updated")- }- })-- t.Run("validates against multiple tokens", func(t *testing.T) {- token2 := "another-token-456"- hash2 := auth.HashAPIToken(token2)-- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: hashedToken, Scopes: []string{ScopeWildcard}},- {ID: "2", Hash: hash2, Scopes: []string{ScopeMonitoringRead}},- },- }-- record, valid := cfg.ValidateAPIToken(token2)- if !valid {- t.Fatal("expected valid=true for second token")- }- if record.ID != "2" {- t.Errorf("expected ID=2, got %q", record.ID)- }- })-- t.Run("empty config returns nil, false", func(t *testing.T) {- cfg := &Config{}- record, valid := cfg.ValidateAPIToken(rawToken)- if record != nil || valid {- t.Error("expected nil, false for empty config")- }- })-}--func TestUpsertAPIToken(t *testing.T) {- t.Run("insert new token", func(t *testing.T) {- cfg := &Config{}- record := APITokenRecord{- ID: "new-id",- Name: "New Token",- Hash: "new-hash",- CreatedAt: time.Now().UTC(),- }-- cfg.UpsertAPIToken(record)-- if len(cfg.APITokens) != 1 {- t.Fatalf("expected 1 token, got %d", len(cfg.APITokens))- }- if cfg.APITokens[0].ID != "new-id" {- t.Errorf("expected ID=new-id, got %q", cfg.APITokens[0].ID)- }- // Should have normalized scopes- if len(cfg.APITokens[0].Scopes) != 1 || cfg.APITokens[0].Scopes[0] != ScopeWildcard {- t.Errorf("expected wildcard scope, got %v", cfg.APITokens[0].Scopes)- }- })-- t.Run("update existing token by ID", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "existing", Name: "Old Name", Hash: "old-hash", CreatedAt: time.Now().UTC()},- },- }-- updated := APITokenRecord{- ID: "existing",- Name: "Updated Name",- Hash: "updated-hash",- CreatedAt: time.Now().UTC(),- Scopes: []string{ScopeMonitoringRead},- }- cfg.UpsertAPIToken(updated)-- if len(cfg.APITokens) != 1 {- t.Fatalf("expected 1 token after update, got %d", len(cfg.APITokens))- }- if cfg.APITokens[0].Name != "Updated Name" {- t.Errorf("expected name to be updated, got %q", cfg.APITokens[0].Name)- }- if cfg.APITokens[0].Hash != "updated-hash" {- t.Errorf("expected hash to be updated, got %q", cfg.APITokens[0].Hash)- }- })-- t.Run("sorting happens after upsert", func(t *testing.T) {- older := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)- newer := time.Date(2024, 6, 1, 0, 0, 0, 0, time.UTC)-- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "older", Name: "Older", Hash: "hash1", CreatedAt: older},- },- }-- cfg.UpsertAPIToken(APITokenRecord{- ID: "newer",- Name: "Newer",- Hash: "hash2",- CreatedAt: newer,- })-- if len(cfg.APITokens) != 2 {- t.Fatalf("expected 2 tokens, got %d", len(cfg.APITokens))- }- // Newest should be first- if cfg.APITokens[0].ID != "newer" {- t.Errorf("expected newest token first, got %q", cfg.APITokens[0].ID)- }- if cfg.APITokens[1].ID != "older" {- t.Errorf("expected older token second, got %q", cfg.APITokens[1].ID)- }- })-}--func TestRemoveAPIToken(t *testing.T) {- t.Run("remove existing returns record", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "keep", Hash: "hash1"},- {ID: "remove", Hash: "hash2"},- {ID: "also-keep", Hash: "hash3"},- },- }-- removed := cfg.RemoveAPIToken("remove")- 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))- }- // Verify the correct token was removed- for _, token := range cfg.APITokens {- if token.ID == "remove" {- t.Error("removed token should not be in list")- }- }- })-- t.Run("remove non-existing returns nil", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "existing", Hash: "hash1"},- },- }-- removed := cfg.RemoveAPIToken("nonexistent")- 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 nil", func(t *testing.T) {- cfg := &Config{}- removed := cfg.RemoveAPIToken("any")- 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))- }- })-}--func TestSortAPITokens(t *testing.T) {- t.Run("sorts newest first", func(t *testing.T) {- oldest := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)- middle := time.Date(2024, 6, 1, 0, 0, 0, 0, time.UTC)- newest := time.Date(2024, 12, 1, 0, 0, 0, 0, time.UTC)-- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "middle", Hash: "hash2", CreatedAt: middle},- {ID: "oldest", Hash: "hash1", CreatedAt: oldest},- {ID: "newest", Hash: "hash3", CreatedAt: newest},- },- }-- cfg.SortAPITokens()-- if cfg.APITokens[0].ID != "newest" {- t.Errorf("expected newest first, got %q", cfg.APITokens[0].ID)- }- if cfg.APITokens[1].ID != "middle" {- t.Errorf("expected middle second, got %q", cfg.APITokens[1].ID)- }- if cfg.APITokens[2].ID != "oldest" {- t.Errorf("expected oldest last, got %q", cfg.APITokens[2].ID)- }- })-- t.Run("updates legacy APIToken field", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: "primary-hash", CreatedAt: time.Now().UTC()},- },- }-- cfg.SortAPITokens()-- if cfg.APIToken != "primary-hash" {- t.Errorf("expected APIToken to be set to primary hash, got %q", cfg.APIToken)- }- })-- t.Run("empty tokens clears APIToken", func(t *testing.T) {- cfg := &Config{- APIToken: "old-value",- APITokens: []APITokenRecord{},- }-- cfg.SortAPITokens()-- if cfg.APIToken != "" {- t.Errorf("expected APIToken to be cleared, got %q", cfg.APIToken)- }- })-- t.Run("normalizes scopes for all tokens", func(t *testing.T) {- cfg := &Config{- APITokens: []APITokenRecord{- {ID: "1", Hash: "hash1", CreatedAt: time.Now().UTC(), Scopes: nil},- {ID: "2", Hash: "hash2", CreatedAt: time.Now().UTC(), Scopes: []string{}},- },- }-- cfg.SortAPITokens()-- for i, token := range cfg.APITokens {- if len(token.Scopes) != 1 || token.Scopes[0] != ScopeWildcard {- t.Errorf("token %d: expected wildcard scope, got %v", i, token.Scopes)- }- }+ t.Run("Multi Org Token", func(t *testing.T) {+ token := APITokenRecord{OrgIDs: []string{"org-1", "org-2"}}+ assert.Equal(t, []string{"org-1", "org-2"}, token.GetBoundOrgs())})}diff --git a/internal/config/config.go b/internal/config/config.goindex 5399eb7e7c..6834607ef7 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -145,6 +145,7 @@ type Config struct {AllowedOrigins string `envconfig:"ALLOWED_ORIGINS" default:"*"`HideLocalLogin bool `envconfig:"PULSE_AUTH_HIDE_LOCAL_LOGIN" default:"false"`DisableDockerUpdateActions bool `envconfig:"PULSE_DISABLE_DOCKER_UPDATE_ACTIONS" default:"false"` // Hide Docker update buttons (read-only mode for containers)+ MultiTenantEnabled bool `envconfig:"PULSE_MULTI_TENANT_ENABLED" default:"false"` // Enable multi-tenant support// Proxy authentication settingsProxyAuthSecret string `envconfig:"PROXY_AUTH_SECRET"`@@ -220,6 +221,69 @@ func CloneDiscoveryConfig(cfg DiscoveryConfig) DiscoveryConfig {return clone}+// DeepCopy creates a deep copy of the Config struct.+// This is important for tenant isolation to ensure each tenant+// has independent config data that won't be shared.+func (c *Config) DeepCopy() *Config {+ if c == nil {+ return nil+ }++ // Start with a shallow copy+ clone := *c++ // Deep copy PVEInstances slice+ if len(c.PVEInstances) > 0 {+ clone.PVEInstances = make([]PVEInstance, len(c.PVEInstances))+ copy(clone.PVEInstances, c.PVEInstances)+ }++ // Deep copy PBSInstances slice+ if len(c.PBSInstances) > 0 {+ clone.PBSInstances = make([]PBSInstance, len(c.PBSInstances))+ copy(clone.PBSInstances, c.PBSInstances)+ }++ // Deep copy PMGInstances slice+ if len(c.PMGInstances) > 0 {+ clone.PMGInstances = make([]PMGInstance, len(c.PMGInstances))+ copy(clone.PMGInstances, c.PMGInstances)+ }++ // Deep copy APITokens slice+ if len(c.APITokens) > 0 {+ clone.APITokens = make([]APITokenRecord, len(c.APITokens))+ for i, token := range c.APITokens {+ clone.APITokens[i] = token.Clone()+ }+ }++ // Deep copy SuppressedEnvMigrations slice+ if len(c.SuppressedEnvMigrations) > 0 {+ clone.SuppressedEnvMigrations = make([]string, len(c.SuppressedEnvMigrations))+ copy(clone.SuppressedEnvMigrations, c.SuppressedEnvMigrations)+ }++ // Deep copy EnvOverrides map+ if len(c.EnvOverrides) > 0 {+ clone.EnvOverrides = make(map[string]bool, len(c.EnvOverrides))+ for k, v := range c.EnvOverrides {+ clone.EnvOverrides[k] = v+ }+ }++ // Deep copy Discovery config+ clone.Discovery = CloneDiscoveryConfig(c.Discovery)++ // Deep copy OIDC config if present using the Clone method+ // which properly deep copies all slices and maps+ if c.OIDC != nil {+ clone.OIDC = c.OIDC.Clone()+ }++ return &clone+}+// NormalizeDiscoveryConfig ensures a discovery config contains sane values and defaults.func NormalizeDiscoveryConfig(cfg DiscoveryConfig) DiscoveryConfig {defaults := DefaultDiscoveryConfig()diff --git a/internal/config/migration.go b/internal/config/migration.gonew file mode 100644index 0000000000..f34acc6823--- /dev/null+++ b/internal/config/migration.go@@ -0,0 +1,195 @@+package config++import (+ "fmt"+ "os"+ "path/filepath"+ "time"++ "github.com/rs/zerolog/log"+)++// MigrationStatus tracks the status of a data migration.+type MigrationStatus struct {+ Version string `json:"version"`+ MigratedAt time.Time `json:"migratedAt"`+ SourceFiles []string `json:"sourceFiles"`+ TargetDir string `json:"targetDir"`+}++// filesToMigrate lists files that should be moved to the default org directory.+// NOTE: This migration is currently dormant - RunMigrationIfNeeded is not called anywhere.+// If enabled in the future, .encryption.key should be added to this list FIRST.+var filesToMigrate = []string{+ "nodes.enc",+ "system.json",+ "alerts.json",+ "notifications.json",+ "audit.db",+}++// MigrateToMultiTenant migrates existing data to the multi-tenant directory structure.+// It moves files from the root data directory to /orgs/default/ and creates symlinks+// for backward compatibility.+//+// Migration structure:+//+// /data/+// orgs/+// default/+// nodes.enc <- moved from /data/nodes.enc+// system.json <- moved from /data/system.json+// alerts.json <- moved from /data/alerts.json+// nodes.enc <- symlink to orgs/default/nodes.enc+// system.json <- symlink to orgs/default/system.json+// alerts.json <- symlink to orgs/default/alerts.json+func MigrateToMultiTenant(dataDir string) error {+ if dataDir == "" {+ return fmt.Errorf("data directory cannot be empty")+ }++ // Check if migration is needed+ defaultOrgDir := filepath.Join(dataDir, "orgs", "default")+ migrationMarker := filepath.Join(defaultOrgDir, ".migrated")++ // If migration marker exists, migration has already been completed+ if _, err := os.Stat(migrationMarker); err == nil {+ log.Debug().Str("data_dir", dataDir).Msg("Multi-tenant migration already completed")+ return nil+ }++ log.Info().Str("data_dir", dataDir).Msg("Starting multi-tenant data migration")++ // Create the default org directory+ if err := os.MkdirAll(defaultOrgDir, 0755); err != nil {+ return fmt.Errorf("failed to create default org directory: %w", err)+ }++ migratedFiles := []string{}+ skippedFiles := []string{}++ // Migrate each file+ for _, filename := range filesToMigrate {+ srcPath := filepath.Join(dataDir, filename)+ dstPath := filepath.Join(defaultOrgDir, filename)++ // Check if source file exists+ srcInfo, err := os.Lstat(srcPath)+ if os.IsNotExist(err) {+ log.Debug().Str("file", filename).Msg("File does not exist, skipping")+ skippedFiles = append(skippedFiles, filename)+ continue+ }+ if err != nil {+ log.Warn().Err(err).Str("file", filename).Msg("Error checking source file, skipping")+ skippedFiles = append(skippedFiles, filename)+ continue+ }++ // Skip if source is already a symlink (already migrated)+ if srcInfo.Mode()&os.ModeSymlink != 0 {+ log.Debug().Str("file", filename).Msg("File is already a symlink, skipping")+ skippedFiles = append(skippedFiles, filename)+ continue+ }++ // Check if destination already exists+ if _, err := os.Stat(dstPath); err == nil {+ log.Warn().Str("file", filename).Msg("Destination already exists, skipping")+ skippedFiles = append(skippedFiles, filename)+ continue+ }++ // Move the file+ if err := os.Rename(srcPath, dstPath); err != nil {+ // If rename fails (cross-device), try copy + delete+ if err := copyFile(srcPath, dstPath); err != nil {+ log.Error().Err(err).Str("file", filename).Msg("Failed to migrate file")+ continue+ }+ if err := os.Remove(srcPath); err != nil {+ log.Warn().Err(err).Str("file", filename).Msg("Failed to remove original file after copy")+ }+ }++ log.Info().Str("file", filename).Msg("Migrated file to default org directory")+ migratedFiles = append(migratedFiles, filename)++ // Create symlink for backward compatibility+ relPath, _ := filepath.Rel(dataDir, dstPath)+ if err := os.Symlink(relPath, srcPath); err != nil {+ log.Warn().Err(err).Str("file", filename).Msg("Failed to create symlink for backward compatibility")+ } else {+ log.Debug().Str("file", filename).Str("target", relPath).Msg("Created symlink for backward compatibility")+ }+ }++ // Create migration marker+ markerContent := fmt.Sprintf("migrated_at=%s\nversion=1.0\nmigrated_files=%d\nskipped_files=%d\n",+ time.Now().Format(time.RFC3339), len(migratedFiles), len(skippedFiles))+ if err := os.WriteFile(migrationMarker, []byte(markerContent), 0644); err != nil {+ log.Warn().Err(err).Msg("Failed to write migration marker")+ }++ log.Info().+ Int("migrated", len(migratedFiles)).+ Int("skipped", len(skippedFiles)).+ Str("data_dir", dataDir).+ Msg("Multi-tenant data migration completed")++ return nil+}++// copyFile copies a file from src to dst.+func copyFile(src, dst string) error {+ data, err := os.ReadFile(src)+ if err != nil {+ return err+ }++ // Get original file permissions+ info, err := os.Stat(src)+ if err != nil {+ return err+ }++ return os.WriteFile(dst, data, info.Mode())+}++// IsMigrationNeeded checks if multi-tenant migration is needed.+func IsMigrationNeeded(dataDir string) bool {+ if dataDir == "" {+ return false+ }++ defaultOrgDir := filepath.Join(dataDir, "orgs", "default")+ migrationMarker := filepath.Join(defaultOrgDir, ".migrated")++ // If marker exists, migration is not needed+ if _, err := os.Stat(migrationMarker); err == nil {+ return false+ }++ // Check if any files to migrate exist+ for _, filename := range filesToMigrate {+ srcPath := filepath.Join(dataDir, filename)+ info, err := os.Lstat(srcPath)+ if err != nil {+ continue+ }+ // File exists and is not a symlink - migration needed+ if info.Mode()&os.ModeSymlink == 0 {+ return true+ }+ }++ return false+}++// RunMigrationIfNeeded checks if migration is needed and runs it.+func RunMigrationIfNeeded(dataDir string) error {+ if !IsMigrationNeeded(dataDir) {+ return nil+ }+ return MigrateToMultiTenant(dataDir)+}diff --git a/internal/config/migration_test.go b/internal/config/migration_test.gonew file mode 100644index 0000000000..b822f9c4c8--- /dev/null+++ b/internal/config/migration_test.go@@ -0,0 +1,62 @@+package config++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestMigrateToMultiTenant(t *testing.T) {+ // Setup temp dir+ dataDir := t.TempDir()++ // Create dummy legacy files+ legacyFiles := []string{"nodes.enc", "system.json", "alerts.json"}+ for _, f := range legacyFiles {+ err := os.WriteFile(filepath.Join(dataDir, f), []byte("dummy content"), 0644)+ require.NoError(t, err)+ }++ // Run migration+ err := MigrateToMultiTenant(dataDir)+ require.NoError(t, err)++ // Verify files moved to default org+ defaultOrgDir := filepath.Join(dataDir, "orgs", "default")+ for _, f := range legacyFiles {+ // Check file exists in new location+ content, err := os.ReadFile(filepath.Join(defaultOrgDir, f))+ require.NoError(t, err, "File %s should exist in default org dir", f)+ require.Equal(t, "dummy content", string(content))++ // Check symlink exists in old location+ info, err := os.Lstat(filepath.Join(dataDir, f))+ require.NoError(t, err, "Symlink %s should exist in root data dir", f)+ require.Equal(t, os.ModeSymlink, info.Mode()&os.ModeSymlink, "%s should be a symlink", f)+ }++ // Verify marker+ _, err = os.Stat(filepath.Join(defaultOrgDir, ".migrated"))+ require.NoError(t, err, "Migration marker should exist")++ // Run again (should be idempotent)+ err = MigrateToMultiTenant(dataDir)+ require.NoError(t, err)+}++func TestIsMigrationNeeded(t *testing.T) {+ dataDir := t.TempDir()++ // Empty dir - no migration needed+ require.False(t, IsMigrationNeeded(dataDir))++ // With files - migration needed+ os.WriteFile(filepath.Join(dataDir, "system.json"), []byte("{}"), 0644)+ require.True(t, IsMigrationNeeded(dataDir))++ // After migration - not needed+ MigrateToMultiTenant(dataDir)+ require.False(t, IsMigrationNeeded(dataDir))+}diff --git a/internal/config/multi_tenant.go b/internal/config/multi_tenant.goindex 09103afe9e..f56bdfad5d 100644--- a/internal/config/multi_tenant.go+++ b/internal/config/multi_tenant.go@@ -54,7 +54,9 @@ func (mtp *MultiTenantPersistence) GetPersistence(orgID string) (*ConfigPersiste// New orgs use /data/orgs/<org-id>var orgDir stringif orgID == "default" {- orgDir = filepath.Join(mtp.baseDataDir, "orgs", "default")+ // IMPORTANT: Default org uses root data dir for backward compatibility+ // This ensures existing users' configs (nodes.enc, ai.enc, etc.) continue to work+ orgDir = mtp.baseDataDir} else {orgDir = filepath.Join(mtp.baseDataDir, "orgs", orgID)}diff --git a/internal/config/persistence.go b/internal/config/persistence.goindex 08e53fdd5e..d1cc90937f 100644--- a/internal/config/persistence.go+++ b/internal/config/persistence.go@@ -42,6 +42,7 @@ type ConfigPersistence struct {agentProfilesFile stringagentAssignmentsFile stringaiChatSessionsFile string+ orgFile stringcrypto *crypto.CryptoManagerfs FileSystem@@ -125,6 +126,7 @@ func newConfigPersistence(configDir string) (*ConfigPersistence, error) {agentProfilesFile: filepath.Join(configDir, "agent_profiles.json"),agentAssignmentsFile: filepath.Join(configDir, "agent_profile_assignments.json"),aiChatSessionsFile: filepath.Join(configDir, "ai_chat_sessions.json"),+ orgFile: filepath.Join(configDir, "org.json"),crypto: cryptoMgr,fs: defaultFileSystem{},}@@ -149,6 +151,45 @@ func (c *ConfigPersistence) GetConfigDir() string {return c.configDir}+// LoadOrganization loads the organization metadata from org.json.+func (c *ConfigPersistence) LoadOrganization() (*models.Organization, error) {+ c.mu.RLock()+ defer c.mu.RUnlock()++ data, err := c.fs.ReadFile(c.orgFile)+ if err != nil {+ if os.IsNotExist(err) {+ return nil, err+ }+ return nil, fmt.Errorf("failed to read org file: %w", err)+ }++ var org models.Organization+ if err := json.Unmarshal(data, &org); err != nil {+ return nil, fmt.Errorf("failed to parse org file: %w", err)+ }++ return &org, nil+}++// SaveOrganization saves the organization metadata to org.json.+func (c *ConfigPersistence) SaveOrganization(org *models.Organization) error {+ c.mu.Lock()+ defer c.mu.Unlock()++ data, err := json.MarshalIndent(org, "", " ")+ if err != nil {+ return fmt.Errorf("failed to serialize org: %w", err)+ }++ if err := c.fs.WriteFile(c.orgFile, data, 0600); err != nil {+ return fmt.Errorf("failed to write org file: %w", err)+ }++ log.Debug().Str("org_id", org.ID).Msg("Saved organization metadata")+ return nil+}+// EnsureConfigDir ensures the configuration directory existsfunc (c *ConfigPersistence) EnsureConfigDir() error {return c.fs.MkdirAll(c.configDir, 0700)@@ -422,6 +463,26 @@ func (c *ConfigPersistence) SaveAlertConfig(config alerts.AlertConfig) error {if config.BackupDefaults.CriticalDays > 0 && config.BackupDefaults.WarningDays > config.BackupDefaults.CriticalDays {config.BackupDefaults.WarningDays = config.BackupDefaults.CriticalDays}+ if config.BackupDefaults.AlertOrphaned == nil {+ alertOrphaned := true+ config.BackupDefaults.AlertOrphaned = &alertOrphaned+ }+ if len(config.BackupDefaults.IgnoreVMIDs) > 0 {+ seen := make(map[string]struct{}, len(config.BackupDefaults.IgnoreVMIDs))+ normalized := make([]string, 0, len(config.BackupDefaults.IgnoreVMIDs))+ for _, entry := range config.BackupDefaults.IgnoreVMIDs {+ value := strings.TrimSpace(entry)+ if value == "" {+ continue+ }+ if _, exists := seen[value]; exists {+ continue+ }+ seen[value] = struct{}{}+ normalized = append(normalized, value)+ }+ config.BackupDefaults.IgnoreVMIDs = normalized+ }config.DockerIgnoredContainerPrefixes = alerts.NormalizeDockerIgnoredPrefixes(config.DockerIgnoredContainerPrefixes)data, err := json.Marshal(config)@@ -446,6 +507,7 @@ func (c *ConfigPersistence) LoadAlertConfig() (*alerts.AlertConfig, error) {c.mu.RLock()defer c.mu.RUnlock()+ alertOrphaned := truedata, err := c.fs.ReadFile(c.alertFile)if err != nil {if os.IsNotExist(err) {@@ -487,11 +549,13 @@ func (c *ConfigPersistence) LoadAlertConfig() (*alerts.AlertConfig, error) {CriticalSizeGiB: 0,},BackupDefaults: alerts.BackupAlertConfig{- Enabled: false,- WarningDays: 7,- CriticalDays: 14,- FreshHours: 24,- StaleHours: 72,+ Enabled: false,+ WarningDays: 7,+ CriticalDays: 14,+ FreshHours: 24,+ StaleHours: 72,+ AlertOrphaned: &alertOrphaned,+ IgnoreVMIDs: []string{},},Overrides: make(map[string]alerts.ThresholdConfig),}, nil@@ -634,6 +698,26 @@ func (c *ConfigPersistence) LoadAlertConfig() (*alerts.AlertConfig, error) {if config.BackupDefaults.StaleHours < config.BackupDefaults.FreshHours {config.BackupDefaults.StaleHours = config.BackupDefaults.FreshHours}+ if config.BackupDefaults.AlertOrphaned == nil {+ alertOrphaned := true+ config.BackupDefaults.AlertOrphaned = &alertOrphaned+ }+ if len(config.BackupDefaults.IgnoreVMIDs) > 0 {+ seen := make(map[string]struct{}, len(config.BackupDefaults.IgnoreVMIDs))+ normalized := make([]string, 0, len(config.BackupDefaults.IgnoreVMIDs))+ for _, entry := range config.BackupDefaults.IgnoreVMIDs {+ value := strings.TrimSpace(entry)+ if value == "" {+ continue+ }+ if _, exists := seen[value]; exists {+ continue+ }+ seen[value] = struct{}{}+ normalized = append(normalized, value)+ }+ config.BackupDefaults.IgnoreVMIDs = normalized+ }config.MetricTimeThresholds = alerts.NormalizeMetricTimeThresholds(config.MetricTimeThresholds)config.DockerIgnoredContainerPrefixes = alerts.NormalizeDockerIgnoredPrefixes(config.DockerIgnoredContainerPrefixes)@@ -1691,7 +1775,11 @@ func (c *ConfigPersistence) LoadAIConfig() (*AIConfig, error) {// Migration: Ensure patrol settings have sensible defaults for existing configs// PatrolIntervalMinutes=0 means it was never set - use defaultif settings.PatrolIntervalMinutes <= 0 {- settings.PatrolIntervalMinutes = 15+ if !settings.PatrolEnabled || strings.EqualFold(settings.PatrolSchedulePreset, "disabled") {+ settings.PatrolIntervalMinutes = 0+ } else {+ settings.PatrolIntervalMinutes = 360+ }}migratedControlLevel := false@@ -1751,6 +1839,13 @@ type AIFindingRecord struct {UserNote string `json:"user_note,omitempty"`TimesRaised int `json:"times_raised"`Suppressed bool `json:"suppressed"`++ // Investigation fields - tracks autonomous AI investigation of findings+ InvestigationSessionID string `json:"investigation_session_id,omitempty"`+ InvestigationStatus string `json:"investigation_status,omitempty"`+ InvestigationOutcome string `json:"investigation_outcome,omitempty"`+ LastInvestigatedAt *time.Time `json:"last_investigated_at,omitempty"`+ InvestigationAttempts int `json:"investigation_attempts"`}// SaveAIFindings persists AI findings to disk@@ -1763,7 +1858,7 @@ func (c *ConfigPersistence) SaveAIFindings(findings map[string]*AIFindingRecord)}data := AIFindingsData{- Version: 1,+ Version: 2, // Bumped from 1: finding IDs now include issue keyLastSaved: time.Now(),Findings: findings,}@@ -1793,15 +1888,16 @@ func (c *ConfigPersistence) SetFileSystem(fs FileSystem) {// LoadAIFindings loads AI findings from diskfunc (c *ConfigPersistence) LoadAIFindings() (*AIFindingsData, error) {+ // Read file under read lockc.mu.RLock()- defer c.mu.RUnlock()-data, err := c.fs.ReadFile(c.aiFindingsFile)+ c.mu.RUnlock()+if err != nil {if os.IsNotExist(err) {// Return empty data if file doesn't existreturn &AIFindingsData{- Version: 1,+ Version: 2,Findings: make(map[string]*AIFindingRecord),}, nil}@@ -1813,7 +1909,7 @@ func (c *ConfigPersistence) LoadAIFindings() (*AIFindingsData, error) {log.Error().Err(err).Str("file", c.aiFindingsFile).Msg("Failed to parse AI findings file")// Return empty data on parse error rather than failingreturn &AIFindingsData{- Version: 1,+ Version: 2,Findings: make(map[string]*AIFindingRecord),}, nil}@@ -1822,6 +1918,30 @@ func (c *ConfigPersistence) LoadAIFindings() (*AIFindingsData, error) {findingsData.Findings = make(map[string]*AIFindingRecord)}+ // Version 2 changed finding ID format to include issue key.+ // Clear old findings since IDs are incompatible, and persist immediately.+ if findingsData.Version < 2 {+ oldCount := len(findingsData.Findings)+ findingsData.Findings = make(map[string]*AIFindingRecord)+ findingsData.Version = 2+ findingsData.LastSaved = time.Now()++ if oldCount > 0 {+ log.Info().+ Int("cleared_count", oldCount).+ Msg("AI findings cleared due to schema upgrade (v1 -> v2)")+ }++ // Persist the migrated (empty) v2 file immediately to avoid re-migrating on restart+ c.mu.Lock()+ if jsonData, err := json.Marshal(findingsData); err == nil {+ if err := c.writeConfigFileLocked(c.aiFindingsFile, jsonData, 0600); err != nil {+ log.Warn().Err(err).Msg("Failed to persist migrated AI findings file")+ }+ }+ c.mu.Unlock()+ }+log.Info().Str("file", c.aiFindingsFile).Int("count", len(findingsData.Findings)).diff --git a/internal/config/persistence_ai_branches_test.go b/internal/config/persistence_ai_branches_test.goindex 315efc09fe..565abdd1d4 100644--- a/internal/config/persistence_ai_branches_test.go+++ b/internal/config/persistence_ai_branches_test.go@@ -45,7 +45,7 @@ func TestLoadAIConfig_Branches(t *testing.T) {settings, err := cp.LoadAIConfig()assert.NoError(t, err)- assert.Equal(t, 15, settings.PatrolIntervalMinutes)+ assert.Equal(t, 360, settings.PatrolIntervalMinutes)}func TestLoadAIFindings_Branches(t *testing.T) {