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
Keep tenant authentication bound to the current runtime owner
pulse-triage[bot]3b6483fce675
diff --git a/internal/api/auth.go b/internal/api/auth.goindex 9170a36224..f7f3e9d967 100644--- a/internal/api/auth.go+++ b/internal/api/auth.go@@ -203,13 +203,21 @@ const (// a tenant credential. It identifies the live inventory, not an authentication// grant: route auth must revalidate the presented token against that inventory.type tenantTokenSource struct {- manager *monitoring.MultiTenantMonitor- orgID string+ manager *monitoring.MultiTenantMonitor+ resolveManager func() *monitoring.MultiTenantMonitor+ orgID string}func tenantTokenConfigForRequest(r *http.Request) *config.Config {source, ok := r.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)- if !ok || source.manager == nil || source.orgID == "" || source.orgID == "default" {+ if !ok || source.orgID == "" || source.orgID == "default" {+ return nil+ }+ manager := source.manager+ if source.resolveManager != nil {+ manager = source.resolveManager()+ }+ if manager == nil {return nil}orgID := strings.TrimSpace(GetOrgID(r.Context()))@@ -222,7 +230,7 @@ func tenantTokenConfigForRequest(r *http.Request) *config.Config {// Do not start a cold tenant during a second auth check. Resolve the live// cached owner again, so import/replacement or revocation between middleware// and route enforcement cannot authenticate through a stale config pointer.- monitor, exists := source.manager.PeekMonitor(orgID)+ monitor, exists := manager.PeekMonitor(orgID)if !exists || monitor == nil {return nil}@@ -1334,10 +1342,18 @@ func isAdminBypassRequest(ctx context.Context) bool {// Note: This middleware does NOT enforce authentication - it only populates context.// Use RequireAuth for enforcement.func AuthContextMiddleware(cfg *config.Config, mtm *monitoring.MultiTenantMonitor, next http.Handler) http.Handler {+ return authContextMiddlewareWithMonitorResolver(cfg, func() *monitoring.MultiTenantMonitor { return mtm }, next)+}++func authContextMiddlewareWithMonitorResolver(cfg *config.Config, resolve func() *monitoring.MultiTenantMonitor, next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- // Try to extract auth info and store in context WITHOUT enforcing auth- // This allows tenant middleware to check authorization later- r = extractAndStoreAuthContext(cfg, mtm, r)+ // The router's monitor manager can be replaced by an instance reload.+ // Resolve its current owner both here and during route revalidation.+ r = extractAndStoreAuthContext(cfg, resolve(), r)+ if source, ok := r.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource); ok {+ source.resolveManager = resolve+ r = r.WithContext(context.WithValue(r.Context(), tenantTokenSourceContextKey, source))+ }next.ServeHTTP(w, r)})}diff --git a/internal/api/auth_context_tenant_test.go b/internal/api/auth_context_tenant_test.goindex df2a6b9fe0..6c33390e45 100644--- a/internal/api/auth_context_tenant_test.go+++ b/internal/api/auth_context_tenant_test.go@@ -149,3 +149,62 @@ func TestCheckAuthTenantSourceCannotChangeOrganisation(t *testing.T) {t.Fatal("stale tenant config authenticated after runtime replacement")}}++func TestAuthContextMiddlewareUsesCurrentTenantManager(t *testing.T) {+ const orgID = "tenant-a"+ const oldRaw = "synthetic-before-reload-token.12345678"+ const newRaw = "synthetic-after-reload-token.12345678"+ base := &config.Config{}+ mtp := config.NewMultiTenantPersistence(t.TempDir())+ if _, err := mtp.GetPersistence(orgID); err != nil {+ t.Fatal(err)+ }+ makeManager := func(raw string) *monitoring.MultiTenantMonitor {+ t.Helper()+ record, err := config.NewAPITokenRecord(raw, "synthetic", []string{config.ScopeMonitoringRead})+ if err != nil {+ t.Fatal(err)+ }+ cfg := &config.Config{APITokens: []config.APITokenRecord{*record}}+ monitor := &monitoring.Monitor{}+ setUnexportedField(t, monitor, "config", cfg)+ manager := monitoring.NewMultiTenantMonitor(base, mtp, nil)+ setUnexportedField(t, manager, "monitors", map[string]*monitoring.Monitor{orgID: monitor})+ t.Cleanup(manager.Stop)+ return manager+ }+ oldManager, newManager := makeManager(oldRaw), makeManager(newRaw)+ current := oldManager+ replaceBetweenChecks := false+ handler := authContextMiddlewareWithMonitorResolver(base, func() *monitoring.MultiTenantMonitor { return current }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if replaceBetweenChecks {+ current = newManager+ }+ if !checkAuth(base, w, r, false) {+ return+ }+ w.WriteHeader(http.StatusOK)+ }))+ for _, tc := range []struct {+ name, raw string+ replace bool+ status int+ }{+ {"old owner", oldRaw, false, http.StatusOK},+ {"owner changes before enforcement", oldRaw, true, http.StatusUnauthorized},+ {"new owner", newRaw, false, http.StatusOK},+ {"old token after replacement", oldRaw, false, http.StatusUnauthorized},+ } {+ t.Run(tc.name, func(t *testing.T) {+ replaceBetweenChecks = tc.replace+ req := httptest.NewRequest(http.MethodGet, "/api/test", nil)+ req.Header.Set("X-Pulse-Org-ID", orgID)+ req.Header.Set("X-API-Token", tc.raw)+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)+ if rec.Code != tc.status {+ t.Fatalf("status = %d, want %d", rec.Code, tc.status)+ }+ })+ }+}diff --git a/internal/api/configapi/config_handlers.go b/internal/api/configapi/config_handlers.goindex 28564758dd..b5c08ca01c 100644--- a/internal/api/configapi/config_handlers.go+++ b/internal/api/configapi/config_handlers.go@@ -300,6 +300,14 @@ func (h *ConfigHandlers) SetMultiTenantMonitor(mtm *monitoring.MultiTenantMonito}}+// MultiTenantMonitor returns the current owner used by scoped configuration+// and authentication, including after an instance-wide monitor replacement.+func (h *ConfigHandlers) MultiTenantMonitor() *monitoring.MultiTenantMonitor {+ h.stateMu.RLock()+ defer h.stateMu.RUnlock()+ return h.mtMonitor+}+// SetMonitor updates the default-org monitor reference used by the config handlers.func (h *ConfigHandlers) SetMonitor(m *monitoring.Monitor) {h.stateMu.Lock()diff --git a/internal/api/configapi/config_import_scope_test.go b/internal/api/configapi/config_import_scope_test.goindex 8bec96bd2c..661896d2c0 100644--- a/internal/api/configapi/config_import_scope_test.go+++ b/internal/api/configapi/config_import_scope_test.go@@ -10,6 +10,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/api/apicontext""github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring")func TestHandleImportConfigTenantWithoutRuntimeDoesNotFallBack(t *testing.T) {@@ -50,3 +51,22 @@ func TestHandleImportConfigTenantWithoutRuntimeDoesNotFallBack(t *testing.T) {t.Error("missing tenant runtime fell back to default persistence or reload")}}++func TestConfigHandlersTenantManagerReferenceTracksReplacement(t *testing.T) {+ first := monitoring.NewMultiTenantMonitor(&config.Config{}, nil, nil)+ second := monitoring.NewMultiTenantMonitor(&config.Config{}, nil, nil)+ t.Cleanup(first.Stop)+ t.Cleanup(second.Stop)+ h := &ConfigHandlers{mtMonitor: first}+ if h.MultiTenantMonitor() != first {+ t.Fatal("initial scoped owner missing")+ }+ h.SetMultiTenantMonitor(second)+ if h.MultiTenantMonitor() != second {+ t.Fatal("replacement scoped owner not visible")+ }+ h.SetMultiTenantMonitor(nil)+ if h.MultiTenantMonitor() != nil {+ t.Fatal("removed scoped owner remained usable")+ }+}diff --git a/internal/api/router.go b/internal/api/router.goindex d92ff447d3..80821941c7 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -353,7 +353,7 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monithandler = tenantMiddleware.Middleware(handler)// Auth context middleware extracts user/token info BEFORE tenant middleware- handler = AuthContextMiddleware(cfg, r.mtMonitor, handler)+ handler = authContextMiddlewareWithMonitorResolver(cfg, r.configHandlers.MultiTenantMonitor, handler)handler = UniversalRateLimitMiddlewareWithConfig(r.endpointRateLimitConfig, handler)r.wrapped = handler