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
Revalidate tenant credentials against their live scoped runtime
pulse-triage[bot]31db0c8f38a2
diff --git a/internal/api/auth.go b/internal/api/auth.goindex 114d4980d8..9170a36224 100644--- a/internal/api/auth.go+++ b/internal/api/auth.go@@ -195,9 +195,40 @@ func resolveOIDCRefreshConfig(cfg *config.Config, session *SessionData) (*configtype authContextKey stringconst (- adminBypassContextKey authContextKey = "admin_bypass"+ adminBypassContextKey authContextKey = "admin_bypass"+ tenantTokenSourceContextKey authContextKey = "tenant_token_source")+// tenantTokenSource is installed only by AuthContextMiddleware after validating+// 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+}++func tenantTokenConfigForRequest(r *http.Request) *config.Config {+ source, ok := r.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)+ if !ok || source.manager == nil || source.orgID == "" || source.orgID == "default" {+ return nil+ }+ orgID := strings.TrimSpace(GetOrgID(r.Context()))+ if orgID == "" {+ orgID = resolveTenantOrgID(r)+ }+ if orgID != source.orgID {+ return nil+ }+ // 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)+ if !exists || monitor == nil {+ return nil+ }+ return monitor.GetConfig()+}+// InitSessionStore initializes the persistent session storefunc InitSessionStore(dataPath string) {_ = ensureSessionStore(dataPath)@@ -716,7 +747,7 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, writeMsg("Checking authentication")authenticateToken := func(token string) bool {- if record, ok := validateGlobalAPITokenLocked(cfg, token); ok {+ if record, ok := validateAPITokenAgainstConfigsLocked(cfg, tenantTokenConfigForRequest(r), token); ok {attachAPITokenRecord(r, record)if authenticatedUser := apiTokenAuthenticatedUser(record); authenticatedUser != "" {w.Header().Set("X-Authenticated-User", authenticatedUser)@@ -728,16 +759,14 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, write}// Explicit token credentials always take precedence over session/basic auth.- if cfg.HasAPITokens() {- if providedToken, provided := explicitAPITokenFromRequest(r); provided {- if authenticateToken(providedToken) {- return true- }- if w != nil {- http.Error(w, "Invalid API token", http.StatusUnauthorized)- }- return false+ if providedToken, provided := explicitAPITokenFromRequest(r); provided {+ if authenticateToken(providedToken) {+ return true}+ if w != nil {+ http.Error(w, "Invalid API token", http.StatusUnauthorized)+ }+ return false}// Check session cookie (for WebSocket and UI). Hosted cloud-handoff and@@ -1338,6 +1367,7 @@ func extractAndStoreAuthContext(cfg *config.Config, mtm *monitoring.MultiTenantMif cfg.HasAPITokens() || mtm != nil {// Determine which config to use for validation (Global vs Tenant)targetConfig := cfg+ targetOrgID := ""providedToken, explicitTokenProvided := explicitAPITokenFromRequest(r)// Global tokens are the common control-plane credential. Authenticate@@ -1369,6 +1399,7 @@ func extractAndStoreAuthContext(cfg *config.Config, mtm *monitoring.MultiTenantMif mtm.OrgExists(orgID) {if m, err := mtm.GetMonitor(orgID); err == nil && m != nil {targetConfig = m.GetConfig()+ targetOrgID = strings.TrimSpace(orgID)}}}@@ -1377,6 +1408,9 @@ func extractAndStoreAuthContext(cfg *config.Config, mtm *monitoring.MultiTenantMvalidateToken := func(token string) (*http.Request, bool) {if record, ok := validateAPITokenAgainstConfigsLocked(cfg, targetConfig, token); ok {attachAPITokenRecord(r, record)+ if targetOrgID != "" && targetConfig != cfg {+ *r = *r.WithContext(context.WithValue(r.Context(), tenantTokenSourceContextKey, tenantTokenSource{manager: mtm, orgID: targetOrgID}))+ }return attachUserContext(r, apiTokenAuthenticatedUser(record)), true}return nil, falsediff --git a/internal/api/auth_context_tenant_test.go b/internal/api/auth_context_tenant_test.goindex b29d9ba89a..df2a6b9fe0 100644--- a/internal/api/auth_context_tenant_test.go+++ b/internal/api/auth_context_tenant_test.go@@ -22,6 +22,7 @@ func TestExtractAndStoreAuthContext_UsesTenantConfigForToken(t *testing.T) {}{{"global fallback with empty tenant tokens", true, false, globalToken, "global"},{"tenant token with different global tokens", true, true, tenantToken, "tenant"},+ {"tenant token without global tokens", false, true, tenantToken, "tenant"},{"unknown token is rejected", true, true, "unknown-token-123.12345678", ""},} {t.Run(tc.name, func(t *testing.T) {@@ -81,6 +82,70 @@ func TestExtractAndStoreAuthContext_UsesTenantConfigForToken(t *testing.T) {if !ok || record.Name != tc.wantRecord || !record.HasScope(config.ScopeMonitoringRead) {t.Fatalf("expected %s monitoring token in context, got %#v", tc.wantRecord, token)}+ if !checkAuth(baseCfg, httptest.NewRecorder(), req, false) {+ t.Fatal("route authentication rejected the middleware-validated credential")+ }+ if tc.wantRecord == "tenant" {+ // A stale context record is not authority after revocation.+ tenantCfg.APITokens = nil+ if checkAuth(baseCfg, httptest.NewRecorder(), req, false) {+ t.Fatal("route authentication accepted a revoked tenant credential")+ }+ }})}}++func TestCheckAuthRejectsUnvalidatedTenantTokenContext(t *testing.T) {+ cfg := &config.Config{}+ req := httptest.NewRequest(http.MethodGet, "/api/test", nil)+ req.Header.Set("X-Pulse-Org-ID", "tenant-a")+ req.Header.Set("X-API-Token", "unvalidated-tenant-token.12345678")+ record, err := config.NewAPITokenRecord("unvalidated-tenant-token.12345678", "forged-context", []string{config.ScopeWildcard})+ if err != nil {+ t.Fatal(err)+ }+ req = req.WithContext(internalauth.WithAPIToken(req.Context(), record))+ if checkAuth(cfg, httptest.NewRecorder(), req, false) {+ t.Fatal("caller-supplied token context authenticated without a live validated inventory")+ }+}++func TestCheckAuthTenantSourceCannotChangeOrganisation(t *testing.T) {+ const raw = "synthetic-live-tenant-token.12345678"+ record, err := config.NewAPITokenRecord(raw, "tenant", []string{config.ScopeMonitoringRead})+ if err != nil {+ t.Fatal(err)+ }+ base := &config.Config{}+ tenantCfg := &config.Config{APITokens: []config.APITokenRecord{*record}}+ mtp := config.NewMultiTenantPersistence(t.TempDir())+ if _, err := mtp.GetPersistence("tenant-a"); err != nil {+ t.Fatal(err)+ }+ mtm := monitoring.NewMultiTenantMonitor(base, mtp, nil)+ t.Cleanup(mtm.Stop)+ m := &monitoring.Monitor{}+ setUnexportedField(t, m, "config", tenantCfg)+ setUnexportedField(t, mtm, "monitors", map[string]*monitoring.Monitor{"tenant-a": m})+ req := httptest.NewRequest(http.MethodGet, "/api/test", nil)+ req.Header.Set("X-Pulse-Org-ID", "tenant-a")+ req.Header.Set("X-API-Token", raw)+ req = extractAndStoreAuthContext(base, mtm, req)+ if !checkAuth(base, httptest.NewRecorder(), req, false) {+ t.Fatal("valid tenant credential was not usable")+ }+ req.Header.Set("X-Pulse-Org-ID", "tenant-b")+ if checkAuth(base, httptest.NewRecorder(), req, false) {+ t.Fatal("validated tenant source followed a changed organisation")+ }+ req.Header.Set("X-Pulse-Org-ID", "tenant-a")+ // Replace the cached owner without changing the old config: revalidation+ // must consult the replacement, not the earlier authenticated pointer.+ replacement := &monitoring.Monitor{}+ setUnexportedField(t, replacement, "config", &config.Config{})+ setUnexportedField(t, mtm, "monitors", map[string]*monitoring.Monitor{"tenant-a": replacement})+ if checkAuth(base, httptest.NewRecorder(), req, false) {+ t.Fatal("stale tenant config authenticated after runtime replacement")+ }+}