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
Apply configuration imports only to the selected tenant runtime
pulse-triage[bot]d141bd540494
diff --git a/internal/api/config_import_tenant_runtime_test.go b/internal/api/config_import_tenant_runtime_test.goindex 087c99e484..c28f2856ce 100644--- a/internal/api/config_import_tenant_runtime_test.go+++ b/internal/api/config_import_tenant_runtime_test.go@@ -67,6 +67,9 @@ func TestConfigImportAppliesOnlySelectedTenant(t *testing.T) {beforeDefault := cfg.DeepCopy()beforeOther := monitors["tenant-b"].GetConfig().DeepCopy()filesBefore := configImportFileDigests(t, persistences["default"], persistences["tenant-b"])+ for _, orgID := range []string{"default", "tenant-a", "tenant-b"} {+ logConfigImportSettings(t, router, orgID, "before")+ }source := config.NewConfigPersistence(t.TempDir())seedConfigImportRuntime(t, source, "restored", "tenant-a", 137)@@ -126,6 +129,31 @@ func TestConfigImportAppliesOnlySelectedTenant(t *testing.T) {if err != nil || len(persistedNodes.PVEInstances) != 1 || persistedNodes.PVEInstances[0].Name != "restored" {t.Error("selected tenant archive was not persisted")}+ // Imported credentials must be immediately usable in the selected scope,+ // not only present in a struct or saved for the next process restart.+ for _, check := range []struct {+ orgID, token string+ allowed bool+ }{+ {"tenant-a", "synthetic-restored-api-token.12345678", true},+ {"tenant-a", "synthetic-tenant-a-api-token.12345678", false},+ {"tenant-b", "synthetic-restored-api-token.12345678", false},+ {"default", "synthetic-restored-api-token.12345678", false},+ {"tenant-b", "synthetic-tenant-b-api-token.12345678", true},+ {"default", "synthetic-default-api-token.12345678", true},+ } {+ r := httptest.NewRequest(http.MethodGet, "/api/system/settings", nil)+ r.Header.Set("X-Pulse-Org-ID", check.orgID)+ r.Header.Set("X-API-Token", check.token)+ response := httptest.NewRecorder()+ router.Handler().ServeHTTP(response, r)+ if (response.Code == http.StatusOK) != check.allowed {+ t.Errorf("post-import token access for %s = %d; allowed=%v", check.orgID, response.Code, check.allowed)+ }+ }+ for _, orgID := range []string{"default", "tenant-a", "tenant-b"} {+ logConfigImportSettings(t, router, orgID, "after")+ }// These are the same producers the existing settings page consumes.ctx := context.WithValue(context.Background(), apicontext.OrgIDContextKey, "tenant-a")settingsRec := httptest.NewRecorder()@@ -174,3 +202,16 @@ func configImportFileDigests(t *testing.T, persistences ...*config.ConfigPersist}return digests}++// These readbacks contain only synthetic public settings, never archive/token+// material. Verbose regression logs make runtime-versus-persistence drift clear.+func logConfigImportSettings(t *testing.T, router *Router, orgID, phase string) {+ t.Helper()+ ctx := context.WithValue(context.Background(), apicontext.OrgIDContextKey, orgID)+ rec := httptest.NewRecorder()+ router.configHandlers.HandleGetSystemSettings(rec, httptest.NewRequest(http.MethodGet, "/api/system/settings", nil).WithContext(ctx))+ if rec.Code != http.StatusOK {+ t.Fatalf("%s settings readback failed: %d", orgID, rec.Code)+ }+ t.Logf("SYNTHETIC_SETTINGS_READBACK %s %s %s", phase, orgID, bytes.TrimSpace(rec.Body.Bytes()))+}diff --git a/internal/api/configapi/config_export_import_handlers.go b/internal/api/configapi/config_export_import_handlers.goindex c40fb898a3..cc3a9e7fb1 100644--- a/internal/api/configapi/config_export_import_handlers.go+++ b/internal/api/configapi/config_export_import_handlers.go@@ -106,12 +106,25 @@ func (h *ConfigHandlers) handleImportConfig(w http.ResponseWriter, r *http.Requereturn}+ // Capture the resolved scope once. A non-default request must never use+ // the single-runtime fallback or commit an archive without a scoped apply.+ orgID := apicontext.OrgID(r.Context())+ isTenant := orgID != "" && orgID != "default"+ currentConfig, persistence, _ := h.getContextState(r.Context())+ h.stateMu.RLock()+ mtMonitor := h.mtMonitor+ h.stateMu.RUnlock()+ if currentConfig == nil || persistence == nil || (isTenant && mtMonitor == nil) {+ http.Error(w, "Configuration runtime unavailable", http.StatusServiceUnavailable)+ return+ }+// Capture actor identity before config swap (config replacement changes auth resolution)deps := h.runtimeDependencies()- importUser := deps.AuthUsername(h.getConfig(r.Context()), r)+ importUser := deps.AuthUsername(currentConfig, r)// Import configuration.- if err := h.getPersistence(r.Context()).ImportConfig(req.Data, req.Passphrase); err != nil {+ if err := persistence.ImportConfig(req.Data, req.Passphrase); err != nil {deps.AuditEvent(apicontext.OrgID(r.Context()), "config_imported", importUser, deps.ClientIP(r), r.URL.Path, false,"Import failed")log.Error().Err(err).Msg("Failed to import configuration")@@ -119,28 +132,40 @@ func (h *ConfigHandlers) handleImportConfig(w http.ResponseWriter, r *http.Requereturn}- // Reload configuration from disk.- newConfig, err := config.Load()- if err != nil {- deps.AuditEvent(apicontext.OrgID(r.Context()), "config_imported", importUser, deps.ClientIP(r), r.URL.Path, false,- "Import succeeded but config reload failed")- log.Error().Err(err).Msg("Failed to reload configuration after import")- http.Error(w, "Configuration imported but failed to reload", http.StatusInternalServerError)- return- }-- // Update the config reference.- *h.getConfig(r.Context()) = *newConfig-- // Reload monitor with new configuration.- if h.reloadFunc != nil {- if err := h.reloadFunc(); err != nil {- deps.AuditEvent(apicontext.OrgID(r.Context()), "config_imported", importUser, deps.ClientIP(r), r.URL.Path, false,- "Import succeeded but monitor reload failed")- log.Error().Err(err).Msg("Failed to reload monitor after import")+ if isTenant {+ // Recreate only this tenant. Loading process-global configuration here+ // copied the default org's paths and credentials into the live tenant,+ // and the shared hook restarted unrelated monitoring.+ if _, err := mtMonitor.ReloadTenant(orgID); err != nil {+ deps.AuditEvent(orgID, "config_imported", importUser, deps.ClientIP(r), r.URL.Path, false,+ "Import succeeded but tenant runtime reload failed")+ log.Error().Err(err).Str("org_id", orgID).Msg("Failed to apply imported tenant configuration")http.Error(w, "Configuration imported but failed to apply changes", http.StatusInternalServerError)return}+ } else {+ // The default organization retains its existing instance-wide reload.+ // Reloading must not reinitialize the process logger under live workers.+ newConfig, err := config.LoadWithoutLoggingInit()+ if err != nil {+ deps.AuditEvent(orgID, "config_imported", importUser, deps.ClientIP(r), r.URL.Path, false,+ "Import succeeded but config reload failed")+ log.Error().Err(err).Msg("Failed to reload configuration after import")+ http.Error(w, "Configuration imported but failed to reload", http.StatusInternalServerError)+ return+ }+ config.Mu.Lock()+ *currentConfig = *newConfig+ config.Mu.Unlock()+ if h.reloadFunc != nil {+ if err := h.reloadFunc(); err != nil {+ deps.AuditEvent(orgID, "config_imported", importUser, deps.ClientIP(r), r.URL.Path, false,+ "Import succeeded but monitor reload failed")+ log.Error().Err(err).Msg("Failed to reload monitor after import")+ http.Error(w, "Configuration imported but failed to apply changes", http.StatusInternalServerError)+ return+ }+ }}// Also reload alert and notification configs explicitlydiff --git a/internal/api/configapi/config_import_scope_test.go b/internal/api/configapi/config_import_scope_test.gonew file mode 100644index 0000000000..8bec96bd2c--- /dev/null+++ b/internal/api/configapi/config_import_scope_test.go@@ -0,0 +1,52 @@+package configapi++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/api/apicontext"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+)++func TestHandleImportConfigTenantWithoutRuntimeDoesNotFallBack(t *testing.T) {+ cfg := &config.Config{DataPath: t.TempDir(), PublicURL: "https://default.invalid"}+ h := newTestConfigHandlers(t, cfg)+ settings := config.DefaultSystemSettings()+ settings.PublicURL = cfg.PublicURL+ if err := h.defaultPersistence.SaveSystemSettings(*settings); err != nil {+ t.Fatal(err)+ }+ source := config.NewConfigPersistence(t.TempDir())+ settings.PublicURL = "https://must-not-apply.invalid"+ if err := source.SaveSystemSettings(*settings); err != nil {+ t.Fatal(err)+ }+ archive, err := source.ExportConfig("synthetic-import-passphrase")+ if err != nil {+ t.Fatal(err)+ }+ body, err := json.Marshal(ImportConfigRequest{Data: archive, Passphrase: "synthetic-import-passphrase"})+ if err != nil {+ t.Fatal(err)+ }+ reloads := 0+ h.reloadFunc = func() error { reloads++; return nil }+ ctx := context.WithValue(context.Background(), apicontext.OrgIDContextKey, "tenant-a")+ req := httptest.NewRequest(http.MethodPost, "/api/config/import", bytes.NewReader(body)).WithContext(ctx)+ rec := httptest.NewRecorder()+ h.HandleImportConfig(rec, req)+ if rec.Code != http.StatusServiceUnavailable {+ t.Fatalf("missing tenant runtime status = %d, want 503", rec.Code)+ }+ after, err := h.defaultPersistence.LoadSystemSettings()+ if err != nil {+ t.Fatal(err)+ }+ if after.PublicURL != "https://default.invalid" || cfg.PublicURL != "https://default.invalid" || reloads != 0 {+ t.Error("missing tenant runtime fell back to default persistence or reload")+ }+}diff --git a/internal/monitoring/multi_tenant_monitor.go b/internal/monitoring/multi_tenant_monitor.goindex 430a391ab0..791ac70c15 100644--- a/internal/monitoring/multi_tenant_monitor.go+++ b/internal/monitoring/multi_tenant_monitor.go@@ -204,46 +204,29 @@ func (mtm *MultiTenantMonitor) GetMonitor(orgID string) (*Monitor, error) {// diagnostics immediately. Non-default tenants remain isolated deep copies// so their mutable state and credentials cannot alias the primary runtime.tenantConfig := mtm.baseConfig- if orgID != "default" {- tenantConfig = mtm.baseConfig.DeepCopy()- }- // Clear inherited credentials - tenants must load their own- // This prevents credential leakage between tenants- tenantConfig.PVEInstances = nil- tenantConfig.PBSInstances = nil- tenantConfig.PMGInstances = nil-- // Ensure the DataPath is correct for this tenant to isolate storage (sqlite, etc)+ // Resolve scoped persistence before loading any resource or credential.tenantPersistence, err := mtm.persistence.GetPersistence(orgID)if err != nil {return nil, fmt.Errorf("failed to get persistence for org %s: %w", orgID, err)}- tenantConfig.DataPath = tenantPersistence.GetConfigDir()if orgID != "default" {- // PULSE_METRICS_DB_PATH names one database file. Inherited by every- // tenant it would put all organizations' series in the same store, so- // the override applies to the default org only. Other orgs keep- // metrics.db under their own data directory, where org deletion also- // removes it.- tenantConfig.MetricsDBPath = ""- }-- // Load tenant-specific nodes from <orgDir>/nodes.enc- nodesConfig, err := tenantPersistence.LoadNodesConfig()- if err != nil {- log.Warn().Err(err).Str("org_id", orgID).Msg("failed to load tenant nodes config, starting with empty config")- // Not a fatal error - tenant may not have configured any nodes yet- } else if nodesConfig != nil {- tenantConfig.PVEInstances = nodesConfig.PVEInstances- tenantConfig.PBSInstances = nodesConfig.PBSInstances- tenantConfig.PMGInstances = nodesConfig.PMGInstances- log.Info().- Str("org_id", orgID).- Int("pve_count", len(nodesConfig.PVEInstances)).- Int("pbs_count", len(nodesConfig.PBSInstances)).- Int("pmg_count", len(nodesConfig.PMGInstances)).- Msg("Loaded tenant nodes config")+ tenantConfig, err = loadTenantRuntimeConfig(mtm.baseConfig, tenantPersistence)+ if err != nil {+ return nil, fmt.Errorf("failed to load configuration for org %s: %w", orgID, err)+ }+ } else {+ tenantConfig.PVEInstances = nil+ tenantConfig.PBSInstances = nil+ tenantConfig.PMGInstances = nil+ tenantConfig.DataPath = tenantPersistence.GetConfigDir()+ if nodes, loadErr := tenantPersistence.LoadNodesConfig(); loadErr != nil {+ log.Warn().Err(loadErr).Str("org_id", orgID).Msg("failed to load tenant nodes config, starting with empty config")+ } else if nodes != nil {+ tenantConfig.PVEInstances = nodes.PVEInstances+ tenantConfig.PBSInstances = nodes.PBSInstances+ tenantConfig.PMGInstances = nodes.PMGInstances+ }}// 2. Create Monitordiff --git a/internal/monitoring/tenant_runtime_config.go b/internal/monitoring/tenant_runtime_config.gonew file mode 100644index 0000000000..3d33c5124d--- /dev/null+++ b/internal/monitoring/tenant_runtime_config.go@@ -0,0 +1,181 @@+package monitoring++import (+ "fmt"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+)++// loadTenantRuntimeConfig deliberately does not call config.Load: that loader+// owns the process environment, logger and default-org persistence. A tenant+// starts (including after import) from its own persisted resources and settings,+// retaining only the effective process settings and environment locks in base.+func loadTenantRuntimeConfig(base *config.Config, p *config.ConfigPersistence) (*config.Config, error) {+ if base == nil || p == nil {+ return nil, fmt.Errorf("tenant configuration is unavailable")+ }+ cfg := base.DeepCopy()+ cfg.DataPath, cfg.ConfigPath = p.GetConfigDir(), p.GetConfigDir()+ // A process-level override names one database file, not a tenant template.+ cfg.MetricsDBPath = ""+ cfg.PVEInstances, cfg.PBSInstances, cfg.PMGInstances = nil, nil, nil+ cfg.APITokens, cfg.APIToken = nil, ""+ nodes, err := p.LoadNodesConfig()+ if err != nil {+ return nil, fmt.Errorf("load tenant nodes: %w", err)+ }+ if nodes != nil {+ cfg.PVEInstances, cfg.PBSInstances, cfg.PMGInstances = nodes.PVEInstances, nodes.PBSInstances, nodes.PMGInstances+ }+ tokens, err := p.LoadAPITokens()+ if err != nil {+ return nil, fmt.Errorf("load tenant API tokens: %w", err)+ }+ cfg.APITokens = tokens+ cfg.SortAPITokens()+ s, err := p.LoadSystemSettings()+ if err != nil {+ return nil, fmt.Errorf("load tenant system settings: %w", err)+ }+ if s == nil {+ return cfg, nil+ }+ locked := func(keys ...string) bool {+ for _, key := range keys {+ if cfg.EnvOverrides[key] {+ return true+ }+ }+ return false+ }+ if s.PVEPollingInterval > 0 && !locked("PVE_POLLING_INTERVAL") {+ cfg.PVEPollingInterval = min(time.Duration(s.PVEPollingInterval)*time.Second, time.Hour)+ }+ if s.PBSPollingInterval > 0 && !locked("PBS_POLLING_INTERVAL") {+ cfg.PBSPollingInterval = time.Duration(s.PBSPollingInterval) * time.Second+ }+ if s.PMGPollingInterval > 0 && !locked("PMG_POLLING_INTERVAL") {+ cfg.PMGPollingInterval = time.Duration(s.PMGPollingInterval) * time.Second+ }+ if s.BackupPollingInterval >= 0 && !locked("BACKUP_POLLING_INTERVAL") {+ cfg.BackupPollingInterval = time.Duration(s.BackupPollingInterval) * time.Second+ }+ if s.BackupPollingEnabled != nil && !locked("ENABLE_BACKUP_POLLING") {+ cfg.EnableBackupPolling = *s.BackupPollingEnabled+ }+ if s.AdaptivePollingEnabled != nil && !locked("ADAPTIVE_POLLING_ENABLED") {+ cfg.AdaptivePollingEnabled = *s.AdaptivePollingEnabled+ }+ if s.AdaptivePollingBaseInterval > 0 && !locked("ADAPTIVE_POLLING_BASE_INTERVAL") {+ cfg.AdaptivePollingBaseInterval = time.Duration(s.AdaptivePollingBaseInterval) * time.Second+ }+ if s.AdaptivePollingMinInterval > 0 && !locked("ADAPTIVE_POLLING_MIN_INTERVAL") {+ cfg.AdaptivePollingMinInterval = time.Duration(s.AdaptivePollingMinInterval) * time.Second+ }+ if s.AdaptivePollingMaxInterval > 0 && !locked("ADAPTIVE_POLLING_MAX_INTERVAL") {+ cfg.AdaptivePollingMaxInterval = time.Duration(s.AdaptivePollingMaxInterval) * time.Second+ }+ cfg.UpdateChannel = config.EffectiveUpdateChannel(s.UpdateChannel, cfg.UpdateChannel)+ cfg.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabled(cfg.UpdateChannel, s.AutoUpdateEnabled)+ if !locked("ALLOWED_ORIGINS", "allowedOrigins") {+ cfg.AllowedOrigins = s.AllowedOrigins+ }+ if s.ConnectionTimeout > 0 && !locked("connectionTimeout") {+ cfg.ConnectionTimeout = time.Duration(s.ConnectionTimeout) * time.Second+ }+ if s.LogLevel != "" && !locked("logLevel") {+ cfg.LogLevel = s.LogLevel+ }+ if !locked("discoveryEnabled") {+ cfg.DiscoveryEnabled = s.DiscoveryEnabled+ }+ if !locked("discoverySubnet") {+ cfg.DiscoverySubnet = s.DiscoverySubnet+ }+ discovery := config.NormalizeDiscoveryConfig(config.CloneDiscoveryConfig(s.DiscoveryConfig))+ // Merge only persisted discovery fields not fixed by the process environment.+ if locked("discoveryEnvironmentOverride") {+ discovery.EnvironmentOverride = cfg.Discovery.EnvironmentOverride+ }+ if locked("discoverySubnetAllowlist") {+ discovery.SubnetAllowlist = cfg.Discovery.SubnetAllowlist+ }+ if locked("discoverySubnetBlocklist") {+ discovery.SubnetBlocklist = cfg.Discovery.SubnetBlocklist+ }+ if locked("discoveryMaxHostsPerScan") {+ discovery.MaxHostsPerScan = cfg.Discovery.MaxHostsPerScan+ }+ if locked("discoveryMaxConcurrent") {+ discovery.MaxConcurrent = cfg.Discovery.MaxConcurrent+ }+ if locked("discoveryEnableReverseDns") {+ discovery.EnableReverseDNS = cfg.Discovery.EnableReverseDNS+ }+ if locked("discoveryScanGateways") {+ discovery.ScanGateways = cfg.Discovery.ScanGateways+ }+ if locked("discoveryDialTimeoutMs") {+ discovery.DialTimeout = cfg.Discovery.DialTimeout+ }+ if locked("discoveryHttpTimeoutMs") {+ discovery.HTTPTimeout = cfg.Discovery.HTTPTimeout+ }+ cfg.Discovery = discovery+ if !locked("temperatureMonitoringEnabled") {+ cfg.TemperatureMonitoringEnabled = s.TemperatureMonitoringEnabled+ }+ if s.DNSCacheTimeout > 0 && !locked("DNS_CACHE_TIMEOUT") {+ cfg.DNSCacheTimeout = time.Duration(s.DNSCacheTimeout) * time.Second+ }+ if !locked("SSH_PORT") {+ cfg.SSHPort = s.SSHPort+ if cfg.SSHPort <= 0 {+ cfg.SSHPort = 22+ }+ }+ if !locked("PULSE_AUTH_HIDE_LOCAL_LOGIN", "hideLocalLogin") {+ cfg.HideLocalLogin = s.HideLocalLogin+ }+ if !locked("PULSE_DISABLE_DOCKER_UPDATE_ACTIONS", "disableDockerUpdateActions") {+ cfg.DisableDockerUpdateActions = s.DisableDockerUpdateActions+ }+ if !locked("PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY", "enableProxmoxGuestDockerInventory") {+ cfg.EnableProxmoxGuestDockerInventory = s.EnableProxmoxGuestDockerInventory+ }+ if !locked("PULSE_TELEMETRY", "telemetryEnabled") {+ cfg.TelemetryEnabled = s.TelemetryEnabled == nil || *s.TelemetryEnabled+ }+ if !locked("publicURL") {+ cfg.PublicURL = s.PublicURL+ }+ if s.MetricsRetentionRawHours > 0 {+ cfg.MetricsRetentionRawHours = s.MetricsRetentionRawHours+ }+ if s.MetricsRetentionMinuteHours > 0 {+ cfg.MetricsRetentionMinuteHours = s.MetricsRetentionMinuteHours+ }+ if s.MetricsRetentionHourlyDays > 0 {+ cfg.MetricsRetentionHourlyDays = s.MetricsRetentionHourlyDays+ }+ if s.MetricsRetentionDailyDays > 0 {+ cfg.MetricsRetentionDailyDays = s.MetricsRetentionDailyDays+ }+ return cfg, nil+}++// ReloadTenant rebuilds only the selected organization's runtime from its own+// persisted configuration. Never use the instance-wide reload for this path.+// removeTenant retains its availability guard when shutdown is incomplete.+func (mtm *MultiTenantMonitor) ReloadTenant(orgID string) (*Monitor, error) {+ orgID = strings.TrimSpace(orgID)+ if mtm == nil || orgID == "" || orgID == "default" {+ return nil, fmt.Errorf("tenant reload requires a non-default organization")+ }+ if err := mtm.removeTenant(orgID, false); err != nil {+ return nil, err+ }+ return mtm.GetMonitor(orgID)+}diff --git a/internal/monitoring/tenant_runtime_config_test.go b/internal/monitoring/tenant_runtime_config_test.gonew file mode 100644index 0000000000..dfe406418c--- /dev/null+++ b/internal/monitoring/tenant_runtime_config_test.go@@ -0,0 +1,140 @@+package monitoring++import (+ "os"+ "path/filepath"+ "reflect"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+)++func TestLoadTenantRuntimeConfigUsesScopedResourcesAndPreservesEnvironment(t *testing.T) {+ p := config.NewConfigPersistence(t.TempDir())+ settings := config.DefaultSystemSettings()+ settings.PublicURL = "https://tenant.invalid"+ settings.AllowedOrigins = "https://tenant-ui.invalid"+ settings.PVEPollingInterval, settings.PBSPollingInterval = 57, 137+ settings.HideLocalLogin = false+ settings.DisableDockerUpdateActions = true+ settings.DiscoveryConfig.MaxConcurrent = 3+ settings.DiscoveryConfig.SubnetAllowlist = []string{"192.0.2.0/24"}+ if err := p.SaveSystemSettings(*settings); err != nil {+ t.Fatal(err)+ }+ if err := p.SaveNodesConfig([]config.PVEInstance{{Name: "tenant-node", TokenValue: "synthetic-tenant-secret", Disabled: true}}, nil, nil); err != nil {+ t.Fatal(err)+ }+ if err := p.SaveAPITokens([]config.APITokenRecord{{ID: "tenant-token", Hash: "synthetic-tenant-hash", OrgID: "tenant-a", Scopes: []string{config.ScopeSettingsRead}}}); err != nil {+ t.Fatal(err)+ }+ // A tenant .env is not process configuration and must never be loaded.+ t.Setenv("PULSE_TENANT_IMPORT_SENTINEL", "process")+ if err := os.WriteFile(filepath.Join(p.GetConfigDir(), ".env"), []byte("PULSE_TENANT_IMPORT_SENTINEL=tenant\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ base := &config.Config{+ DataPath: t.TempDir(), ConfigPath: t.TempDir(), MetricsDBPath: "synthetic-default-metrics-path",+ AuthUser: "instance-admin", AuthPass: "synthetic-instance-auth", ProxyAuthSecret: "synthetic-instance-proxy",+ TLSCertFile: "instance-cert", TLSKeyFile: "instance-key", FrontendPort: 7655,+ APITokens: []config.APITokenRecord{{ID: "default-token", Hash: "synthetic-default-hash"}},+ PVEInstances: []config.PVEInstance{{Name: "default-node", TokenValue: "synthetic-default-secret"}},+ PublicURL: "https://default.invalid", PVEPollingInterval: 42 * time.Second,+ HideLocalLogin: true, Discovery: config.DefaultDiscoveryConfig(),+ EnvOverrides: map[string]bool{"PVE_POLLING_INTERVAL": true, "PULSE_AUTH_HIDE_LOCAL_LOGIN": true, "discoveryMaxConcurrent": true},+ }+ base.Discovery.MaxConcurrent = 11+ before := base.DeepCopy()+ cfg, err := loadTenantRuntimeConfig(base, p)+ if err != nil {+ t.Fatal(err)+ }+ if cfg.DataPath != p.GetConfigDir() || cfg.ConfigPath != p.GetConfigDir() || cfg.MetricsDBPath != "" {+ t.Error("tenant paths inherited a default-org storage location")+ }+ if len(cfg.PVEInstances) != 1 || cfg.PVEInstances[0].Name != "tenant-node" || cfg.PVEInstances[0].TokenValue != "synthetic-tenant-secret" {+ t.Error("tenant nodes/credentials did not replace inherited resources")+ }+ if len(cfg.APITokens) != 1 || cfg.APITokens[0].ID != "tenant-token" || cfg.APIToken != "synthetic-tenant-hash" {+ t.Error("tenant API tokens did not replace inherited tokens and legacy alias")+ }+ if cfg.PublicURL != settings.PublicURL || cfg.AllowedOrigins != settings.AllowedOrigins || cfg.PBSPollingInterval != 137*time.Second || !cfg.DisableDockerUpdateActions {+ t.Error("saved tenant settings were not applied")+ }+ if cfg.PVEPollingInterval != 42*time.Second || !cfg.HideLocalLogin || cfg.Discovery.MaxConcurrent != 11 {+ t.Error("tenant settings bypassed effective process environment locks")+ }+ if !reflect.DeepEqual(cfg.Discovery.SubnetAllowlist, settings.DiscoveryConfig.SubnetAllowlist) {+ t.Error("unlocked discovery setting was not applied")+ }+ if cfg.AuthUser != base.AuthUser || cfg.AuthPass != base.AuthPass || cfg.ProxyAuthSecret != base.ProxyAuthSecret || cfg.TLSCertFile != base.TLSCertFile || cfg.TLSKeyFile != base.TLSKeyFile || cfg.FrontendPort != base.FrontendPort {+ t.Error("tenant loader changed process identity or listener settings")+ }+ if os.Getenv("PULSE_TENANT_IMPORT_SENTINEL") != "process" {+ t.Error("tenant loader changed the process environment")+ }+ if !reflect.DeepEqual(base, before) {+ t.Error("tenant loader mutated the default config")+ }+ cfg.EnvOverrides["synthetic-test-lock"] = true+ cfg.PVEInstances[0].TokenValue = "changed"+ if base.EnvOverrides["synthetic-test-lock"] || base.PVEInstances[0].TokenValue != "synthetic-default-secret" {+ t.Error("tenant config aliases default mutable state")+ }+}++func TestLoadTenantRuntimeConfigEmptyInventoryAndCorruptSettings(t *testing.T) {+ p := config.NewConfigPersistence(t.TempDir())+ base := &config.Config{PVEInstances: []config.PVEInstance{{Name: "default"}}, APITokens: []config.APITokenRecord{{ID: "default", Hash: "synthetic-hash"}}, APIToken: "synthetic-hash"}+ cfg, err := loadTenantRuntimeConfig(base, p)+ if err != nil {+ t.Fatal(err)+ }+ if len(cfg.PVEInstances) != 0 || len(cfg.APITokens) != 0 || cfg.APIToken != "" {+ t.Error("empty tenant inherited another organization's resources or token alias")+ }+ if err := os.WriteFile(filepath.Join(p.GetConfigDir(), "system.json"), []byte("{invalid"), 0o600); err != nil {+ t.Fatal(err)+ }+ if _, err := loadTenantRuntimeConfig(base, p); err == nil {+ t.Error("unreadable tenant settings fell back to the default config")+ }+ if _, err := loadTenantRuntimeConfig(nil, p); err == nil {+ t.Error("missing base config was accepted")+ }+ if _, err := loadTenantRuntimeConfig(base, nil); err == nil {+ t.Error("missing persistence was accepted")+ }+}++func TestReloadTenantRejectsDefaultAndRetainsIncompleteStopGuard(t *testing.T) {+ mtm := NewMultiTenantMonitor(&config.Config{}, nil, nil)+ // No real monitor or storage is started: control only the owned loop's+ // completion signal to verify the existing incomplete-stop contract.+ defer mtm.globalCancel()+ for _, orgID := range []string{"", "default", " default "} {+ if _, err := mtm.ReloadTenant(orgID); err == nil {+ t.Errorf("reload accepted default-org selector %q", orgID)+ }+ }+ previous := tenantMonitorShutdownTimeout+ tenantMonitorShutdownTimeout = time.Millisecond+ t.Cleanup(func() { tenantMonitorShutdownTimeout = previous })+ mtm.tenantDone["tenant-a"] = make(chan struct{})+ mtm.tenantCancel["tenant-a"] = func() {}+ if _, err := mtm.ReloadTenant("tenant-a"); err == nil {+ t.Error("incomplete tenant stop reported a successful reload")+ }+ if _, guarded := mtm.tenantDeleting["tenant-a"]; !guarded {+ t.Error("incomplete stop released its tenant availability guard")+ }+ if _, err := mtm.GetMonitor("tenant-a"); err == nil {+ t.Error("incomplete stop admitted a replacement runtime")+ }+ select {+ case <-mtm.globalCtx.Done():+ t.Error("tenant reload cancelled the shared monitoring context")+ default:+ }+}