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
Stamp tenant identity into alert webhook payloads
rcourtmana223b02dd54f
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex cc27c6a46a..8c7738f9db 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -845,6 +845,14 @@ shares, TrueNAS systems/VMs/apps, VMware hosts/VMs/datastores, availabilitytargets, and active alerts. Telemetry callers may consume those coarse totals,but they must not bypass monitoring to read provider-local identifiers ortenant-local resource names.+That same reloadable multi-tenant monitor boundary also owns wiring tenant+identity into per-org notification delivery. When a tenant monitor is+initialized for a non-default org, monitoring installs an org-backed tenant+identity resolver on that org's notification manager so webhook payloads can+stamp the org ID and current display name; the resolver reads the org record+lazily so display-name renames propagate without monitor restarts. The+default org keeps environment-provided identity and must not be overridden+here.Consumer packages already use `ReadState`, but the monitoring core still hasdual truth between unified resources and `StateSnapshot`. This is the maindiff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.mdindex 08aebfe200..df685e34f9 100644--- a/docs/release-control/v6/internal/subsystems/notifications.md+++ b/docs/release-control/v6/internal/subsystems/notifications.md@@ -121,6 +121,18 @@ Enhanced webhook test/live delivery must follow that same ownership model:into the canonical webhook render and transport path instead of maintaining aparallel URL-rendering, enrichment, Telegram URL sanitization, or single-sendHTTP stack.+That same webhook payload boundary also owns tenant identity stamping. Webhook+payload data carries the tenant ID and display name of the runtime or+organization that fired the alert: environment-provided identity+(`PULSE_TENANT_ID` / `PULSE_TENANT_NAME`) is the construction-time default for+isolated client runtimes, the display name falls back to the ID, and+shared-process multi-tenant deployments override it through an org-backed+resolver installed by the monitoring subsystem. Templates consume it as+`{{.TenantID}}` / `{{.TenantName}}`, and the canonical generic template emits+its tenant block only when an identity is present so single-tenant payloads+keep their existing shape. PSA/ticket-bridge receivers must get tenant routing+identity from this payload boundary, not by inferring it from webhook endpoint+configuration.That same transport boundary also owns webhook request normalization. Renderedwebhook URLs must reject userinfo during validation, and request constructionmust route through a validated absolute URL object instead of reparsing raw URLdiff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex dcbea8d382..6ca71e9322 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -2234,3 +2234,50 @@ func TestMonitorUptimeFallsBackToCanonicalResourceUptime(t *testing.T) {}})}++// Tenant monitors must stamp their org's identity into notification webhook+// payloads via an org-backed resolver, so PSA/ticket-bridge receivers get+// tenant routing identity from the payload boundary and display-name renames+// propagate without a monitor restart.+func TestTenantMonitorWiresOrgIdentityIntoNotifications(t *testing.T) {+ mtp, _ := newTestTenantPersistence(t)+ baseCfg := &config.Config{DataPath: t.TempDir()}+ mtm := NewMultiTenantMonitor(baseCfg, mtp, nil)+ t.Cleanup(mtm.Stop)++ if err := mtp.SaveOrganization(&models.Organization{+ ID: "org-acme",+ DisplayName: "Acme Corp",+ }); err != nil {+ t.Fatalf("SaveOrganization(org-acme) error = %v", err)+ }++ monitor, err := mtm.GetMonitor("org-acme")+ if err != nil {+ t.Fatalf("GetMonitor(org-acme) error = %v", err)+ }++ nm := monitor.GetNotificationManager()+ if nm == nil {+ t.Fatal("expected tenant monitor to have a notification manager")+ }++ tenantID, tenantName := nm.TenantIdentity()+ if tenantID != "org-acme" {+ t.Fatalf("TenantIdentity() id = %q, want %q", tenantID, "org-acme")+ }+ if tenantName != "Acme Corp" {+ t.Fatalf("TenantIdentity() name = %q, want %q", tenantName, "Acme Corp")+ }++ // Display-name renames must propagate lazily without monitor restarts.+ if err := mtp.SaveOrganization(&models.Organization{+ ID: "org-acme",+ DisplayName: "Acme Corp Renamed",+ }); err != nil {+ t.Fatalf("SaveOrganization(rename) error = %v", err)+ }+ if _, tenantName = nm.TenantIdentity(); tenantName != "Acme Corp Renamed" {+ t.Fatalf("TenantIdentity() name after rename = %q, want %q", tenantName, "Acme Corp Renamed")+ }+}diff --git a/internal/monitoring/multi_tenant_monitor.go b/internal/monitoring/multi_tenant_monitor.goindex 2f349a445d..3502cf992d 100644--- a/internal/monitoring/multi_tenant_monitor.go+++ b/internal/monitoring/multi_tenant_monitor.go@@ -174,6 +174,21 @@ func (mtm *MultiTenantMonitor) GetMonitor(orgID string) (*Monitor, error) {// Set org ID for tenant isolation// This enables tenant-scoped WebSocket broadcastsmonitor.SetOrgID(orgID)++ // Stamp this org's identity into webhook payloads so external receivers+ // (PSA/ticketing bridges) can route by tenant. Resolved lazily so a+ // display-name rename is picked up without restarting the monitor. The+ // default org keeps the PULSE_TENANT_ID/PULSE_TENANT_NAME env defaults.+ if nm := monitor.GetNotificationManager(); nm != nil && orgID != "default" {+ persistence := mtm.persistence+ nm.SetTenantIdentityResolver(func() (string, string) {+ name := ""+ if org, err := persistence.LoadOrganization(orgID); err == nil && org != nil {+ name = org.DisplayName+ }+ return orgID, name+ })+ }if mtm.recoveryMgr != nil {monitor.SetRecoveryManager(mtm.recoveryMgr)}diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.goindex 37b2e08690..ccebbd75d4 100644--- a/internal/notifications/notifications.go+++ b/internal/notifications/notifications.go@@ -12,6 +12,7 @@ import ("net""net/http""net/url"+ "os""os/exec""strings""sync"@@ -228,12 +229,15 @@ type NotificationManager struct {webhookRateMu sync.Mutex // Separate mutex for webhook rate limitingwebhookRateCleanup time.Time // Last cleanup time for webhook rate limit entriesappriseExec appriseExecFunc- queue *NotificationQueue // Persistent notification queue- webhookClient *http.Client // Shared HTTP client for webhooks- stopCleanup chan struct{} // Signal to stop cleanup goroutine- cleanupDone chan struct{} // Signals cleanup goroutine exit during shutdown- allowedPrivateNets []*net.IPNet // Parsed CIDR ranges allowed for private webhook targets- allowedPrivateMu sync.RWMutex // Protects allowedPrivateNets+ queue *NotificationQueue // Persistent notification queue+ tenantID string // Tenant identity stamped into webhook payloads (env default)+ tenantName string // Tenant display name stamped into webhook payloads (env default)+ tenantResolver func() (id string, name string) // Org-backed tenant identity override (multi-tenant)+ webhookClient *http.Client // Shared HTTP client for webhooks+ stopCleanup chan struct{} // Signal to stop cleanup goroutine+ cleanupDone chan struct{} // Signals cleanup goroutine exit during shutdown+ allowedPrivateNets []*net.IPNet // Parsed CIDR ranges allowed for private webhook targets+ allowedPrivateMu sync.RWMutex // Protects allowedPrivateNets}type webhookHTTPResult struct {@@ -669,6 +673,8 @@ func NewNotificationManagerWithDataDir(publicURL string, dataDir string) *NotifiAPIKeyHeader: "X-API-KEY",},groupWindow: 30 * time.Second,+ tenantID: strings.TrimSpace(os.Getenv("PULSE_TENANT_ID")),+ tenantName: strings.TrimSpace(os.Getenv("PULSE_TENANT_NAME")),pendingAlerts: make([]*alerts.Alert, 0),groupByNode: true,groupByGuest: false,@@ -696,6 +702,36 @@ func NewNotificationManagerWithDataDir(publicURL string, dataDir string) *Notifireturn nm}+// SetTenantIdentityResolver installs an org-backed resolver for the tenant+// identity stamped into webhook payloads. It overrides the+// PULSE_TENANT_ID / PULSE_TENANT_NAME environment defaults; multi-tenant+// deployments use it so each org's manager reports that org's identity.+func (n *NotificationManager) SetTenantIdentityResolver(resolver func() (id string, name string)) {+ n.mu.Lock()+ n.tenantResolver = resolver+ n.mu.Unlock()+}++// TenantIdentity returns the tenant ID and display name stamped into webhook+// payloads. The name falls back to the ID so receivers always get a usable+// label when any tenant identity is configured at all.+func (n *NotificationManager) TenantIdentity() (string, string) {+ n.mu.RLock()+ resolver := n.tenantResolver+ id, name := n.tenantID, n.tenantName+ n.mu.RUnlock()++ if resolver != nil {+ if rid, rname := resolver(); strings.TrimSpace(rid) != "" {+ id, name = strings.TrimSpace(rid), strings.TrimSpace(rname)+ }+ }+ if name == "" {+ name = id+ }+ return id, name+}+// SetPublicURL updates the public URL used for webhook payloads.func (n *NotificationManager) SetPublicURL(publicURL string) {trimmed := strings.TrimRight(strings.TrimSpace(publicURL), "/")@@ -2605,6 +2641,8 @@ func (n *NotificationManager) prepareWebhookData(alert *alerts.Alert, customFielroundedValue := math.Round(alert.Value*10) / 10roundedThreshold := math.Round(alert.Threshold*10) / 10+ tenantID, tenantName := n.TenantIdentity()+return WebhookPayloadData{ID: alert.ID,Level: string(alert.Level),@@ -2627,6 +2665,8 @@ func (n *NotificationManager) prepareWebhookData(alert *alerts.Alert, customFielAckTime: ackTime,AckUser: alert.AckUser,Event: "alert",+ TenantID: tenantID,+ TenantName: tenantName,Metadata: metadataCopy,CustomFields: customFields,AlertCount: 1,diff --git a/internal/notifications/webhook_enhanced.go b/internal/notifications/webhook_enhanced.goindex 7a5c2ec2d3..eca381535a 100644--- a/internal/notifications/webhook_enhanced.go+++ b/internal/notifications/webhook_enhanced.go@@ -65,6 +65,11 @@ type WebhookPayloadData struct {ResolvedAt string // RFC3339 timestamp when alert was resolvedResolvedAtISO string // Same as ResolvedAt (alias for template consistency)+ // Tenant identity (multi-tenant orgs and MSP client runtimes).+ // Empty on plain single-tenant installs.+ TenantID string+ TenantName string+// Additional contextMetadata map[string]interface{}CustomFields map[string]interface{}diff --git a/internal/notifications/webhook_templates.go b/internal/notifications/webhook_templates.goindex f80a5d0ed3..4497b94f90 100644--- a/internal/notifications/webhook_templates.go+++ b/internal/notifications/webhook_templates.go@@ -545,7 +545,11 @@ View in Pulse: {{.Instance}}`,"threshold": {{.Threshold}},"start_time": "{{.StartTime | jsonString}}","duration": "{{.Duration | jsonString}}"- },+ },{{if .TenantID}}+ "tenant": {+ "id": "{{.TenantID | jsonString}}",+ "name": "{{.TenantName | jsonString}}"+ },{{end}}"timestamp": "{{.Timestamp | jsonString}}","source": "pulse-monitoring"}`,@@ -559,7 +563,11 @@ View in Pulse: {{.Instance}}`,"message": "{{.Message | jsonString}}","start_time": "{{.StartTime | jsonString}}","duration": "{{.Duration | jsonString}}"- },+ },{{if .TenantID}}+ "tenant": {+ "id": "{{.TenantID | jsonString}}",+ "name": "{{.TenantName | jsonString}}"+ },{{end}}"resolved_at": "{{.ResolvedAt | jsonString}}","timestamp": "{{.Timestamp | jsonString}}","source": "pulse-monitoring"diff --git a/internal/notifications/webhook_tenant_identity_test.go b/internal/notifications/webhook_tenant_identity_test.gonew file mode 100644index 0000000000..8d1947c2d0--- /dev/null+++ b/internal/notifications/webhook_tenant_identity_test.go@@ -0,0 +1,120 @@+package notifications++import (+ "encoding/json"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func tenantIdentityTestAlert() *alerts.Alert {+ return &alerts.Alert{+ ID: "alert-1",+ Type: "cpu",+ Level: alerts.AlertLevelCritical,+ ResourceName: "web-01",+ Node: "pve1",+ Message: "CPU usage above threshold",+ Value: 95.0,+ Threshold: 90.0,+ StartTime: time.Now().Add(-5 * time.Minute),+ }+}++func TestPrepareWebhookDataNoTenantIdentityByDefault(t *testing.T) {+ t.Setenv("PULSE_TENANT_ID", "")+ t.Setenv("PULSE_TENANT_NAME", "")+ nm := NewNotificationManager("http://pulse.local")++ data := nm.prepareWebhookData(tenantIdentityTestAlert(), nil)+ assert.Empty(t, data.TenantID)+ assert.Empty(t, data.TenantName)+}++func TestPrepareWebhookDataTenantIdentityFromEnv(t *testing.T) {+ t.Setenv("PULSE_TENANT_ID", "client-acme")+ t.Setenv("PULSE_TENANT_NAME", "Acme Corp")+ nm := NewNotificationManager("http://pulse.local")++ data := nm.prepareWebhookData(tenantIdentityTestAlert(), nil)+ assert.Equal(t, "client-acme", data.TenantID)+ assert.Equal(t, "Acme Corp", data.TenantName)+}++func TestPrepareWebhookDataTenantNameFallsBackToID(t *testing.T) {+ t.Setenv("PULSE_TENANT_ID", "client-acme")+ t.Setenv("PULSE_TENANT_NAME", "")+ nm := NewNotificationManager("http://pulse.local")++ data := nm.prepareWebhookData(tenantIdentityTestAlert(), nil)+ assert.Equal(t, "client-acme", data.TenantID)+ assert.Equal(t, "client-acme", data.TenantName)+}++func TestTenantIdentityResolverOverridesEnv(t *testing.T) {+ t.Setenv("PULSE_TENANT_ID", "env-tenant")+ t.Setenv("PULSE_TENANT_NAME", "Env Tenant")+ nm := NewNotificationManager("http://pulse.local")+ nm.SetTenantIdentityResolver(func() (string, string) {+ return "org-beta", "Beta GmbH"+ })++ data := nm.prepareWebhookData(tenantIdentityTestAlert(), nil)+ assert.Equal(t, "org-beta", data.TenantID)+ assert.Equal(t, "Beta GmbH", data.TenantName)+}++func TestTenantIdentityResolverEmptyIDKeepsEnvDefaults(t *testing.T) {+ t.Setenv("PULSE_TENANT_ID", "env-tenant")+ t.Setenv("PULSE_TENANT_NAME", "Env Tenant")+ nm := NewNotificationManager("http://pulse.local")+ nm.SetTenantIdentityResolver(func() (string, string) {+ return "", "ignored"+ })++ data := nm.prepareWebhookData(tenantIdentityTestAlert(), nil)+ assert.Equal(t, "env-tenant", data.TenantID)+ assert.Equal(t, "Env Tenant", data.TenantName)+}++// The generic service template must emit a tenant block when tenant identity+// is configured and omit it entirely when it is not, staying valid JSON in+// both shapes.+func TestGenericTemplateTenantBlock(t *testing.T) {+ var genericTemplate string+ for _, tmpl := range GetWebhookTemplates() {+ if tmpl.Service == "generic" {+ genericTemplate = tmpl.PayloadTemplate+ break+ }+ }+ require.NotEmpty(t, genericTemplate)++ t.Setenv("PULSE_TENANT_ID", "client-acme")+ t.Setenv("PULSE_TENANT_NAME", "Acme Corp")+ nm := NewNotificationManager("http://pulse.local")++ data := nm.prepareWebhookData(tenantIdentityTestAlert(), nil)+ payload, err := nm.generatePayloadFromTemplateWithService(genericTemplate, data, "generic")+ require.NoError(t, err)++ var decoded map[string]interface{}+ require.NoError(t, json.Unmarshal(payload, &decoded))+ tenant, ok := decoded["tenant"].(map[string]interface{})+ require.True(t, ok, "tenant block missing from generic payload: %s", payload)+ assert.Equal(t, "client-acme", tenant["id"])+ assert.Equal(t, "Acme Corp", tenant["name"])++ // Without tenant identity the block is omitted.+ data.TenantID = ""+ data.TenantName = ""+ payload, err = nm.generatePayloadFromTemplateWithService(genericTemplate, data, "generic")+ require.NoError(t, err)+ decoded = map[string]interface{}{}+ require.NoError(t, json.Unmarshal(payload, &decoded))+ _, hasTenant := decoded["tenant"]+ assert.False(t, hasTenant)+}