Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Add entitlement-gated report branding

rcourtmand6964832a069
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 186389ada6..f39e7f6ec7 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -130,6 +130,11 @@ reverse.
command transport as the normal lifecycle install helpers, while failing
closed unless hosted mode is active, the target org exists, and the minted
`agent:report` token remains scoped to that tenant workspace.
+ Provider-hosted MSP report branding must not alter agent enrollment or
+ ingest authority. Agents continue to report into one tenant Pulse runtime
+ with tenant-local tokens; branding is report rendering configuration inside
+ that runtime, not a control-plane token, agent profile, or cross-client
+ ingest path.
20. `internal/api/config_setup_handlers.go` shared with `api-contracts`: auto-register and setup handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.
21. `internal/api/setup_script_render.go` shared with `api-contracts`, `storage-recovery`: the generated Proxmox setup-script is a shared boundary across agent lifecycle (forced-command keys, install/uninstall edits), API contracts (rendered token shape and encoded rerun URL), and storage/recovery (backup visibility grants, Pulse-managed temperature SSH keys, and SMART disk-temperature collection).
PBS setup-script auto-registration remains lifecycle-owned bootstrap
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index ea754b6ae8..2de00cecc3 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -180,6 +180,17 @@ persistence, org binding, token metadata, and already-initialized tenant
monitor refresh behavior. Provider-hosted MSP control-plane proofs may exercise
that helper, but they must not create a second control-plane-only token path.
+Performance report branding is a canonical reporting API payload boundary.
+Reporting handlers may attach `ReportBranding` to the existing single-resource
+and multi-resource report request contracts by combining provider-default
+runtime configuration with an optional tenant-local `system.json` workspace
+override. The API must pass the active `white_label` entitlement state into the
+reporting layer, and the reporting layer remains the final gate: an unentitled
+tenant runtime must render the normal Pulse report identity even if branding
+configuration is present. Provider-hosted MSP proofs may exercise branding
+through tenant runtimes, but the control plane must not gain MSP-specific report
+generation plumbing or cross-client report content.
+
Pulse Account workspace summaries carry setup state as a backend-owned payload
contract. Browser bootstrap and `/api/portal/dashboard` workspace entries may
include `setup_status` with only `ready`, `setup_path`, `install_agents`,
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index e754927791..ae6a8338af 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -42,6 +42,13 @@ contract. `CP_DOCKER_NETWORK` names the provider ingress and support network,
not the client runtime boundary: each client workspace runtime must be created
on a derived per-tenant Docker bridge, and support containers must be explicitly
attached to that bridge before the tenant runtime is started.
+Provider-hosted MSP report branding is a tenant runtime configuration
+contract, not control-plane report generation. The control plane may accept
+provider-default report brand environment values and pass them into each tenant
+container as generic `PULSE_REPORT_PROVIDER_BRAND_*` runtime configuration, but
+the tenant Pulse runtime owns report rendering, per-workspace override loading,
+and the `white_label` entitlement gate. This keeps provider-hosted MSP
+Stripe-free and avoids a cloud-control-plane report data path across clients.
## Canonical Files
@@ -209,6 +216,12 @@ attached to that bridge before the tenant runtime is started.
retargeted across workspaces, org-bound agent install/report tokens must not
write into another client runtime, and rotated-out install tokens must fail
immediately.
+ Provider-default report branding is part of the same tenant environment
+ contract: `internal/cloudcp/docker/manager.go` may inject
+ `PULSE_REPORT_PROVIDER_BRAND_DISPLAY_NAME`, logo path/data, and logo format
+ into each tenant container, but it must not collect report data or render
+ PDFs in the control plane. Tenant-local reporting and tenant-local licensing
+ decide whether that configured brand appears.
10. `internal/cloudcp/provider_msp_backup.go` shared with `deployment-installability`: provider-hosted MSP backup is both a cloud-paid license/account/runtime continuity boundary and a deployment-installability recovery artifact boundary.
License-backed provider MSP backups must include the signed MSP license
file as a recovery artifact while exposing only license metadata in command
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index 3b5f6d4381..c34ba39bc9 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -185,6 +185,13 @@ surfaces.
containers through the host Docker socket, the provider data directory must
be mounted at the same absolute path inside the control-plane container that
the host Docker daemon will later use for tenant runtime bind mounts.
+ Provider-hosted MSP installability must also pass provider-default report
+ branding through the packaged tenant environment rather than requiring
+ report-specific operator provisioning. The deployable control-plane config
+ may carry `CP_REPORT_BRAND_*` values, and `internal/cloudcp/docker/manager.go`
+ translates those into generic tenant runtime `PULSE_REPORT_PROVIDER_BRAND_*`
+ variables; tenant Pulse runtimes still own report rendering and entitlement
+ enforcement.
`pulse-control-plane provider-msp status` is the non-mutating operational
companion to that proof: it must report registry readiness, tenant
state/health counts, stuck provisioning workspaces, Docker runtime
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index ddab0cee45..416e6d4f37 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -219,6 +219,11 @@ regression protection.
before returning it to AI runtime, but it must not scan run history broadly,
hydrate resource inventories, call models, or perform persistence fan-out as
part of router setup or generic request admission.
+ Report branding follows the same bounded-work rule. Reporting handlers may
+ read provider-default env configuration and a tenant-local system-settings
+ record when a report is generated, but router setup and normal protected
+ request handling must not scan tenants, hydrate cross-client state, read logo
+ files outside PDF rendering, or add report-specific control-plane fan-out.
API action-completion event bridging in `internal/api/router.go` follows
the same bounded-work rule: router wiring may connect the already-completed
action audit record to the agent SSE projection, but it must not perform
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index e891f4bc29..62e40d3368 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -110,6 +110,13 @@ controls as normal product settings.
`remoteControl` or `commandsEnabled` must not be used to imply that a
desired server state is already enforced on the agent when the applied
report is missing or divergent.
+ Report branding settings are also a trust-surface payload because they
+ can carry operator-authored names and logo material into generated PDFs.
+ `reportBranding` updates must validate object shape, supported keys,
+ string types, bounded lengths, newline-free values, supported logo formats,
+ and valid bounded base64 before persistence. Rendering custom branding
+ remains gated by the `white_label` entitlement in the reporting layer, so
+ storing a brand setting never becomes a free branding bypass.
16. `internal/cloudcp/auth/magiclink.go` shared with `cloud-paid`: control-plane magic-link HMAC handling is both a Pulse Cloud account-access boundary and a security/privacy token-secrecy boundary.
17. `internal/cloudcp/auth/magiclink_store.go` shared with `cloud-paid`: control-plane magic-link persistence is both a Pulse Cloud account-access boundary and a security/privacy storage-hardening boundary.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index e02212727d..5fd3bf01fc 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -71,6 +71,11 @@ token may allow agent reporting for the scoped tenant workspace, but it must not
grant backup visibility, recovery authority, or storage health privileges; those
remain governed by the setup-script and source-specific backup API boundaries
below.
+Tenant report branding settings are adjacent tenant-local configuration, not a
+storage or recovery product state. `reportBranding` persisted in a tenant
+runtime's `system.json` should be preserved by the existing tenant data
+backup/restore path, but it must not create cross-client report storage,
+restore scope, backup visibility, or recovery authority.
Generated Proxmox setup-script, runtime host-agent setup, and installer
auto-registration changes that affect backup visibility permissions are
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index ce1383b9c0..e834b3fc43 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -3760,6 +3760,51 @@ func TestContract_PerformanceReportTransportUsesCatalogDefinition(t *testing.T)
}
}
+func TestContract_ReportingRequestCarriesEntitledReportBranding(t *testing.T) {
+ engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}
+ original := reporting.GetEngine()
+ reporting.SetEngine(engine)
+ t.Cleanup(func() { reporting.SetEngine(original) })
+
+ service := pkglicensing.NewService()
+ service.SetCurrentForTesting(&pkglicensing.License{
+ Claims: pkglicensing.Claims{
+ LicenseID: "lic_contract_report_branding",
+ Email: "[email protected]",
+ Tier: pkglicensing.TierEnterprise,
+ },
+ ValidatedAt: time.Now(),
+ })
+ SetLicenseServiceProvider(reportBrandLicenseProvider{service: service})
+ t.Cleanup(func() { SetLicenseServiceProvider(nil) })
+
+ t.Setenv("PULSE_REPORT_PROVIDER_BRAND_DISPLAY_NAME", "Provider Default")
+ handler := NewReportingHandlers(nil, nil)
+ handler.SetSystemSettingsStore(reportBrandSettingsStore{settings: &config.SystemSettings{
+ ReportBranding: &config.ReportBrandSettings{DisplayName: "Client One"},
+ }})
+
+ req := httptest.NewRequest(http.MethodGet, "/api/reporting?resourceType=node&resourceId=node-1", nil)
+ rec := httptest.NewRecorder()
+ handler.HandleGenerateReport(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d body=%s", rec.Code, rec.Body.String())
+ }
+ if !engine.lastReq.Branding.Entitled {
+ t.Fatal("expected reporting request to carry white_label entitlement state")
+ }
+ if got := engine.lastReq.Branding.ProviderDefault.DisplayName; got != "Provider Default" {
+ t.Fatalf("provider brand = %q, want Provider Default", got)
+ }
+ if got := engine.lastReq.Branding.WorkspaceOverride.DisplayName; got != "Client One" {
+ t.Fatalf("workspace brand = %q, want Client One", got)
+ }
+ if got := engine.lastReq.Branding.EffectiveBrand(); got == nil || got.DisplayName != "Client One" {
+ t.Fatalf("effective brand should prefer workspace override, got %+v", got)
+ }
+}
+
func TestContract_ReportingCatalogRouteAccessibleWithoutReportingFeature(t *testing.T) {
rawToken := "reporting-catalog-contract-token-123.12345678"
record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead}, nil)
diff --git a/internal/api/licensing_bridge.go b/internal/api/licensing_bridge.go
index e8bf781d25..fb301030f3 100644
--- a/internal/api/licensing_bridge.go
+++ b/internal/api/licensing_bridge.go
@@ -56,6 +56,7 @@ const (
featureAuditLoggingValue = pkglicensing.FeatureAuditLogging
featureRBACValue = pkglicensing.FeatureRBAC
featureAdvancedReportingValue = pkglicensing.FeatureAdvancedReporting
+ featureWhiteLabelValue = pkglicensing.FeatureWhiteLabel
featureLongTermMetricsValue = pkglicensing.FeatureLongTermMetrics
featureDemoFixturesValue = pkglicensing.FeatureDemoFixtures
maxUsersLicenseGateKey = pkglicensing.MaxUsersLicenseGateKey
diff --git a/internal/api/metrics_reporting_handlers.go b/internal/api/metrics_reporting_handlers.go
index dd2e7979e3..9c56556d73 100644
--- a/internal/api/metrics_reporting_handlers.go
+++ b/internal/api/metrics_reporting_handlers.go
@@ -7,10 +7,12 @@ import (
"fmt"
"io"
"net/http"
+ "os"
"regexp"
"strings"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/rcourtman/pulse-go-rewrite/internal/recovery"
@@ -93,6 +95,11 @@ type ReportingHandlers struct {
mtMonitor *monitoring.MultiTenantMonitor
recoveryManager *recoverymanager.Manager
narratorResolver func(ctx context.Context) (reporting.Narrator, reporting.FleetNarrator, reporting.FindingsProvider)
+ settingsStore reportingSystemSettingsStore
+}
+
+type reportingSystemSettingsStore interface {
+ LoadSystemSettings() (*config.SystemSettings, error)
}
// SetNarratorResolver wires an optional resolver that returns the
@@ -107,6 +114,13 @@ func (h *ReportingHandlers) SetNarratorResolver(resolver func(ctx context.Contex
h.narratorResolver = resolver
}
+func (h *ReportingHandlers) SetSystemSettingsStore(store reportingSystemSettingsStore) {
+ if h == nil {
+ return
+ }
+ h.settingsStore = store
+}
+
func (h *ReportingHandlers) resolveNarrator(ctx context.Context) (reporting.Narrator, reporting.FleetNarrator, reporting.FindingsProvider) {
if h == nil || h.narratorResolver == nil {
return nil, nil, nil
@@ -114,6 +128,53 @@ func (h *ReportingHandlers) resolveNarrator(ctx context.Context) (reporting.Narr
return h.narratorResolver(ctx)
}
+func (h *ReportingHandlers) resolveReportBranding(ctx context.Context) reporting.ReportBranding {
+ service := getLicenseServiceForContext(ctx)
+ entitled := service != nil && service.HasFeature(featureWhiteLabelValue)
+
+ branding := reporting.ReportBranding{
+ Entitled: entitled,
+ ProviderDefault: reportBrandFromEnv(),
+ }
+ if h == nil || h.settingsStore == nil {
+ return branding
+ }
+ settings, err := h.settingsStore.LoadSystemSettings()
+ if err != nil || settings == nil {
+ return branding
+ }
+ if settings.ReportBranding != nil {
+ branding.WorkspaceOverride = reportBrandFromSettings(*settings.ReportBranding)
+ }
+ return branding
+}
+
+func reportBrandFromEnv() reporting.ReportBrand {
+ return reportBrandFromSettings(config.ReportBrandSettings{
+ DisplayName: os.Getenv("PULSE_REPORT_PROVIDER_BRAND_DISPLAY_NAME"),
+ LogoPath: os.Getenv("PULSE_REPORT_PROVIDER_BRAND_LOGO_PATH"),
+ LogoBase64: os.Getenv("PULSE_REPORT_PROVIDER_BRAND_LOGO_BASE64"),
+ LogoFormat: os.Getenv("PULSE_REPORT_PROVIDER_BRAND_LOGO_FORMAT"),
+ })
+}
+
+func reportBrandFromSettings(settings config.ReportBrandSettings) reporting.ReportBrand {
+ logoData, err := config.DecodeReportBrandLogoBase64(settings.LogoBase64)
+ if err != nil {
+ log.Warn().Err(err).Msg("Ignoring invalid report brand logoBase64")
+ }
+ format, ok := config.CanonicalReportBrandLogoFormat(settings.LogoFormat)
+ if !ok {
+ format = ""
+ }
+ return reporting.ReportBrand{
+ DisplayName: strings.TrimSpace(settings.DisplayName),
+ LogoPath: strings.TrimSpace(settings.LogoPath),
+ LogoData: logoData,
+ LogoFormat: format,
+ }
+}
+
func performanceReportDefinition() reporting.PerformanceReportDefinition {
return reporting.DescribePerformanceReport()
}
@@ -499,6 +560,7 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.
End: end,
Format: format,
Title: title,
+ Branding: h.resolveReportBranding(r.Context()),
}
// Enrich with resource data if monitor is available
@@ -869,6 +931,7 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *
End: end,
Title: title,
MetricType: metricType,
+ Branding: h.resolveReportBranding(r.Context()),
}
// Get monitor state for enrichment
@@ -899,6 +962,7 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *
End: end,
Format: format,
Title: title,
+ Branding: multiReq.Branding,
}
// Enrich with resource data
diff --git a/internal/api/reporting_handlers_test.go b/internal/api/reporting_handlers_test.go
index b302cf39e1..bd99e1a48b 100644
--- a/internal/api/reporting_handlers_test.go
+++ b/internal/api/reporting_handlers_test.go
@@ -1,6 +1,7 @@
package api
import (
+ "context"
"encoding/json"
"fmt"
"net/http"
@@ -10,7 +11,9 @@ import (
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
"github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
)
@@ -54,6 +57,22 @@ func (s *stubReportingEngine) FleetNarrativeFor(req reporting.MultiReportRequest
return &reporting.FleetNarrative{Source: reporting.NarrativeSourceHeuristic}, nil
}
+type reportBrandSettingsStore struct {
+ settings *config.SystemSettings
+}
+
+func (s reportBrandSettingsStore) LoadSystemSettings() (*config.SystemSettings, error) {
+ return s.settings, nil
+}
+
+type reportBrandLicenseProvider struct {
+ service *pkglicensing.Service
+}
+
+func (p reportBrandLicenseProvider) Service(context.Context) *pkglicensing.Service {
+ return p.service
+}
+
func TestReportingHandlers_MethodNotAllowed(t *testing.T) {
handler := NewReportingHandlers(nil, nil)
req := httptest.NewRequest(http.MethodPost, "/api/reporting", nil)
@@ -156,6 +175,55 @@ func TestReportingHandlers_GenerateReport(t *testing.T) {
}
}
+func TestReportingHandlers_AttachesEntitledReportBranding(t *testing.T) {
+ engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}
+ original := reporting.GetEngine()
+ reporting.SetEngine(engine)
+ t.Cleanup(func() { reporting.SetEngine(original) })
+
+ service := pkglicensing.NewService()
+ service.SetCurrentForTesting(&pkglicensing.License{
+ Claims: pkglicensing.Claims{
+ LicenseID: "lic_report_branding",
+ Email: "[email protected]",
+ Tier: pkglicensing.TierEnterprise,
+ },
+ ValidatedAt: time.Now(),
+ })
+ SetLicenseServiceProvider(reportBrandLicenseProvider{service: service})
+ t.Cleanup(func() { SetLicenseServiceProvider(nil) })
+
+ handler := NewReportingHandlers(nil, nil)
+ handler.SetSystemSettingsStore(reportBrandSettingsStore{settings: &config.SystemSettings{
+ ReportBranding: &config.ReportBrandSettings{
+ DisplayName: "Client Alpha MSP",
+ LogoBase64: "iVBORw0KGgo=",
+ LogoFormat: "png",
+ },
+ }})
+ t.Setenv("PULSE_REPORT_PROVIDER_BRAND_DISPLAY_NAME", "Provider Default")
+
+ req := httptest.NewRequest(http.MethodGet, "/api/reporting?format=pdf&resourceType=node&resourceId=node-1", nil)
+ rr := httptest.NewRecorder()
+ handler.HandleGenerateReport(rr, req)
+
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rr.Code, rr.Body.String())
+ }
+ if !engine.lastReq.Branding.Entitled {
+ t.Fatal("expected report branding to be marked entitled")
+ }
+ if got := engine.lastReq.Branding.ProviderDefault.DisplayName; got != "Provider Default" {
+ t.Fatalf("provider brand = %q, want Provider Default", got)
+ }
+ if got := engine.lastReq.Branding.WorkspaceOverride.DisplayName; got != "Client Alpha MSP" {
+ t.Fatalf("workspace brand = %q, want Client Alpha MSP", got)
+ }
+ if len(engine.lastReq.Branding.WorkspaceOverride.LogoData) == 0 {
+ t.Fatal("expected workspace logo base64 to be decoded into logo data")
+ }
+}
+
func TestReportingHandlers_GenerateReport_TrimsOptionalFields(t *testing.T) {
engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}
original := reporting.GetEngine()
diff --git a/internal/api/router.go b/internal/api/router.go
index bbf715c959..aaa25e3ce3 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -528,6 +528,7 @@ func (r *Router) setupRoutes() {
// Wire license service provider so middleware can access per-tenant license services
SetLicenseServiceProvider(r.licenseHandlers)
r.reportingHandlers = NewReportingHandlers(r.mtMonitor, recoveryManager)
+ r.reportingHandlers.SetSystemSettingsStore(r.persistence)
r.logHandlers = NewLogHandlers(r.config, r.persistence)
rbacHandlers := NewRBACHandlers(r.config, rbacProvider)
var magicLinkService *MagicLinkService
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 04304b14d5..ad658365cd 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -1882,6 +1882,62 @@ func TestSystemSettingsUpdatePreservesAPIOnlyAuthError(t *testing.T) {
}
}
+func TestSystemSettingsReportBrandingValidationRejectsUnsafePayload(t *testing.T) {
+ tests := []struct {
+ name string
+ raw map[string]interface{}
+ want string
+ }{
+ {
+ name: "non_object",
+ raw: map[string]interface{}{"reportBranding": "Client"},
+ want: "reportBranding must be an object",
+ },
+ {
+ name: "unsupported_key",
+ raw: map[string]interface{}{"reportBranding": map[string]interface{}{
+ "displayName": "Client",
+ "tenantID": "other-client",
+ }},
+ want: "reportBranding.tenantID is not supported",
+ },
+ {
+ name: "newline",
+ raw: map[string]interface{}{"reportBranding": map[string]interface{}{
+ "displayName": "Client\nName",
+ }},
+ want: "reportBranding.displayName must not contain newlines",
+ },
+ {
+ name: "invalid_logo_base64",
+ raw: map[string]interface{}{"reportBranding": map[string]interface{}{
+ "logoBase64": "not base64!",
+ }},
+ want: "reportBranding.logoBase64 must be valid base64",
+ },
+ {
+ name: "invalid_logo_format",
+ raw: map[string]interface{}{"reportBranding": map[string]interface{}{
+ "logoFormat": "svg",
+ }},
+ want: "reportBranding.logoFormat must be png, jpg, jpeg, gif, or empty",
+ },
+ }
+
+ for _, tt := range tests {
+ tt := tt
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateSystemSettings(nil, tt.raw)
+ if err == nil {
+ t.Fatalf("expected validation error containing %q", tt.want)
+ }
+ if !strings.Contains(err.Error(), tt.want) {
+ t.Fatalf("unexpected validation error: %v", err)
+ }
+ })
+ }
+}
+
func TestMockModeReadRequiresSettingsReadScope(t *testing.T) {
rawToken := "mock-mode-read-token-123.12345678"
record := newTokenRecord(t, rawToken, []string{config.ScopeMonitoringRead}, nil)
diff --git a/internal/api/system_settings.go b/internal/api/system_settings.go
index 16635297c9..d4f03994ec 100644
--- a/internal/api/system_settings.go
+++ b/internal/api/system_settings.go
@@ -314,6 +314,16 @@ func applyDiscoveryConfigOverrides(current config.DiscoveryConfig, cfgMap map[st
// validateSystemSettings validates settings before applying them
func validateSystemSettings(_ *config.SystemSettings, rawRequest map[string]interface{}) error {
+ if val, ok := rawRequest["reportBranding"]; ok {
+ settings, ok := val.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("reportBranding must be an object")
+ }
+ if err := validateReportBrandingSettings(settings); err != nil {
+ return err
+ }
+ }
+
if val, ok := rawRequest["pvePollingInterval"]; ok {
if interval, ok := val.(float64); ok {
if interval <= 0 {
@@ -591,6 +601,46 @@ func validateSystemSettings(_ *config.SystemSettings, rawRequest map[string]inte
return nil
}
+func validateReportBrandingSettings(settings map[string]interface{}) error {
+ allowed := map[string]struct{}{
+ "displayName": {},
+ "logoPath": {},
+ "logoBase64": {},
+ "logoFormat": {},
+ }
+ for key, val := range settings {
+ if _, ok := allowed[key]; !ok {
+ return fmt.Errorf("reportBranding.%s is not supported", key)
+ }
+ str, ok := val.(string)
+ if !ok {
+ return fmt.Errorf("reportBranding.%s must be a string", key)
+ }
+ if strings.ContainsAny(str, "\r\n") {
+ return fmt.Errorf("reportBranding.%s must not contain newlines", key)
+ }
+ switch key {
+ case "displayName":
+ if len(strings.TrimSpace(str)) > config.ReportBrandDisplayNameMaxLength {
+ return fmt.Errorf("reportBranding.displayName must be <= %d characters", config.ReportBrandDisplayNameMaxLength)
+ }
+ case "logoPath":
+ if len(strings.TrimSpace(str)) > config.ReportBrandLogoPathMaxLength {
+ return fmt.Errorf("reportBranding.logoPath must be <= %d characters", config.ReportBrandLogoPathMaxLength)
+ }
+ case "logoBase64":
+ if _, err := config.DecodeReportBrandLogoBase64(str); err != nil {
+ return fmt.Errorf("reportBranding.%s", err.Error())
+ }
+ case "logoFormat":
+ if _, ok := config.CanonicalReportBrandLogoFormat(str); !ok {
+ return fmt.Errorf("reportBranding.logoFormat must be png, jpg, jpeg, gif, or empty")
+ }
+ }
+ }
+ return nil
+}
+
// HandleGetSystemSettings returns the current system settings
func (h *SystemSettingsHandler) HandleGetSystemSettings(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
@@ -833,6 +883,11 @@ func (h *SystemSettingsHandler) HandleUpdateSystemSettings(w http.ResponseWriter
if _, ok := rawRequest["publicURL"]; ok {
settings.PublicURL = updates.PublicURL
}
+ // Allow per-runtime report branding overrides. The reporting layer still
+ // enforces the white_label entitlement before rendering these values.
+ if _, ok := rawRequest["reportBranding"]; ok {
+ settings.ReportBranding = updates.ReportBranding
+ }
// Boolean fields need special handling since false is a valid value
if _, ok := rawRequest["autoUpdateEnabled"]; ok {
diff --git a/internal/cloudcp/cloud_audit.go b/internal/cloudcp/cloud_audit.go
index 1ccdddf22c..464beb6dbb 100644
--- a/internal/cloudcp/cloud_audit.go
+++ b/internal/cloudcp/cloud_audit.go
@@ -118,10 +118,16 @@ func AuditCloud(ctx context.Context, cfg *CPConfig) (*CloudAuditReport, error) {
BaseDomain: baseDomainFromURL(cfg.BaseURL),
TrialActivationPublicKey: cfg.TrialActivationPublicKey,
TrustedProxyCIDRs: cfg.TrustedProxyCIDRs,
- MemoryLimit: cfg.TenantMemoryLimit,
- CPUShares: cfg.TenantCPUShares,
- TenantLogMaxSize: cfg.TenantLogMaxSize,
- TenantLogMaxFile: cfg.TenantLogMaxFile,
+ TenantReportBrand: cpDocker.TenantReportBrandConfig{
+ DisplayName: cfg.ReportBrandDisplayName,
+ LogoPath: cfg.ReportBrandLogoPath,
+ LogoBase64: cfg.ReportBrandLogoBase64,
+ LogoFormat: cfg.ReportBrandLogoFormat,
+ },
+ MemoryLimit: cfg.TenantMemoryLimit,
+ CPUShares: cfg.TenantCPUShares,
+ TenantLogMaxSize: cfg.TenantLogMaxSize,
+ TenantLogMaxFile: cfg.TenantLogMaxFile,
})
if err != nil {
report.DockerUnavailable = err.Error()
diff --git a/internal/cloudcp/config.go b/internal/cloudcp/config.go
index 29db4d5ea7..c4db9ae29f 100644
--- a/internal/cloudcp/config.go
+++ b/internal/cloudcp/config.go
@@ -13,6 +13,7 @@ import (
"time"
"github.com/joho/godotenv"
+ runtimeconfig "github.com/rcourtman/pulse-go-rewrite/internal/config"
pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
)
@@ -52,6 +53,10 @@ type CPConfig struct {
TenantCPUShares int64
TenantLogMaxSize string
TenantLogMaxFile int
+ ReportBrandDisplayName string // Provider-level default for tenant report PDFs
+ ReportBrandLogoPath string
+ ReportBrandLogoBase64 string
+ ReportBrandLogoFormat string
AllowDockerlessProvisioning bool
StorageGuardrailsEnabled bool
StorageRootPath string
@@ -213,6 +218,10 @@ func LoadConfig() (*CPConfig, error) {
TenantCPUShares: tenantCPUShares,
TenantLogMaxSize: envOrDefault("CP_TENANT_LOG_MAX_SIZE", "10m"),
TenantLogMaxFile: tenantLogMaxFile,
+ ReportBrandDisplayName: strings.TrimSpace(os.Getenv("CP_REPORT_BRAND_DISPLAY_NAME")),
+ ReportBrandLogoPath: strings.TrimSpace(os.Getenv("CP_REPORT_BRAND_LOGO_PATH")),
+ ReportBrandLogoBase64: strings.TrimSpace(os.Getenv("CP_REPORT_BRAND_LOGO_BASE64")),
+ ReportBrandLogoFormat: strings.TrimSpace(os.Getenv("CP_REPORT_BRAND_LOGO_FORMAT")),
AllowDockerlessProvisioning: envOrDefaultBool("CP_ALLOW_DOCKERLESS_PROVISIONING", false),
StorageGuardrailsEnabled: envOrDefaultBool("CP_STORAGE_GUARDRAILS_ENABLED", environment != "development"),
StorageRootPath: envOrDefault("CP_STORAGE_ROOT_PATH", "/"),
@@ -302,6 +311,18 @@ func (c *CPConfig) validate() error {
if c.TenantLogMaxFile <= 0 {
return fmt.Errorf("CP_TENANT_LOG_MAX_FILE must be greater than 0")
}
+ if len(strings.TrimSpace(c.ReportBrandDisplayName)) > runtimeconfig.ReportBrandDisplayNameMaxLength {
+ return fmt.Errorf("CP_REPORT_BRAND_DISPLAY_NAME must be <= %d characters", runtimeconfig.ReportBrandDisplayNameMaxLength)
+ }
+ if len(strings.TrimSpace(c.ReportBrandLogoPath)) > runtimeconfig.ReportBrandLogoPathMaxLength {
+ return fmt.Errorf("CP_REPORT_BRAND_LOGO_PATH must be <= %d characters", runtimeconfig.ReportBrandLogoPathMaxLength)
+ }
+ if _, err := runtimeconfig.DecodeReportBrandLogoBase64(c.ReportBrandLogoBase64); err != nil {
+ return fmt.Errorf("CP_REPORT_BRAND_LOGO_BASE64 %s", err.Error())
+ }
+ if _, ok := runtimeconfig.CanonicalReportBrandLogoFormat(c.ReportBrandLogoFormat); !ok {
+ return fmt.Errorf("CP_REPORT_BRAND_LOGO_FORMAT must be png, jpg, jpeg, gif, or empty")
+ }
if c.WebhookRateLimitPerMinute <= 0 {
return fmt.Errorf("CP_RL_WEBHOOK_PER_MINUTE must be greater than 0")
}
diff --git a/internal/cloudcp/config_test.go b/internal/cloudcp/config_test.go
index 9475805d21..761a7c9f45 100644
--- a/internal/cloudcp/config_test.go
+++ b/internal/cloudcp/config_test.go
@@ -523,6 +523,44 @@ func TestLoadConfig_ProviderHostedMSPDoesNotRequireStripe(t *testing.T) {
}
}
+func TestLoadConfig_ProviderHostedMSPReportBrandDefaults(t *testing.T) {
+ setProviderHostedMSPEnv(t)
+ t.Setenv("CP_REPORT_BRAND_DISPLAY_NAME", "Provider Default")
+ t.Setenv("CP_REPORT_BRAND_LOGO_PATH", "/etc/pulse/brand.png")
+ t.Setenv("CP_REPORT_BRAND_LOGO_BASE64", "iVBORw0KGgo=")
+ t.Setenv("CP_REPORT_BRAND_LOGO_FORMAT", "png")
+
+ cfg, err := LoadConfig()
+ if err != nil {
+ t.Fatalf("LoadConfig: %v", err)
+ }
+ if cfg.ReportBrandDisplayName != "Provider Default" {
+ t.Fatalf("ReportBrandDisplayName = %q, want Provider Default", cfg.ReportBrandDisplayName)
+ }
+ if cfg.ReportBrandLogoPath != "/etc/pulse/brand.png" {
+ t.Fatalf("ReportBrandLogoPath = %q", cfg.ReportBrandLogoPath)
+ }
+ if cfg.ReportBrandLogoBase64 != "iVBORw0KGgo=" {
+ t.Fatalf("ReportBrandLogoBase64 = %q", cfg.ReportBrandLogoBase64)
+ }
+ if cfg.ReportBrandLogoFormat != "png" {
+ t.Fatalf("ReportBrandLogoFormat = %q, want png", cfg.ReportBrandLogoFormat)
+ }
+}
+
+func TestLoadConfig_ReportBrandDefaultsRejectInvalidLogoFormat(t *testing.T) {
+ setProviderHostedMSPEnv(t)
+ t.Setenv("CP_REPORT_BRAND_LOGO_FORMAT", "svg")
+
+ _, err := LoadConfig()
+ if err == nil {
+ t.Fatal("expected invalid report brand logo format to fail config validation")
+ }
+ if !strings.Contains(err.Error(), "CP_REPORT_BRAND_LOGO_FORMAT must be png, jpg, jpeg, gif, or empty") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
func TestLoadConfig_ProviderHostedMSPRejectsStripeConfig(t *testing.T) {
for _, tc := range []struct {
name string
diff --git a/internal/cloudcp/docker/manager.go b/internal/cloudcp/docker/manager.go
index 71028a53d3..a2a51ca1ba 100644
--- a/internal/cloudcp/docker/manager.go
+++ b/internal/cloudcp/docker/manager.go
@@ -30,6 +30,7 @@ type ManagerConfig struct {
BaseDomain string
TrialActivationPublicKey string
TrustedProxyCIDRs []string
+ TenantReportBrand TenantReportBrandConfig
MemoryLimit int64 // bytes
CPUShares int64
TenantLogMaxSize string
@@ -37,6 +38,13 @@ type ManagerConfig struct {
ContainerPort int // port inside the container (default 7655)
}
+type TenantReportBrandConfig struct {
+ DisplayName string
+ LogoPath string
+ LogoBase64 string
+ LogoFormat string
+}
+
// Manager orchestrates Docker containers for tenant lifecycle.
type Manager struct {
cli *client.Client
@@ -504,7 +512,7 @@ func (m *Manager) CreateAndStart(ctx context.Context, tenantID, tenantDataDir st
Config: &container.Config{
Image: m.cfg.Image,
Labels: labels,
- Env: tenantEnv(tenantID, m.cfg.BaseDomain, m.cfg.TrialActivationPublicKey, m.tenantTrustedProxyCIDRs(ctx, tenantNetworkName)),
+ Env: tenantEnv(tenantID, m.cfg.BaseDomain, m.cfg.TrialActivationPublicKey, m.tenantTrustedProxyCIDRs(ctx, tenantNetworkName), m.cfg.TenantReportBrand),
},
HostConfig: &container.HostConfig{
RestartPolicy: container.RestartPolicy{Name: "unless-stopped"},
@@ -576,7 +584,7 @@ func tenantRuntimeOwnershipPaths() []string {
}
}
-func tenantEnv(tenantID, baseDomain, trialActivationPublicKey string, trustedProxyCIDRs []string) []string {
+func tenantEnv(tenantID, baseDomain, trialActivationPublicKey string, trustedProxyCIDRs []string, reportBrand TenantReportBrandConfig) []string {
routing := CanonicalTenantRuntimeRouting(tenantID, baseDomain)
tenantID = strings.TrimSpace(tenantID)
@@ -598,6 +606,18 @@ func tenantEnv(tenantID, baseDomain, trialActivationPublicKey string, trustedPro
if len(trustedProxyCIDRs) > 0 {
env = append(env, "PULSE_TRUSTED_PROXY_CIDRS="+strings.Join(trustedProxyCIDRs, ","))
}
+ if value := strings.TrimSpace(reportBrand.DisplayName); value != "" {
+ env = append(env, "PULSE_REPORT_PROVIDER_BRAND_DISPLAY_NAME="+value)
+ }
+ if value := strings.TrimSpace(reportBrand.LogoPath); value != "" {
+ env = append(env, "PULSE_REPORT_PROVIDER_BRAND_LOGO_PATH="+value)
+ }
+ if value := strings.TrimSpace(reportBrand.LogoBase64); value != "" {
+ env = append(env, "PULSE_REPORT_PROVIDER_BRAND_LOGO_BASE64="+value)
+ }
+ if value := strings.TrimSpace(reportBrand.LogoFormat); value != "" {
+ env = append(env, "PULSE_REPORT_PROVIDER_BRAND_LOGO_FORMAT="+value)
+ }
return env
}
diff --git a/internal/cloudcp/docker/manager_test.go b/internal/cloudcp/docker/manager_test.go
index ed9a0c89a8..1d8f8917cd 100644
--- a/internal/cloudcp/docker/manager_test.go
+++ b/internal/cloudcp/docker/manager_test.go
@@ -73,7 +73,7 @@ func TestTenantMountsKeepImmutableFilesReadOnly(t *testing.T) {
func TestTenantEnvIncludesImmutableOwnershipContract(t *testing.T) {
t.Parallel()
- env := tenantEnv("t-example", "cloud.pulserelay.pro", "pubkey-123", []string{"172.18.0.0/16", "127.0.0.1/32"})
+ env := tenantEnv("t-example", "cloud.pulserelay.pro", "pubkey-123", []string{"172.18.0.0/16", "127.0.0.1/32"}, TenantReportBrandConfig{})
want := map[string]bool{
"PULSE_DATA_DIR=/etc/pulse": true,
"PULSE_HOSTED_MODE=true": true,
@@ -181,7 +181,7 @@ func TestHealthCheckPrefersProviderMSPIsolatedTenantNetwork(t *testing.T) {
func TestTenantEnvLowercasesPublicURLHost(t *testing.T) {
t.Parallel()
- env := tenantEnv("T-AbCd123", "Cloud.PulseRelay.Pro", "", nil)
+ env := tenantEnv("T-AbCd123", "Cloud.PulseRelay.Pro", "", nil, TenantReportBrandConfig{})
want := "PULSE_PUBLIC_URL=https://t-abcd123.cloud.pulserelay.pro"
for _, item := range env {
if item == want {
@@ -194,7 +194,7 @@ func TestTenantEnvLowercasesPublicURLHost(t *testing.T) {
func TestTenantEnvOmitsPublicURLWithoutTenantContext(t *testing.T) {
t.Parallel()
- env := tenantEnv("", "", "", nil)
+ env := tenantEnv("", "", "", nil, TenantReportBrandConfig{})
sawTenantID := false
for _, item := range env {
if strings.HasPrefix(item, "PULSE_PUBLIC_URL=") {
@@ -209,6 +209,27 @@ func TestTenantEnvOmitsPublicURLWithoutTenantContext(t *testing.T) {
}
}
+func TestTenantEnvIncludesProviderReportBrandDefaults(t *testing.T) {
+ t.Parallel()
+
+ env := tenantEnv("t-acme", "msp.example.com", "", nil, TenantReportBrandConfig{
+ DisplayName: "Acme Managed IT",
+ LogoBase64: "iVBORw0KGgo=",
+ LogoFormat: "png",
+ })
+ want := map[string]bool{
+ "PULSE_REPORT_PROVIDER_BRAND_DISPLAY_NAME=Acme Managed IT": true,
+ "PULSE_REPORT_PROVIDER_BRAND_LOGO_BASE64=iVBORw0KGgo=": true,
+ "PULSE_REPORT_PROVIDER_BRAND_LOGO_FORMAT=png": true,
+ }
+ for _, item := range env {
+ delete(want, item)
+ }
+ if len(want) > 0 {
+ t.Fatalf("tenantEnv() missing report brand env items: %v; env=%v", want, env)
+ }
+}
+
func TestTenantRuntimeLogConfigBoundsJSONLogs(t *testing.T) {
t.Parallel()
diff --git a/internal/cloudcp/server.go b/internal/cloudcp/server.go
index a82884e681..05096c300f 100644
--- a/internal/cloudcp/server.go
+++ b/internal/cloudcp/server.go
@@ -59,10 +59,16 @@ func Run(ctx context.Context, version string) error {
BaseDomain: baseDomainFromURL(cfg.BaseURL),
TrialActivationPublicKey: cfg.TrialActivationPublicKey,
TrustedProxyCIDRs: cfg.TrustedProxyCIDRs,
- MemoryLimit: cfg.TenantMemoryLimit,
- CPUShares: cfg.TenantCPUShares,
- TenantLogMaxSize: cfg.TenantLogMaxSize,
- TenantLogMaxFile: cfg.TenantLogMaxFile,
+ TenantReportBrand: cpDocker.TenantReportBrandConfig{
+ DisplayName: cfg.ReportBrandDisplayName,
+ LogoPath: cfg.ReportBrandLogoPath,
+ LogoBase64: cfg.ReportBrandLogoBase64,
+ LogoFormat: cfg.ReportBrandLogoFormat,
+ },
+ MemoryLimit: cfg.TenantMemoryLimit,
+ CPUShares: cfg.TenantCPUShares,
+ TenantLogMaxSize: cfg.TenantLogMaxSize,
+ TenantLogMaxFile: cfg.TenantLogMaxFile,
})
if err != nil {
log.Warn().Err(err).Msg("Docker unavailable — container management disabled")
diff --git a/internal/cloudcp/tenant_runtime_rollout.go b/internal/cloudcp/tenant_runtime_rollout.go
index 1bdd5ff46b..dd402d3876 100644
--- a/internal/cloudcp/tenant_runtime_rollout.go
+++ b/internal/cloudcp/tenant_runtime_rollout.go
@@ -222,10 +222,16 @@ func newTenantRuntimeRolloutServiceFromConfig(
BaseDomain: baseDomainFromURL(cfg.BaseURL),
TrialActivationPublicKey: cfg.TrialActivationPublicKey,
TrustedProxyCIDRs: cfg.TrustedProxyCIDRs,
- MemoryLimit: cfg.TenantMemoryLimit,
- CPUShares: cfg.TenantCPUShares,
- TenantLogMaxSize: cfg.TenantLogMaxSize,
- TenantLogMaxFile: cfg.TenantLogMaxFile,
+ TenantReportBrand: cpDocker.TenantReportBrandConfig{
+ DisplayName: cfg.ReportBrandDisplayName,
+ LogoPath: cfg.ReportBrandLogoPath,
+ LogoBase64: cfg.ReportBrandLogoBase64,
+ LogoFormat: cfg.ReportBrandLogoFormat,
+ },
+ MemoryLimit: cfg.TenantMemoryLimit,
+ CPUShares: cfg.TenantCPUShares,
+ TenantLogMaxSize: cfg.TenantLogMaxSize,
+ TenantLogMaxFile: cfg.TenantLogMaxFile,
})
if err != nil {
_ = reg.Close()
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index 0522015a3f..f1eb2e2504 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -1351,36 +1351,37 @@ type NodesConfig struct {
// SystemSettings represents system configuration settings
type SystemSettings struct {
- PVEPollingInterval int `json:"pvePollingInterval"` // PVE polling interval in seconds
- PBSPollingInterval int `json:"pbsPollingInterval"` // PBS polling interval in seconds
- PMGPollingInterval int `json:"pmgPollingInterval"` // PMG polling interval in seconds
- BackupPollingInterval int `json:"backupPollingInterval,omitempty"`
- BackupPollingEnabled *bool `json:"backupPollingEnabled,omitempty"`
- AdaptivePollingEnabled *bool `json:"adaptivePollingEnabled,omitempty"`
- AdaptivePollingBaseInterval int `json:"adaptivePollingBaseInterval,omitempty"`
- AdaptivePollingMinInterval int `json:"adaptivePollingMinInterval,omitempty"`
- AdaptivePollingMaxInterval int `json:"adaptivePollingMaxInterval,omitempty"`
- FrontendPort int `json:"frontendPort,omitempty"`
- AllowedOrigins string `json:"allowedOrigins,omitempty"`
- ConnectionTimeout int `json:"connectionTimeout,omitempty"`
- UpdateChannel string `json:"updateChannel,omitempty"`
- AutoUpdateEnabled bool `json:"autoUpdateEnabled"` // Removed omitempty so false is saved
- AutoUpdateCheckInterval int `json:"autoUpdateCheckInterval,omitempty"`
- AutoUpdateTime string `json:"autoUpdateTime,omitempty"`
- LogLevel string `json:"logLevel,omitempty"`
- DiscoveryEnabled bool `json:"discoveryEnabled"`
- DiscoverySubnet string `json:"discoverySubnet,omitempty"`
- DiscoveryConfig DiscoveryConfig `json:"discoveryConfig"`
- Theme string `json:"theme,omitempty"` // User theme preference: "light", "dark", or empty for system default
- FullWidthMode bool `json:"fullWidthMode"` // Full-width layout mode preference
- AllowEmbedding bool `json:"allowEmbedding"` // Allow iframe embedding
- AllowedEmbedOrigins string `json:"allowedEmbedOrigins,omitempty"` // Comma-separated list of allowed origins for embedding
- TemperatureMonitoringEnabled bool `json:"temperatureMonitoringEnabled"`
- DNSCacheTimeout int `json:"dnsCacheTimeout,omitempty"` // DNS cache timeout in seconds (0 = default 5 minutes)
- SSHPort int `json:"sshPort,omitempty"` // Default SSH port for temperature monitoring (0 = use 22)
- WebhookAllowedPrivateCIDRs string `json:"webhookAllowedPrivateCIDRs,omitempty"` // Comma-separated list of private CIDR ranges allowed for webhooks (e.g., "192.168.1.0/24,10.0.0.0/8")
- HideLocalLogin bool `json:"hideLocalLogin"` // Hide local login form (username/password)
- PublicURL string `json:"publicURL,omitempty"` // Public URL for email notifications (e.g., http://198.51.100.100:8080)
+ PVEPollingInterval int `json:"pvePollingInterval"` // PVE polling interval in seconds
+ PBSPollingInterval int `json:"pbsPollingInterval"` // PBS polling interval in seconds
+ PMGPollingInterval int `json:"pmgPollingInterval"` // PMG polling interval in seconds
+ BackupPollingInterval int `json:"backupPollingInterval,omitempty"`
+ BackupPollingEnabled *bool `json:"backupPollingEnabled,omitempty"`
+ AdaptivePollingEnabled *bool `json:"adaptivePollingEnabled,omitempty"`
+ AdaptivePollingBaseInterval int `json:"adaptivePollingBaseInterval,omitempty"`
+ AdaptivePollingMinInterval int `json:"adaptivePollingMinInterval,omitempty"`
+ AdaptivePollingMaxInterval int `json:"adaptivePollingMaxInterval,omitempty"`
+ FrontendPort int `json:"frontendPort,omitempty"`
+ AllowedOrigins string `json:"allowedOrigins,omitempty"`
+ ConnectionTimeout int `json:"connectionTimeout,omitempty"`
+ UpdateChannel string `json:"updateChannel,omitempty"`
+ AutoUpdateEnabled bool `json:"autoUpdateEnabled"` // Removed omitempty so false is saved
+ AutoUpdateCheckInterval int `json:"autoUpdateCheckInterval,omitempty"`
+ AutoUpdateTime string `json:"autoUpdateTime,omitempty"`
+ LogLevel string `json:"logLevel,omitempty"`
+ DiscoveryEnabled bool `json:"discoveryEnabled"`
+ DiscoverySubnet string `json:"discoverySubnet,omitempty"`
+ DiscoveryConfig DiscoveryConfig `json:"discoveryConfig"`
+ Theme string `json:"theme,omitempty"` // User theme preference: "light", "dark", or empty for system default
+ FullWidthMode bool `json:"fullWidthMode"` // Full-width layout mode preference
+ AllowEmbedding bool `json:"allowEmbedding"` // Allow iframe embedding
+ AllowedEmbedOrigins string `json:"allowedEmbedOrigins,omitempty"` // Comma-separated list of allowed origins for embedding
+ TemperatureMonitoringEnabled bool `json:"temperatureMonitoringEnabled"`
+ DNSCacheTimeout int `json:"dnsCacheTimeout,omitempty"` // DNS cache timeout in seconds (0 = default 5 minutes)
+ SSHPort int `json:"sshPort,omitempty"` // Default SSH port for temperature monitoring (0 = use 22)
+ WebhookAllowedPrivateCIDRs string `json:"webhookAllowedPrivateCIDRs,omitempty"` // Comma-separated list of private CIDR ranges allowed for webhooks (e.g., "192.168.1.0/24,10.0.0.0/8")
+ HideLocalLogin bool `json:"hideLocalLogin"` // Hide local login form (username/password)
+ PublicURL string `json:"publicURL,omitempty"` // Public URL for email notifications (e.g., http://198.51.100.100:8080)
+ ReportBranding *ReportBrandSettings `json:"reportBranding,omitempty"` // Optional per-workspace report branding override
// Metrics retention configuration (in hours)
// These control how long historical metrics are stored at each aggregation tier.
@@ -1404,6 +1405,16 @@ type SystemSettings struct {
// APIToken is not persisted in system settings; API tokens are managed in api_tokens.json.
}
+// ReportBrandSettings stores optional report-brand override material for this
+// Pulse runtime. In provider-hosted MSP each runtime is one client workspace,
+// so this is naturally per-client without special reporting plumbing.
+type ReportBrandSettings struct {
+ DisplayName string `json:"displayName,omitempty"`
+ LogoPath string `json:"logoPath,omitempty"`
+ LogoBase64 string `json:"logoBase64,omitempty"`
+ LogoFormat string `json:"logoFormat,omitempty"`
+}
+
// DefaultSystemSettings returns a SystemSettings struct populated with sane defaults.
func DefaultSystemSettings() *SystemSettings {
defaultDiscovery := DefaultDiscoveryConfig()
diff --git a/internal/config/report_branding.go b/internal/config/report_branding.go
new file mode 100644
index 0000000000..3e8cf4f8ec
--- /dev/null
+++ b/internal/config/report_branding.go
@@ -0,0 +1,50 @@
+package config
+
+import (
+ "encoding/base64"
+ "fmt"
+ "strings"
+)
+
+const (
+ ReportBrandDisplayNameMaxLength = 120
+ ReportBrandLogoPathMaxLength = 1024
+ ReportBrandLogoBase64MaxLength = 48 * 1024
+)
+
+// DecodeReportBrandLogoBase64 decodes a plain base64 value or a data URL value.
+func DecodeReportBrandLogoBase64(raw string) ([]byte, error) {
+ value := strings.TrimSpace(raw)
+ if value == "" {
+ return nil, nil
+ }
+ if idx := strings.Index(value, ";base64,"); idx >= 0 {
+ value = value[idx+len(";base64,"):]
+ }
+ if len(value) > ReportBrandLogoBase64MaxLength {
+ return nil, fmt.Errorf("logoBase64 must be <= %d characters", ReportBrandLogoBase64MaxLength)
+ }
+ if decoded, err := base64.StdEncoding.DecodeString(value); err == nil {
+ return decoded, nil
+ }
+ decoded, err := base64.RawStdEncoding.DecodeString(value)
+ if err != nil {
+ return nil, fmt.Errorf("logoBase64 must be valid base64")
+ }
+ return decoded, nil
+}
+
+func CanonicalReportBrandLogoFormat(format string) (string, bool) {
+ switch strings.ToLower(strings.TrimSpace(format)) {
+ case "":
+ return "", true
+ case "png":
+ return "png", true
+ case "jpg", "jpeg":
+ return "jpg", true
+ case "gif":
+ return "gif", true
+ default:
+ return "", false
+ }
+}
diff --git a/internal/notifications/provider_client_isolation_test.go b/internal/notifications/provider_client_isolation_test.go
new file mode 100644
index 0000000000..78498b7d0d
--- /dev/null
+++ b/internal/notifications/provider_client_isolation_test.go
@@ -0,0 +1,131 @@
+package notifications
+
+import (
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/stretchr/testify/require"
+)
+
+func TestProviderClientWebhookRoutingStaysRuntimeLocal(t *testing.T) {
+ t.Parallel()
+
+ clientAReceiver := newWebhookCapture()
+ clientAServer := newIPv4HTTPServer(t, clientAReceiver)
+ defer clientAServer.Close()
+
+ clientBReceiver := newWebhookCapture()
+ clientBServer := newIPv4HTTPServer(t, clientBReceiver)
+ defer clientBServer.Close()
+
+ clientA := NewNotificationManagerWithDataDir("https://client-a.example.test", t.TempDir())
+ t.Cleanup(clientA.Stop)
+ require.NoError(t, clientA.UpdateAllowedPrivateCIDRs("127.0.0.1"))
+
+ clientB := NewNotificationManagerWithDataDir("https://client-b.example.test", t.TempDir())
+ t.Cleanup(clientB.Stop)
+ require.NoError(t, clientB.UpdateAllowedPrivateCIDRs("127.0.0.1"))
+
+ alertA := providerClientAlert("alert-client-a", "client-a-node")
+ alertB := providerClientAlert("alert-client-b", "client-b-node")
+
+ err := clientA.SendEnhancedWebhook(EnhancedWebhookConfig{
+ WebhookConfig: WebhookConfig{
+ Name: "client-a-gotify",
+ URL: clientAServer.URL + "/message?token=client-a-token",
+ Enabled: true,
+ Service: "gotify",
+ },
+ Service: "gotify",
+ }, alertA)
+ require.NoError(t, err)
+
+ genericTemplate := webhookPayloadTemplateForTest(t, "generic")
+ err = clientB.SendEnhancedWebhook(EnhancedWebhookConfig{
+ WebhookConfig: WebhookConfig{
+ Name: "client-b-generic",
+ URL: clientBServer.URL + "/hook",
+ Enabled: true,
+ Service: "generic",
+ },
+ Service: "generic",
+ PayloadTemplate: genericTemplate,
+ }, alertB)
+ require.NoError(t, err)
+
+ clientABodies := clientAReceiver.bodies()
+ clientBBodies := clientBReceiver.bodies()
+ require.Len(t, clientABodies, 1)
+ require.Len(t, clientBBodies, 1)
+
+ if !strings.Contains(clientABodies[0], "alert-client-a") || !strings.Contains(clientABodies[0], "client-a-node") {
+ t.Fatalf("client A Gotify payload missing client A event: %s", clientABodies[0])
+ }
+ if strings.Contains(clientABodies[0], "alert-client-b") || strings.Contains(clientABodies[0], "client-b-node") {
+ t.Fatalf("client A Gotify payload included client B event: %s", clientABodies[0])
+ }
+
+ if !strings.Contains(clientBBodies[0], "alert-client-b") || !strings.Contains(clientBBodies[0], "client-b-node") {
+ t.Fatalf("client B generic payload missing client B event: %s", clientBBodies[0])
+ }
+ if strings.Contains(clientBBodies[0], "alert-client-a") || strings.Contains(clientBBodies[0], "client-a-node") {
+ t.Fatalf("client B generic payload included client A event: %s", clientBBodies[0])
+ }
+}
+
+func providerClientAlert(id, resource string) *alerts.Alert {
+ return &alerts.Alert{
+ ID: id,
+ Type: "cpu",
+ Level: alerts.AlertLevelCritical,
+ ResourceName: resource,
+ Node: resource,
+ Message: "CPU threshold exceeded for " + resource,
+ Value: 96,
+ Threshold: 90,
+ StartTime: time.Now().UTC().Add(-5 * time.Minute),
+ Instance: "https://" + resource + ".example.test",
+ }
+}
+
+func webhookPayloadTemplateForTest(t *testing.T, service string) string {
+ t.Helper()
+ for _, tmpl := range GetWebhookTemplates() {
+ if tmpl.Service == service {
+ return tmpl.PayloadTemplate
+ }
+ }
+ t.Fatalf("missing webhook template %q", service)
+ return ""
+}
+
+type webhookCapture struct {
+ mu sync.Mutex
+ values []string
+}
+
+func newWebhookCapture() *webhookCapture {
+ return &webhookCapture{}
+}
+
+func (c *webhookCapture) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ c.mu.Lock()
+ c.values = append(c.values, string(body))
+ c.mu.Unlock()
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte("ok"))
+}
+
+func (c *webhookCapture) bodies() []string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ out := make([]string, len(c.values))
+ copy(out, c.values)
+ return out
+}
diff --git a/pkg/licensing/features.go b/pkg/licensing/features.go
index 7a64e95821..a920525e89 100644
--- a/pkg/licensing/features.go
+++ b/pkg/licensing/features.go
@@ -36,7 +36,7 @@ const (
// MSP/Enterprise tier features
FeatureMultiUser = "multi_user" // Multi-user (likely merged with RBAC)
- FeatureWhiteLabel = "white_label" // Custom branding - NOT IMPLEMENTED YET
+ FeatureWhiteLabel = "white_label" // Custom report branding
FeatureMultiTenant = "multi_tenant" // Multi-tenant organizations
FeatureUnlimited = "unlimited" // Compatibility capability marker for MSP/enterprise deals
diff --git a/pkg/licensing/features_test.go b/pkg/licensing/features_test.go
index 98f22ba29a..185cf935a9 100644
--- a/pkg/licensing/features_test.go
+++ b/pkg/licensing/features_test.go
@@ -127,6 +127,30 @@ func TestDeriveCapabilitiesFromTier_Sorted(t *testing.T) {
}
}
+func TestWhiteLabelBrandingRemainsExplicitEnterpriseEntitlement(t *testing.T) {
+ if TierHasFeature(TierFree, FeatureWhiteLabel) {
+ t.Fatal("community tier must not include white_label report branding")
+ }
+ if TierHasFeature(TierMSP, FeatureWhiteLabel) {
+ t.Fatal("MSP tier defaults must not imply white_label unless the license grants it")
+ }
+ if !TierHasFeature(TierEnterprise, FeatureWhiteLabel) {
+ t.Fatal("enterprise tier must keep white_label report branding entitlement")
+ }
+
+ got := DeriveCapabilitiesFromTier(TierMSP, []string{FeatureWhiteLabel})
+ found := false
+ for _, feature := range got {
+ if feature == FeatureWhiteLabel {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatal("explicit white_label grants must be merged into MSP capabilities")
+ }
+}
+
func TestSelfHostedPaidFeatureClaimMatrix(t *testing.T) {
tests := []struct {
name string
diff --git a/pkg/reporting/branding.go b/pkg/reporting/branding.go
new file mode 100644
index 0000000000..ea2aee08d3
--- /dev/null
+++ b/pkg/reporting/branding.go
@@ -0,0 +1,67 @@
+package reporting
+
+import (
+ "strings"
+)
+
+// ReportBrand describes custom report branding supplied by configuration.
+// A brand is custom white-label material; an empty brand falls back to the
+// built-in Pulse report identity.
+type ReportBrand struct {
+ DisplayName string
+ LogoPath string
+ LogoData []byte
+ LogoFormat string
+}
+
+// ReportBranding carries the provider default and the workspace override into
+// the reporting layer, along with the entitlement decision for the request.
+type ReportBranding struct {
+ Entitled bool
+ ProviderDefault ReportBrand
+ WorkspaceOverride ReportBrand
+}
+
+// EffectiveBrand returns the white-label brand that should be rendered. The
+// reporting layer enforces the entitlement gate so callers cannot accidentally
+// render configured branding without the white_label capability.
+func (b ReportBranding) EffectiveBrand() *ReportBrand {
+ if !b.Entitled {
+ return nil
+ }
+ if brand, ok := b.WorkspaceOverride.normalized(); ok {
+ return &brand
+ }
+ if brand, ok := b.ProviderDefault.normalized(); ok {
+ return &brand
+ }
+ return nil
+}
+
+func (b ReportBrand) normalized() (ReportBrand, bool) {
+ normalized := ReportBrand{
+ DisplayName: strings.TrimSpace(b.DisplayName),
+ LogoPath: strings.TrimSpace(b.LogoPath),
+ LogoFormat: normalizeLogoFormat(b.LogoFormat),
+ }
+ if len(b.LogoData) > 0 {
+ normalized.LogoData = append([]byte(nil), b.LogoData...)
+ }
+ if normalized.DisplayName == "" && normalized.LogoPath == "" && len(normalized.LogoData) == 0 {
+ return ReportBrand{}, false
+ }
+ return normalized, true
+}
+
+func normalizeLogoFormat(format string) string {
+ switch strings.ToLower(strings.TrimSpace(format)) {
+ case "jpg", "jpeg":
+ return "jpg"
+ case "png":
+ return "png"
+ case "gif":
+ return "gif"
+ default:
+ return ""
+ }
+}
diff --git a/pkg/reporting/engine.go b/pkg/reporting/engine.go
index 62c1e8d401..fe706e0ede 100644
--- a/pkg/reporting/engine.go
+++ b/pkg/reporting/engine.go
@@ -213,6 +213,7 @@ type ReportData struct {
Metrics map[string][]MetricDataPoint
TotalPoints int
Summary MetricSummary
+ Brand *ReportBrand
// Enrichment data (optional, for richer PDF reports)
Resource *ResourceInfo
@@ -267,6 +268,7 @@ func (e *ReportEngine) queryMetrics(req MetricReportRequest) (*ReportData, error
End: req.End,
GeneratedAt: time.Now(),
Metrics: make(map[string][]MetricDataPoint),
+ Brand: req.Branding.EffectiveBrand(),
Summary: MetricSummary{
ByMetric: make(map[string]MetricStats),
},
@@ -379,6 +381,7 @@ func (e *ReportEngine) GenerateMulti(req MultiReportRequest) (data []byte, conte
Start: req.Start,
End: req.End,
GeneratedAt: time.Now(),
+ Brand: req.Branding.EffectiveBrand(),
}
if multiData.Title == "" {
@@ -393,6 +396,7 @@ func (e *ReportEngine) GenerateMulti(req MultiReportRequest) (data []byte, conte
resReq.Start = req.Start
resReq.End = req.End
resReq.MetricType = req.MetricType
+ resReq.Branding = req.Branding
if resReq.Narrator == nil {
resReq.Narrator = req.Narrator
}
diff --git a/pkg/reporting/pdf.go b/pkg/reporting/pdf.go
index 9cb4a70b5d..9c0e390097 100644
--- a/pkg/reporting/pdf.go
+++ b/pkg/reporting/pdf.go
@@ -3,8 +3,12 @@ package reporting
import (
"bytes"
"context"
+ "crypto/sha256"
+ "encoding/hex"
"fmt"
"math"
+ "os"
+ "path/filepath"
"sort"
"strings"
"time"
@@ -35,6 +39,117 @@ func NewPDFGenerator() *PDFGenerator {
return &PDFGenerator{}
}
+func reportCoverBrandName(brand *ReportBrand) string {
+ if brand != nil && strings.TrimSpace(brand.DisplayName) != "" {
+ return strings.TrimSpace(brand.DisplayName)
+ }
+ return "PULSE"
+}
+
+func reportHeaderBrandName(brand *ReportBrand, fallback string) string {
+ if brand != nil && strings.TrimSpace(brand.DisplayName) != "" {
+ return strings.ToUpper(strings.TrimSpace(brand.DisplayName))
+ }
+ return fallback
+}
+
+func reportLogoTypeFromData(data []byte, configured string) string {
+ if normalized := normalizeLogoFormat(configured); normalized != "" {
+ return normalized
+ }
+ switch {
+ case len(data) >= 8 && bytes.Equal(data[:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}):
+ return "png"
+ case len(data) >= 3 && data[0] == 0xff && data[1] == 0xd8 && data[2] == 0xff:
+ return "jpg"
+ case len(data) >= 6 && (bytes.Equal(data[:6], []byte("GIF87a")) || bytes.Equal(data[:6], []byte("GIF89a"))):
+ return "gif"
+ default:
+ return ""
+ }
+}
+
+func reportLogoTypeFromPath(path string, configured string) string {
+ if normalized := normalizeLogoFormat(configured); normalized != "" {
+ return normalized
+ }
+ switch strings.ToLower(strings.TrimPrefix(filepath.Ext(path), ".")) {
+ case "jpg", "jpeg":
+ return "jpg"
+ case "png":
+ return "png"
+ case "gif":
+ return "gif"
+ default:
+ return ""
+ }
+}
+
+func scaledLogoSize(info *fpdf.ImageInfoType, maxW, maxH float64) (float64, float64) {
+ if info == nil {
+ return 0, 0
+ }
+ w := info.Width()
+ h := info.Height()
+ if w <= 0 || h <= 0 {
+ return 0, 0
+ }
+ scale := math.Min(maxW/w, maxH/h)
+ if scale <= 0 {
+ return 0, 0
+ }
+ return w * scale, h * scale
+}
+
+func (g *PDFGenerator) drawBrandLogo(pdf *fpdf.Fpdf, brand *ReportBrand, x, y, maxW, maxH float64) bool {
+ if brand == nil || maxW <= 0 || maxH <= 0 {
+ return false
+ }
+
+ options := fpdf.ImageOptions{ReadDpi: true}
+ var imageName string
+ var info *fpdf.ImageInfoType
+
+ if len(brand.LogoData) > 0 {
+ imageType := reportLogoTypeFromData(brand.LogoData, brand.LogoFormat)
+ if imageType == "" {
+ return false
+ }
+ sum := sha256.Sum256(brand.LogoData)
+ imageName = "report-brand-logo-" + hex.EncodeToString(sum[:8])
+ options.ImageType = imageType
+ info = pdf.RegisterImageOptionsReader(imageName, options, bytes.NewReader(brand.LogoData))
+ } else if strings.TrimSpace(brand.LogoPath) != "" {
+ path := strings.TrimSpace(brand.LogoPath)
+ imageType := reportLogoTypeFromPath(path, brand.LogoFormat)
+ if imageType == "" {
+ return false
+ }
+ stat, err := os.Stat(path)
+ if err != nil || stat.IsDir() {
+ return false
+ }
+ imageName = path
+ options.ImageType = imageType
+ info = pdf.RegisterImageOptions(imageName, options)
+ }
+
+ if pdf.Err() || info == nil {
+ pdf.ClearError()
+ return false
+ }
+ w, h := scaledLogoSize(info, maxW, maxH)
+ if w <= 0 || h <= 0 {
+ return false
+ }
+ pdf.ImageOptions(imageName, x+(maxW-w)/2, y+(maxH-h)/2, w, h, false, options, 0, "")
+ if pdf.Err() {
+ pdf.ClearError()
+ return false
+ }
+ return true
+}
+
// Generate creates a PDF report from the provided data.
func (g *PDFGenerator) Generate(data *ReportData) ([]byte, error) {
pdf := fpdf.New("P", "mm", "A4", "")
@@ -113,11 +228,15 @@ func (g *PDFGenerator) writeCoverPage(pdf *fpdf.Fpdf, data *ReportData) {
pdf.SetFillColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
pdf.Rect(0, 0, pageWidth, 8, "F")
- // Pulse branding area
- pdf.SetY(50)
+ // Branding area
+ if g.drawBrandLogo(pdf, data.Brand, pageWidth/2-20, 34, 40, 18) {
+ pdf.SetY(58)
+ } else {
+ pdf.SetY(50)
+ }
pdf.SetFont("Arial", "B", 32)
pdf.SetTextColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
- pdf.CellFormat(0, 15, "PULSE", "", 1, "C", false, 0, "")
+ pdf.CellFormat(0, 15, reportCoverBrandName(data.Brand), "", 1, "C", false, 0, "")
pdf.SetFont("Arial", "", 12)
pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
@@ -576,14 +695,19 @@ func (g *PDFGenerator) addPageHeader(pdf *fpdf.Fpdf, data *ReportData, section s
pdf.Line(20, 15, pageWidth-20, 15)
// Header text
- pdf.SetY(18)
+ textX := 20.0
+ if g.drawBrandLogo(pdf, data.Brand, 20, 17, 7, 7) {
+ textX = 30
+ }
+ pdf.SetXY(textX, 18)
pdf.SetFont("Arial", "B", 9)
pdf.SetTextColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
- pdf.CellFormat(0, 5, "PULSE PERFORMANCE REPORT", "", 0, "L", false, 0, "")
+ pdf.CellFormat(pageWidth-textX-20, 5, reportHeaderBrandName(data.Brand, "PULSE")+" PERFORMANCE REPORT", "", 0, "L", false, 0, "")
pdf.SetFont("Arial", "", 9)
pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
- pdf.CellFormat(0, 5, data.ResourceID, "", 1, "R", false, 0, "")
+ pdf.SetXY(20, 18)
+ pdf.CellFormat(pageWidth-40, 5, data.ResourceID, "", 1, "R", false, 0, "")
// Section title
pdf.SetY(30)
@@ -1573,11 +1697,15 @@ func (g *PDFGenerator) writeMultiCoverPage(pdf *fpdf.Fpdf, data *MultiReportData
pdf.SetFillColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
pdf.Rect(0, 0, pageWidth, 8, "F")
- // Pulse branding area
- pdf.SetY(50)
+ // Branding area
+ if g.drawBrandLogo(pdf, data.Brand, pageWidth/2-20, 34, 40, 18) {
+ pdf.SetY(58)
+ } else {
+ pdf.SetY(50)
+ }
pdf.SetFont("Arial", "B", 32)
pdf.SetTextColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
- pdf.CellFormat(0, 15, "PULSE", "", 1, "C", false, 0, "")
+ pdf.CellFormat(0, 15, reportCoverBrandName(data.Brand), "", 1, "C", false, 0, "")
pdf.SetFont("Arial", "", 12)
pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
@@ -1702,14 +1830,19 @@ func (g *PDFGenerator) addMultiPageHeader(pdf *fpdf.Fpdf, data *MultiReportData,
pdf.Line(20, 15, pageWidth-20, 15)
// Header text
- pdf.SetY(18)
+ textX := 20.0
+ if g.drawBrandLogo(pdf, data.Brand, 20, 17, 7, 7) {
+ textX = 30
+ }
+ pdf.SetXY(textX, 18)
pdf.SetFont("Arial", "B", 9)
pdf.SetTextColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
- pdf.CellFormat(0, 5, "PULSE FLEET REPORT", "", 0, "L", false, 0, "")
+ pdf.CellFormat(pageWidth-textX-20, 5, reportHeaderBrandName(data.Brand, "PULSE")+" FLEET REPORT", "", 0, "L", false, 0, "")
pdf.SetFont("Arial", "", 9)
pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
- pdf.CellFormat(0, 5, fmt.Sprintf("%d Resources", len(data.Resources)), "", 1, "R", false, 0, "")
+ pdf.SetXY(20, 18)
+ pdf.CellFormat(pageWidth-40, 5, fmt.Sprintf("%d Resources", len(data.Resources)), "", 1, "R", false, 0, "")
// Section title
pdf.SetY(30)
diff --git a/pkg/reporting/report_branding_test.go b/pkg/reporting/report_branding_test.go
new file mode 100644
index 0000000000..43a1dbc436
--- /dev/null
+++ b/pkg/reporting/report_branding_test.go
@@ -0,0 +1,161 @@
+package reporting
+
+import (
+ "bytes"
+ "encoding/base64"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
+ "github.com/stretchr/testify/require"
+)
+
+const tinyPNGBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII="
+
+func testReportLogo(t *testing.T) []byte {
+ t.Helper()
+ data, err := base64.StdEncoding.DecodeString(tinyPNGBase64)
+ require.NoError(t, err)
+ return data
+}
+
+func TestReportBrandingEffectiveBrand(t *testing.T) {
+ branding := ReportBranding{
+ Entitled: true,
+ ProviderDefault: ReportBrand{DisplayName: "Provider Default"},
+ }
+ if got := branding.EffectiveBrand(); got == nil || got.DisplayName != "Provider Default" {
+ t.Fatalf("provider default brand = %#v, want Provider Default", got)
+ }
+
+ branding.WorkspaceOverride = ReportBrand{DisplayName: "Client Override"}
+ if got := branding.EffectiveBrand(); got == nil || got.DisplayName != "Client Override" {
+ t.Fatalf("workspace override brand = %#v, want Client Override", got)
+ }
+
+ branding.Entitled = false
+ if got := branding.EffectiveBrand(); got != nil {
+ t.Fatalf("unentitled brand = %#v, want nil", got)
+ }
+}
+
+func TestReportBrandingRendersPerClientPDFsAndEntitlementGate(t *testing.T) {
+ logo := testReportLogo(t)
+ now := time.Now().UTC()
+ start := now.Add(-time.Hour)
+ end := now.Add(time.Minute)
+
+ clientA := renderBrandedClientReport(t, "client-a-node", start, end, ReportBranding{
+ Entitled: true,
+ ProviderDefault: ReportBrand{DisplayName: "Provider Default", LogoData: logo, LogoFormat: "png"},
+ WorkspaceOverride: ReportBrand{
+ DisplayName: "Client Alpha MSP",
+ LogoData: logo,
+ LogoFormat: "png",
+ },
+ })
+ clientB := renderBrandedClientReport(t, "client-b-node", start, end, ReportBranding{
+ Entitled: true,
+ ProviderDefault: ReportBrand{DisplayName: "Provider Default", LogoData: logo, LogoFormat: "png"},
+ WorkspaceOverride: ReportBrand{
+ DisplayName: "Client Beta MSP",
+ LogoData: logo,
+ LogoFormat: "png",
+ },
+ })
+ unentitled := renderBrandedClientReport(t, "client-c-node", start, end, ReportBranding{
+ Entitled: false,
+ ProviderDefault: ReportBrand{DisplayName: "Provider Default", LogoData: logo, LogoFormat: "png"},
+ WorkspaceOverride: ReportBrand{
+ DisplayName: "Client Gamma MSP",
+ LogoData: logo,
+ LogoFormat: "png",
+ },
+ })
+
+ assertPDFContainsOnlyClient(t, clientA.text, "Client Alpha MSP", "client-a-node", []string{"Client Beta MSP", "client-b-node", "Client Gamma MSP", "client-c-node", "Provider Default"})
+ assertPDFContainsOnlyClient(t, clientB.text, "Client Beta MSP", "client-b-node", []string{"Client Alpha MSP", "client-a-node", "Client Gamma MSP", "client-c-node", "Provider Default"})
+ if !bytes.Contains(clientA.pdf, []byte("/Subtype /Image")) || !bytes.Contains(clientB.pdf, []byte("/Subtype /Image")) {
+ t.Fatal("entitled branded PDFs should embed the configured logo image")
+ }
+
+ if strings.Contains(unentitled.text, "Client Gamma MSP") || strings.Contains(unentitled.text, "Provider Default") {
+ t.Fatalf("unentitled report rendered custom branding:\n%s", unentitled.text)
+ }
+ if !strings.Contains(unentitled.text, "PULSE") {
+ t.Fatalf("unentitled report should keep built-in Pulse identity, got:\n%s", unentitled.text)
+ }
+ if bytes.Contains(unentitled.pdf, []byte("/Subtype /Image")) {
+ t.Fatal("unentitled report embedded a custom logo image")
+ }
+ if strings.Contains(unentitled.text, "client-a-node") || strings.Contains(unentitled.text, "client-b-node") {
+ t.Fatalf("unentitled report included another client resource:\n%s", unentitled.text)
+ }
+}
+
+type renderedClientReport struct {
+ pdf []byte
+ text string
+}
+
+func renderBrandedClientReport(t *testing.T, resourceID string, start, end time.Time, branding ReportBranding) renderedClientReport {
+ t.Helper()
+
+ dir := t.TempDir()
+ store, err := metrics.NewStore(metrics.StoreConfig{
+ DBPath: filepath.Join(dir, "metrics.db"),
+ WriteBufferSize: 10,
+ FlushInterval: 25 * time.Millisecond,
+ RetentionRaw: 24 * time.Hour,
+ RetentionMinute: 7 * 24 * time.Hour,
+ RetentionHourly: 30 * 24 * time.Hour,
+ RetentionDaily: 90 * 24 * time.Hour,
+ })
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = store.Close() })
+
+ for i := 0; i < 4; i++ {
+ store.Write("node", resourceID, "cpu", float64(10+i), start.Add(time.Duration(i)*10*time.Minute))
+ }
+ store.Flush()
+
+ engine := NewReportEngine(EngineConfig{MetricsStore: store})
+ req := MetricReportRequest{
+ ResourceType: "node",
+ ResourceID: resourceID,
+ Start: start,
+ End: end,
+ Format: FormatPDF,
+ Branding: branding,
+ }
+
+ var pdf []byte
+ var contentType string
+ require.Eventually(t, func() bool {
+ var genErr error
+ pdf, contentType, genErr = engine.Generate(req)
+ return genErr == nil && contentType == "application/pdf" && len(pdf) > 1000
+ }, 2*time.Second, 25*time.Millisecond)
+
+ return renderedClientReport{
+ pdf: pdf,
+ text: extractPDFText(t, pdf),
+ }
+}
+
+func assertPDFContainsOnlyClient(t *testing.T, text, brand, resource string, forbidden []string) {
+ t.Helper()
+ if !strings.Contains(text, brand) {
+ t.Fatalf("report missing brand %q:\n%s", brand, text)
+ }
+ if !strings.Contains(text, resource) {
+ t.Fatalf("report missing resource %q:\n%s", resource, text)
+ }
+ for _, value := range forbidden {
+ if strings.Contains(text, value) {
+ t.Fatalf("report included forbidden value %q:\n%s", value, text)
+ }
+ }
+}
diff --git a/pkg/reporting/reporting.go b/pkg/reporting/reporting.go
index ada7360f35..69e97091c4 100644
--- a/pkg/reporting/reporting.go
+++ b/pkg/reporting/reporting.go
@@ -21,6 +21,7 @@ type MetricReportRequest struct {
End time.Time
Format ReportFormat
Title string
+ Branding ReportBranding
// Optional enrichment data (populated by handler from monitor state)
Resource *ResourceInfo // Details about the resource being reported on
@@ -122,6 +123,7 @@ type MultiReportRequest struct {
End time.Time
Title string
MetricType string
+ Branding ReportBranding
// Optional fleet-level narrative interpretation. When FleetNarrator is
// non-nil the engine builds a FleetNarrativeInput from the queried
@@ -142,6 +144,7 @@ type MultiReportData struct {
GeneratedAt time.Time
Resources []*ReportData // Reuse existing ReportData per resource
TotalPoints int
+ Brand *ReportBrand
// Fleet-level narrative interpretation, populated by the engine when
// the request supplies a FleetNarrator (or always populated with the
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 85e0035d82..69bd9c340d 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -2860,7 +2860,7 @@ class SubsystemLookupTest(unittest.TestCase):
{
"heading": "## Shared Boundaries",
"path": "internal/api/access_control_handlers.go",
- "line": 335,
+ "line": 346,
"heading_line": 113,
}
],