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.

Keep credentials out of support-bundle system summaries

pulse-triage[bot]f4a14d223531
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index ca06941653..489f7d34dd 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -10756,3 +10756,16 @@ itself served (`Sec-Fetch-Site: same-origin`), so the Pulse UI running on the
setup admin token stops reading as external-agent use. This changes no agent
token, enrolment, credential scope, authentication or runtime operation; only
which requests write the content-free activity marker.
+
+
+### Diagnostic log downloads do not export recovery credentials
+
+The existing administrative log-bundle route retains its auth/scope gates and
+raw log-file/buffer evidence. Its system-info member now uses the API contract's
+explicit diagnostic allowlist rather than a full Config/environment copy. No
+endpoint/name/path, arbitrary environment or credential is included in that
+summary; logs still require private manual review. Connection and polling
+settings remain live and unchanged. This is not a backup, credential recovery,
+agent/guest probe or installed recovery. The normal HTTP contract
+`TestContractSupportBundleCredentialBoundary` and `log_bundle_test.go` cover the
+summary, scope denials, state preservation and configured-file/buffer fallbacks.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 5d8a408447..d0b235aaba 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -13358,3 +13358,33 @@ manager/files on rejection, supported results, existing denials and both
fallbacks. `TestContractRBACIntegrityQueryAdmission` exercises the registered
router and unchanged authentication/licence gates. No frontend consumes this
admin-only check; this changes no rendered state, recovery token or sign-in.
+
+
+### Support bundles use an explicit diagnostic allowlist
+
+`GET /api/logs/download` retains instance administration plus `settings:read`,
+the ZIP attachment and the configured log-file/retained-buffer fallback. Logs
+are unchanged private evidence, not anonymised or safe to publish. The existing
+System Logs warning and display-only pause/clear behaviour remain applicable.
+
+`system-info.json` is a diagnostic summary, not a configuration backup: only
+selected scalar polling, retention, logging, transport and feature settings,
+connection counts/order, credential-presence/TLS flags and monitored surfaces
+are copied. No Config object, free-form endpoint/name/path or credential is
+serialized. Enumerated strings accept only fixed values; unknown values are
+redacted. New configuration fields are excluded by default. A detached snapshot
+uses configuration ownership shared by log-level updates; export never rewrites
+live credentials, connections or logs. Runtime metadata uses the injected build
+version (explicitly unknown when missing), current Go runtime and OS, not a
+hardcoded legacy version.
+
+Environment export includes only `GOMAXPROCS`, `GOGC` and `GOMEMLIMIT`, with
+bounded numeric/unit/off grammars. Other names and values are absent, including
+credential-bearing proxy URLs and DSNs; invalid allowlisted values are redacted.
+No name-based secret heuristic or claim of complete log scrubbing remains.
+`TestContractSupportBundleCredentialBoundary` exercises the real authenticated
+HTTP route, both token headers, independent administration, unchanged denials,
+synthetic credentials and preserved live data. `log_bundle_test.go` covers
+value grammars, detached projections, log fallbacks, runtime identity and race
+ownership. Consuming browser evidence exercises the unchanged download control
+with the exact synthetic native ZIP; it is not installed/customer recovery.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 298768d99f..51b2b30c9b 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -3960,3 +3960,33 @@ inferred. Tests: `internal/api/log_stream_auth_test.go`,
`frontend-modern/src/components/Settings/__tests__/useSystemLogsPanelState.test.tsx`,
`frontend-modern/src/components/Settings/__tests__/SystemLogsPanel.safety.test.tsx`
and `frontend-modern/src/utils/__tests__/systemLogsPresentation.test.ts`.
+
+
+### Support bundles use an explicit diagnostic allowlist
+
+`GET /api/logs/download` retains instance administration plus `settings:read`,
+the ZIP attachment and the configured log-file/retained-buffer fallback. Logs
+are unchanged private evidence, not anonymised or safe to publish. The existing
+System Logs warning and display-only pause/clear behaviour remain applicable.
+
+`system-info.json` is a diagnostic summary, not a configuration backup: only
+selected scalar polling, retention, logging, transport and feature settings,
+connection counts/order, credential-presence/TLS flags and monitored surfaces
+are copied. No Config object, free-form endpoint/name/path or credential is
+serialized. Enumerated strings accept only fixed values; unknown values are
+redacted. New configuration fields are excluded by default. A detached snapshot
+uses configuration ownership shared by log-level updates; export never rewrites
+live credentials, connections or logs. Runtime metadata uses the injected build
+version (explicitly unknown when missing), current Go runtime and OS, not a
+hardcoded legacy version.
+
+Environment export includes only `GOMAXPROCS`, `GOGC` and `GOMEMLIMIT`, with
+bounded numeric/unit/off grammars. Other names and values are absent, including
+credential-bearing proxy URLs and DSNs; invalid allowlisted values are redacted.
+No name-based secret heuristic or claim of complete log scrubbing remains.
+`TestContractSupportBundleCredentialBoundary` exercises the real authenticated
+HTTP route, both token headers, independent administration, unchanged denials,
+synthetic credentials and preserved live data. `log_bundle_test.go` covers
+value grammars, detached projections, log fallbacks, runtime identity and race
+ownership. Consuming browser evidence exercises the unchanged download control
+with the exact synthetic native ZIP; it is not installed/customer recovery.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 5a8f5888e0..8dbdcf897d 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -9179,3 +9179,16 @@ literal date evidence and the browser-reproduced focus repair. The 15% threshold
all other per-chunk baselines, total JS/CSS and preload/SRI checks stay unchanged.
This is a narrowly declared intentional UI/accessibility cost, not suppression
of the retained failed budget runs or permission to omit browser verification.
+
+
+### Diagnostic log downloads do not export recovery credentials
+
+The existing administrative log-bundle route retains its auth/scope gates and
+raw log-file/buffer evidence. Its system-info member now uses the API contract's
+explicit diagnostic allowlist rather than a full Config/environment copy. No
+endpoint/name/path, arbitrary environment or credential is included in that
+summary; logs still require private manual review. Connection and polling
+settings remain live and unchanged. This is not a backup, credential recovery,
+agent/guest probe or installed recovery. The normal HTTP contract
+`TestContractSupportBundleCredentialBoundary` and `log_bundle_test.go` cover the
+summary, scope denials, state preservation and configured-file/buffer fallbacks.
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 7769c544ef..184399d68f 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -28852,3 +28852,106 @@ func TestAgentEventTokenLifecycleRefreshesDisclosure(t *testing.T) {
func TestContract_MonitoringWebSocketTokenDeleteThroughHTTP(t *testing.T) {
deleteMonitoringWebSocketTokenThroughHTTP(t)
}
+
+// Support downloads use a fixed diagnostic schema, not a serialized Config or
+// a name-based guess about which environment variables might hold credentials.
+func TestContractSupportBundleCredentialBoundary(t *testing.T) {
+ const canary = "synthetic-bundle-confidential-value"
+ t.Setenv("HTTPS_PROXY", "http://operator:"+canary+"@proxy.invalid:3128")
+ t.Setenv("DATABASE_URL", "postgres://operator:"+canary+"@database.invalid/db")
+ t.Setenv("ORDINARY_OPTION", canary)
+ t.Setenv("GOMAXPROCS", "2")
+ t.Setenv("GOGC", "100")
+ t.Setenv("GOMEMLIMIT", "512MiB")
+
+ _, cfg, server := newLogStreamRouter(t)
+ logFile := filepathWithTemp(t, "private.log")
+ const logLine = "synthetic private log evidence: review before sharing"
+ if err := os.WriteFile(logFile, []byte(logLine), 0600); err != nil {
+ t.Fatal(err)
+ }
+ config.Mu.Lock()
+ cfg.LogFile, cfg.LogLevel, cfg.LogFormat = logFile, "info", "json"
+ cfg.PublicURL = "https://operator:" + canary + "@pulse.invalid/?auth=" + canary
+ cfg.PVEInstances = []config.PVEInstance{{Name: canary, Host: canary, Password: canary, TokenValue: canary, VerifySSL: true, MonitorVMs: true}}
+ cfg.PVEPollingInterval = 10 * time.Second
+ monitorToken := newTokenRecord(t, "synthetic-bundle-monitor-token.12345678", []string{config.ScopeMonitoringRead}, nil)
+ cfg.APITokens = append(cfg.APITokens, monitorToken)
+ tenantToken := newTokenRecord(t, "synthetic-bundle-tenant-token.12345678", []string{config.ScopeSettingsRead}, nil)
+ tenantToken.OrgID = "tenant-only"
+ cfg.APITokens = append(cfg.APITokens, tenantToken)
+ config.Mu.Unlock()
+
+ for _, tc := range []struct {
+ name, token, transport string
+ status int
+ }{
+ {"settings read", logStreamToken, "X-API-Token", http.StatusOK},
+ {"bearer", logStreamToken, "Authorization", http.StatusOK},
+ {"independent admin", logStreamControl, "X-API-Token", http.StatusOK},
+ {"unauthenticated", "", "X-API-Token", http.StatusUnauthorized},
+ {"monitoring is not settings", "synthetic-bundle-monitor-token.12345678", "X-API-Token", http.StatusForbidden},
+ {"tenant is not instance admin", "synthetic-bundle-tenant-token.12345678", "X-API-Token", http.StatusForbidden},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ req, err := http.NewRequest(http.MethodGet, server.URL+"/api/logs/download", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.token != "" {
+ value := tc.token
+ if tc.transport == "Authorization" {
+ value = "Bearer " + value
+ }
+ req.Header.Set(tc.transport, value)
+ }
+ resp, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != tc.status {
+ t.Fatalf("download status = %d, want %d", resp.StatusCode, tc.status)
+ }
+ if tc.status != http.StatusOK {
+ if strings.Contains(resp.Header.Get("Content-Type"), "zip") || bytes.Contains(body, []byte("system-info.json")) {
+ t.Fatal("denied caller received archive data")
+ }
+ return
+ }
+ if resp.Header.Get("Content-Type") != "application/zip" || !strings.HasPrefix(resp.Header.Get("Content-Disposition"), `attachment; filename="pulse-support-bundle-`) {
+ t.Fatal("support download lost attachment headers")
+ }
+ entries := readSupportBundle(t, body)
+ if len(entries) != 2 || string(entries["pulse.log"]) != logLine {
+ t.Fatal("private log evidence changed or archive entries missing")
+ }
+ system := entries["system-info.json"]
+ if bytes.Contains(system, []byte(canary)) || bytes.Contains(system, []byte("HTTPS_PROXY")) || bytes.Contains(system, []byte("ORDINARY_OPTION")) || bytes.Contains(system, []byte("DATABASE_URL")) {
+ t.Fatal("system-info disclosed synthetic credentials or arbitrary process environment")
+ }
+ var info struct {
+ Config supportBundleConfig
+ Env []string
+ }
+ if err := json.Unmarshal(system, &info); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Contains(info.Env, "GOMAXPROCS=2") || !slices.Contains(info.Env, "GOGC=100") || !slices.Contains(info.Env, "GOMEMLIMIT=512MiB") || len(info.Env) != 3 {
+ t.Fatal("safe runtime environment details lost")
+ }
+ if info.Config.LogLevel != "info" || info.Config.PVEPollingInterval != 10*time.Second || len(info.Config.PVEInstances) != 1 || !info.Config.PVEInstances[0].VerifySSL || !info.Config.PVEInstances[0].PasswordConfigured || !info.Config.PVEInstances[0].TokenConfigured {
+ t.Fatal("useful connection/polling diagnostics lost")
+ }
+ })
+ }
+ config.Mu.RLock()
+ defer config.Mu.RUnlock()
+ if cfg.PublicURL != "https://operator:"+canary+"@pulse.invalid/?auth="+canary || cfg.PVEInstances[0].Password != canary || cfg.PVEInstances[0].TokenValue != canary || len(cfg.APITokens) != 4 {
+ t.Fatal("download mutated live credentials or connection state")
+ }
+}
diff --git a/internal/api/log_bundle.go b/internal/api/log_bundle.go
new file mode 100644
index 0000000000..8d6d1d5daa
--- /dev/null
+++ b/internal/api/log_bundle.go
@@ -0,0 +1,181 @@
+package api
+
+import (
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// This is deliberately not config.Config, even a redacted copy. New settings,
+// free-form URLs, paths, names and credentials must not enter a diagnostic
+// archive just because a new configuration field becomes JSON-serializable.
+// Connection order is retained so log references can be compared with settings.
+type supportBundleConfig struct {
+ FrontendPort int
+ AgentIngestPort int
+ PVEPollingInterval time.Duration
+ PBSPollingInterval time.Duration
+ PMGPollingInterval time.Duration
+ ConnectionTimeout time.Duration
+ BackupPollingInterval time.Duration
+ BackupPollingCycles int
+ EnableBackupPolling bool
+ TemperatureMonitoringEnabled bool
+ AdaptivePollingEnabled bool
+ AdaptivePollingBaseInterval time.Duration
+ AdaptivePollingMinInterval time.Duration
+ AdaptivePollingMaxInterval time.Duration
+ MetricsRetentionRawHours int
+ MetricsRetentionMinuteHours int
+ MetricsRetentionHourlyDays int
+ MetricsRetentionDailyDays int
+ LogLevel string
+ LogFormat string
+ LogMaxSize int
+ LogMaxAge int
+ LogCompress bool
+ HTTPSEnabled bool
+ HideLocalLogin bool
+ MultiTenantEnabled bool
+ DiscoveryEnabled bool
+ UpdateChannel string
+ AutoUpdateEnabled bool
+ PVEInstances []supportBundleConnection
+ PBSInstances []supportBundleConnection
+ PMGInstances []supportBundleConnection
+}
+
+type supportBundleConnection struct {
+ PasswordConfigured bool
+ TokenConfigured bool
+ VerifySSL bool
+ FingerprintConfigured bool
+ Disabled bool
+ MonitoredSurfaces []string
+}
+
+// Caller holds config.Mu.RLock. Only scalar values and newly allocated slices
+// cross this boundary, so archive writing neither aliases nor mutates live state.
+func newSupportBundleConfig(cfg *config.Config) supportBundleConfig {
+ out := supportBundleConfig{
+ FrontendPort: cfg.FrontendPort, AgentIngestPort: cfg.AgentIngestPort,
+ PVEPollingInterval: cfg.PVEPollingInterval, PBSPollingInterval: cfg.PBSPollingInterval,
+ PMGPollingInterval: cfg.PMGPollingInterval, ConnectionTimeout: cfg.ConnectionTimeout,
+ BackupPollingInterval: cfg.BackupPollingInterval, BackupPollingCycles: cfg.BackupPollingCycles,
+ EnableBackupPolling: cfg.EnableBackupPolling, TemperatureMonitoringEnabled: cfg.TemperatureMonitoringEnabled,
+ AdaptivePollingEnabled: cfg.AdaptivePollingEnabled, AdaptivePollingBaseInterval: cfg.AdaptivePollingBaseInterval,
+ AdaptivePollingMinInterval: cfg.AdaptivePollingMinInterval, AdaptivePollingMaxInterval: cfg.AdaptivePollingMaxInterval,
+ MetricsRetentionRawHours: cfg.MetricsRetentionRawHours, MetricsRetentionMinuteHours: cfg.MetricsRetentionMinuteHours,
+ MetricsRetentionHourlyDays: cfg.MetricsRetentionHourlyDays, MetricsRetentionDailyDays: cfg.MetricsRetentionDailyDays,
+ LogLevel: supportBundleEnum(cfg.LogLevel, "debug", "info", "warn", "error", "trace", "disabled"),
+ LogFormat: supportBundleEnum(cfg.LogFormat, "auto", "json", "console"),
+ LogMaxSize: cfg.LogMaxSize, LogMaxAge: cfg.LogMaxAge, LogCompress: cfg.LogCompress,
+ HTTPSEnabled: cfg.HTTPSEnabled, HideLocalLogin: cfg.HideLocalLogin, MultiTenantEnabled: cfg.MultiTenantEnabled,
+ DiscoveryEnabled: cfg.DiscoveryEnabled,
+ UpdateChannel: supportBundleEnum(cfg.UpdateChannel, "stable", "rc", "beta"), AutoUpdateEnabled: cfg.AutoUpdateEnabled,
+ PVEInstances: make([]supportBundleConnection, 0, len(cfg.PVEInstances)),
+ PBSInstances: make([]supportBundleConnection, 0, len(cfg.PBSInstances)),
+ PMGInstances: make([]supportBundleConnection, 0, len(cfg.PMGInstances)),
+ }
+ for _, c := range cfg.PVEInstances {
+ out.PVEInstances = append(out.PVEInstances, supportBundleConnection{
+ PasswordConfigured: c.Password != "", TokenConfigured: c.TokenValue != "", VerifySSL: c.VerifySSL,
+ FingerprintConfigured: c.Fingerprint != "", Disabled: c.Disabled,
+ MonitoredSurfaces: supportBundleSurfaces(
+ []string{"vms", "containers", "storage", "backups"},
+ []bool{c.MonitorVMs, c.MonitorContainers, c.MonitorStorage, c.MonitorBackups}),
+ })
+ }
+ for _, c := range cfg.PBSInstances {
+ out.PBSInstances = append(out.PBSInstances, supportBundleConnection{
+ PasswordConfigured: c.Password != "", TokenConfigured: c.TokenValue != "", VerifySSL: c.VerifySSL,
+ FingerprintConfigured: c.Fingerprint != "", Disabled: c.Disabled,
+ MonitoredSurfaces: supportBundleSurfaces(
+ []string{"backups", "datastores", "sync", "verify", "prune", "garbage"},
+ []bool{c.MonitorBackups, c.MonitorDatastores, c.MonitorSyncJobs, c.MonitorVerifyJobs, c.MonitorPruneJobs, c.MonitorGarbageJobs}),
+ })
+ }
+ for _, c := range cfg.PMGInstances {
+ out.PMGInstances = append(out.PMGInstances, supportBundleConnection{
+ PasswordConfigured: c.Password != "", TokenConfigured: c.TokenValue != "", VerifySSL: c.VerifySSL,
+ FingerprintConfigured: c.Fingerprint != "", Disabled: c.Disabled,
+ MonitoredSurfaces: supportBundleSurfaces(
+ []string{"mail", "queues", "quarantine", "domains"},
+ []bool{c.MailStatsEnabled(), c.MonitorQueues, c.MonitorQuarantine, c.MonitorDomainStats}),
+ })
+ }
+ return out
+}
+
+func supportBundleSurfaces(names []string, enabled []bool) []string {
+ out := make([]string, 0, len(names))
+ for i, name := range names {
+ if enabled[i] {
+ out = append(out, name)
+ }
+ }
+ return out
+}
+
+func supportBundleEnum(value string, allowed ...string) string {
+ if value == "" {
+ return ""
+ }
+ for _, candidate := range allowed {
+ if value == candidate {
+ return value
+ }
+ }
+ return "[REDACTED]"
+}
+
+// Export only Go runtime tuning values, never arbitrary process environment
+// names/values (proxy URLs, DSNs and provider options can contain credentials).
+// Even an allowlisted name needs a bounded value grammar; invalid values reveal
+// only that the setting was supplied, not its contents.
+func supportBundleEnvironment(environ []string) []string {
+ out := make([]string, 0, 3)
+ for _, entry := range environ {
+ name, value, ok := strings.Cut(entry, "=")
+ if !ok {
+ continue
+ }
+ valid := false
+ switch name {
+ case "GOMAXPROCS":
+ valid = supportBundleUnsigned(value, false)
+ case "GOGC":
+ valid = value == "off" || supportBundleUnsigned(value, true)
+ case "GOMEMLIMIT":
+ valid = value == "off"
+ for _, suffix := range []string{"B", "KiB", "MiB", "GiB", "TiB"} {
+ if strings.HasSuffix(value, suffix) && supportBundleUnsigned(strings.TrimSuffix(value, suffix), true) {
+ valid = true
+ break
+ }
+ }
+ default:
+ continue
+ }
+ if !valid {
+ value = "[REDACTED]"
+ }
+ out = append(out, name+"="+value)
+ }
+ return out
+}
+
+func supportBundleUnsigned(value string, zero bool) bool {
+ if value == "" || len(value) > 19 {
+ return false
+ }
+ for _, c := range value {
+ if c < '0' || c > '9' {
+ return false
+ }
+ }
+ n, err := strconv.ParseUint(value, 10, 63)
+ return err == nil && (zero || n > 0)
+}
diff --git a/internal/api/log_bundle_test.go b/internal/api/log_bundle_test.go
new file mode 100644
index 0000000000..047965f026
--- /dev/null
+++ b/internal/api/log_bundle_test.go
@@ -0,0 +1,174 @@
+package api
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "reflect"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/logging"
+ "github.com/rcourtman/pulse-go-rewrite/internal/updates"
+)
+
+func readSupportBundle(t *testing.T, body []byte) map[string][]byte {
+ t.Helper()
+ zr, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := make(map[string][]byte)
+ for _, f := range zr.File {
+ r, err := f.Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ out[f.Name], err = io.ReadAll(r)
+ r.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ return out
+}
+
+func TestSupportBundleEnvironmentAllowlist(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ in, want []string
+ }{
+ {"unset", nil, []string{}},
+ {"valid runtime settings", []string{"GOMAXPROCS=2", "GOGC=100", "GOMEMLIMIT=512MiB"}, []string{"GOMAXPROCS=2", "GOGC=100", "GOMEMLIMIT=512MiB"}},
+ {"off and zero", []string{"GOGC=off", "GOMEMLIMIT=off", "GOMAXPROCS=0"}, []string{"GOGC=off", "GOMEMLIMIT=off", "GOMAXPROCS=[REDACTED]"}},
+ {"no secret-name heuristic", []string{"HTTPS_PROXY=http://user:[email protected]", "DATABASE_URL=postgres://user:[email protected]", "TEST_SECRET=synthetic-secret", "ORDINARY_OPTION=synthetic-secret", "PLAIN_NAME", "PATH=/private/path"}, []string{}},
+ {"grammar not name trust", []string{"GOMAXPROCS=synthetic-secret", "GOGC=100\nsynthetic-secret", "GOMEMLIMIT=1GiB#synthetic-secret"}, []string{"GOMAXPROCS=[REDACTED]", "GOGC=[REDACTED]", "GOMEMLIMIT=[REDACTED]"}},
+ {"numeric syntax", []string{"GOGC=0", "GOMAXPROCS=+2", "GOGC=-1", "GOMEMLIMIT=0B"}, []string{"GOGC=0", "GOMAXPROCS=[REDACTED]", "GOGC=[REDACTED]", "GOMEMLIMIT=0B"}},
+ {"bounded syntax", []string{"GOMAXPROCS=9223372036854775808", "GOGC=" + strings.Repeat("0", 100), "GOMEMLIMIT="}, []string{"GOMAXPROCS=[REDACTED]", "GOGC=[REDACTED]", "GOMEMLIMIT=[REDACTED]"}},
+ {"memory units", []string{"GOMEMLIMIT=1B", "GOMEMLIMIT=1KiB", "GOMEMLIMIT=1MiB", "GOMEMLIMIT=1GiB", "GOMEMLIMIT=1TiB", "GOMEMLIMIT=1GB"}, []string{"GOMEMLIMIT=1B", "GOMEMLIMIT=1KiB", "GOMEMLIMIT=1MiB", "GOMEMLIMIT=1GiB", "GOMEMLIMIT=1TiB", "GOMEMLIMIT=[REDACTED]"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := supportBundleEnvironment(tc.in); !reflect.DeepEqual(got, tc.want) {
+ t.Fatalf("environment projection = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestSupportBundleConfigDoesNotExportFreeFormValues(t *testing.T) {
+ cfg := &config.Config{
+ AuthUser: "synthetic-private-user", AuthPass: "synthetic-secret-auth",
+ APIToken: "synthetic-secret-api", ProxyAuthSecret: "synthetic-secret-proxy",
+ PublicURL: "https://synthetic-secret:[email protected]/?auth=synthetic-secret",
+ AgentConnectURL: "synthetic-private-url", ConfigPath: "synthetic-private-path", DataPath: "synthetic-private-path",
+ AllowedOrigins: "synthetic-private-origin", DiscoverySubnet: "synthetic-private-subnet",
+ ProxyAuthLogoutURL: "synthetic-secret", TLSKeyFile: "synthetic-private-path",
+ LogLevel: "info", LogFormat: "json", UpdateChannel: "rc", FrontendPort: 7655,
+ PVEPollingInterval: 10 * time.Second, EnableBackupPolling: true, ConnectionTimeout: time.Minute,
+ PVEInstances: []config.PVEInstance{{Name: "synthetic-private-name", Host: "synthetic-secret", Password: "synthetic-secret", TokenValue: "synthetic-secret", Fingerprint: "synthetic-private-pin", VerifySSL: true, MonitorVMs: true, MonitorBackups: true, ClusterEndpoints: []config.ClusterEndpoint{{PulseError: "synthetic-secret"}}}},
+ PBSInstances: []config.PBSInstance{{Name: "synthetic-private-name", TokenValue: "synthetic-secret", Disabled: true, MonitorDatastores: true}},
+ PMGInstances: []config.PMGInstance{{Name: "synthetic-private-name", Password: "synthetic-secret", MonitorQueues: true}},
+ }
+ before, _ := json.Marshal(cfg)
+ summary := newSupportBundleConfig(cfg)
+ body, err := json.Marshal(summary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(body), "synthetic-") {
+ t.Fatal("configuration projection exported a synthetic private value")
+ }
+ if summary.LogLevel != "info" || summary.LogFormat != "json" || summary.UpdateChannel != "rc" || summary.FrontendPort != 7655 || summary.PVEPollingInterval != 10*time.Second || !summary.EnableBackupPolling || summary.ConnectionTimeout != time.Minute {
+ t.Fatal("diagnostic scalars lost")
+ }
+ if len(summary.PVEInstances) != 1 || !summary.PVEInstances[0].VerifySSL || !summary.PVEInstances[0].PasswordConfigured || !summary.PVEInstances[0].TokenConfigured || !summary.PVEInstances[0].FingerprintConfigured || !reflect.DeepEqual(summary.PVEInstances[0].MonitoredSurfaces, []string{"vms", "backups"}) {
+ t.Fatal("PVE diagnostic summary lost")
+ }
+ if len(summary.PBSInstances) != 1 || !summary.PBSInstances[0].Disabled || !summary.PBSInstances[0].TokenConfigured || !reflect.DeepEqual(summary.PBSInstances[0].MonitoredSurfaces, []string{"datastores"}) {
+ t.Fatal("PBS diagnostic summary lost")
+ }
+ if len(summary.PMGInstances) != 1 || !summary.PMGInstances[0].PasswordConfigured || !reflect.DeepEqual(summary.PMGInstances[0].MonitoredSurfaces, []string{"queues"}) {
+ t.Fatal("PMG diagnostic summary lost")
+ }
+ // A downloaded summary must be detached from live connection slices.
+ summary.PVEInstances[0].MonitoredSurfaces[0] = "changed"
+ after, _ := json.Marshal(cfg)
+ if !bytes.Equal(before, after) {
+ t.Fatal("summary mutated live configuration")
+ }
+ cfg.LogLevel, cfg.LogFormat, cfg.UpdateChannel = "synthetic-secret", "synthetic-secret", "synthetic-secret"
+ body, _ = json.Marshal(newSupportBundleConfig(cfg))
+ if strings.Contains(string(body), "synthetic-") || bytes.Count(body, []byte("[REDACTED]")) != 3 {
+ t.Fatal("enum-shaped config fields trusted arbitrary contents")
+ }
+}
+
+func TestSupportBundleKeepsLogSourcesAndRuntimeIdentity(t *testing.T) {
+ oldVersion := updates.BuildVersion
+ updates.BuildVersion = "6.7.0-test"
+ t.Cleanup(func() { updates.BuildVersion = oldVersion })
+ // Logs remain private, unmodified diagnostic evidence, not automatically
+ // anonymised text. Check file, missing-file and unconfigured-file paths.
+ marker := "synthetic-private-log-marker"
+ path := filepathWithTemp(t, "pulse.log")
+ if err := os.WriteFile(path, []byte(marker), 0600); err != nil {
+ t.Fatal(err)
+ }
+ logging.GetBroadcaster().Write([]byte(marker))
+ for _, tc := range []struct{ name, path, entry string }{
+ {"file", path, "pulse.log"}, {"missing file", path + "-absent", "pulse-tail.log"}, {"buffer", "", "pulse-tail.log"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ h := NewLogHandlers(&config.Config{LogFile: tc.path}, nil)
+ rr := httptest.NewRecorder()
+ h.HandleDownloadBundle(rr, httptest.NewRequest(http.MethodGet, "/api/logs/download", nil))
+ entries := readSupportBundle(t, rr.Body.Bytes())
+ if len(entries) != 2 || !bytes.Contains(entries[tc.entry], []byte(marker)) {
+ t.Fatal("original log evidence missing")
+ }
+ var info struct{ Version, GoVersion, OS string }
+ if err := json.Unmarshal(entries["system-info.json"], &info); err != nil {
+ t.Fatal(err)
+ }
+ if info.Version != "6.7.0-test" || info.GoVersion != runtime.Version() || info.OS != runtime.GOOS {
+ t.Fatal("diagnostic runtime identity is invented")
+ }
+ })
+ }
+ updates.BuildVersion = ""
+ rr := httptest.NewRecorder()
+ NewLogHandlers(&config.Config{LogFile: path}, nil).HandleDownloadBundle(rr, httptest.NewRequest(http.MethodGet, "/api/logs/download", nil))
+ if !bytes.Contains(readSupportBundle(t, rr.Body.Bytes())["system-info.json"], []byte(`"Version": "unknown"`)) {
+ t.Fatal("missing build version must be explicit")
+ }
+}
+
+func TestSupportBundleSharesConfigOwnershipWithLogLevelUpdates(t *testing.T) {
+ original := logging.GetGlobalLevel()
+ t.Cleanup(func() { logging.SetGlobalLevel(original) })
+ cfg := &config.Config{LogLevel: "info"}
+ h := NewLogHandlers(cfg, nil)
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 10; i++ {
+ h.HandleSetLevel(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/api/logs/level", strings.NewReader(`{"level":"info"}`)))
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 10; i++ {
+ h.HandleDownloadBundle(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/logs/download", nil))
+ }
+ }()
+ wg.Wait()
+}
diff --git a/internal/api/log_handlers.go b/internal/api/log_handlers.go
index 0fed42c7ac..98035f1f04 100644
--- a/internal/api/log_handlers.go
+++ b/internal/api/log_handlers.go
@@ -7,11 +7,13 @@ import (
"io"
"net/http"
"os"
+ "runtime"
"strings"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/logging"
+ "github.com/rcourtman/pulse-go-rewrite/internal/updates"
"github.com/rs/zerolog/log"
)
@@ -101,8 +103,16 @@ func (h *LogHandlers) HandleStreamLogs(w http.ResponseWriter, r *http.Request) {
}
}
-// HandleDownloadBundle creates a zip file with system logs and sanitized config
+// HandleDownloadBundle creates a private log archive with an allowlisted diagnostic summary.
+// Log contents are not scrubbed; this is not an anonymised export or configuration backup.
func (h *LogHandlers) HandleDownloadBundle(w http.ResponseWriter, r *http.Request) {
+ // Snapshot only diagnostic fields while holding configuration ownership.
+ // Do not serialize Config or the full process environment into this archive.
+ config.Mu.RLock()
+ logFile := h.config.LogFile
+ summary := newSupportBundleConfig(h.config)
+ config.Mu.RUnlock()
+
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"pulse-support-bundle-%s.zip\"", time.Now().Format("20060102-150405")))
@@ -113,8 +123,8 @@ func (h *LogHandlers) HandleDownloadBundle(w http.ResponseWriter, r *http.Reques
// If a log file is configured and exists, add it.
// Otherwise (or in addition), dump the in-memory buffer.
addedLogFile := false
- if h.config.LogFile != "" {
- if f, err := os.Open(h.config.LogFile); err == nil {
+ if logFile != "" {
+ if f, err := os.Open(logFile); err == nil {
defer f.Close()
if wr, err := zipWriter.Create("pulse.log"); err == nil {
if _, err := io.Copy(wr, f); err != nil {
@@ -136,66 +146,22 @@ func (h *LogHandlers) HandleDownloadBundle(w http.ResponseWriter, r *http.Reques
// 2. Add Sanitized System Info
if wr, err := zipWriter.Create("system-info.json"); err == nil {
- // Create a sanitized copy of config
- sanitizedConfig := h.config.DeepCopy()
-
- // Scrub top-level secrets
- if sanitizedConfig.AuthPass != "" {
- sanitizedConfig.AuthPass = "[REDACTED]"
- }
- if sanitizedConfig.APIToken != "" {
- sanitizedConfig.APIToken = "[REDACTED]"
- }
- if sanitizedConfig.ProxyAuthSecret != "" {
- sanitizedConfig.ProxyAuthSecret = "[REDACTED]"
- }
-
- // Scrub array secrets
- for i := range sanitizedConfig.PVEInstances {
- sanitizedConfig.PVEInstances[i].Password = "[REDACTED]"
- sanitizedConfig.PVEInstances[i].TokenValue = "[REDACTED]"
- }
- for i := range sanitizedConfig.PBSInstances {
- sanitizedConfig.PBSInstances[i].Password = "[REDACTED]"
- sanitizedConfig.PBSInstances[i].TokenValue = "[REDACTED]"
+ version := strings.TrimSpace(updates.BuildVersion)
+ if version == "" {
+ version = "unknown"
}
- for i := range sanitizedConfig.PMGInstances {
- sanitizedConfig.PMGInstances[i].Password = "[REDACTED]"
- sanitizedConfig.PMGInstances[i].TokenValue = "[REDACTED]"
- }
-
- // Sanitize environment variables
- rawEnv := os.Environ()
- sanitizedEnv := make([]string, 0, len(rawEnv))
- for _, e := range rawEnv {
- parts := strings.SplitN(e, "=", 2)
- if len(parts) == 2 {
- key := parts[0]
- upperKey := strings.ToUpper(key)
- // Redact known sensitive keys
- if strings.Contains(upperKey, "TOKEN") ||
- strings.Contains(upperKey, "PASS") ||
- strings.Contains(upperKey, "SECRET") ||
- strings.Contains(upperKey, "KEY") {
- sanitizedEnv = append(sanitizedEnv, fmt.Sprintf("%s=[REDACTED]", key))
- } else {
- sanitizedEnv = append(sanitizedEnv, e)
- }
- }
- }
-
safeConfig := struct {
Version string
GoVersion string
OS string
- Config *config.Config
+ Config supportBundleConfig
Env []string
}{
- Version: "5.x",
- GoVersion: "go1.21+",
- OS: "linux",
- Config: sanitizedConfig,
- Env: sanitizedEnv,
+ Version: version,
+ GoVersion: runtime.Version(),
+ OS: runtime.GOOS,
+ Config: summary,
+ Env: supportBundleEnvironment(os.Environ()),
}
enc := json.NewEncoder(wr)
@@ -225,7 +191,9 @@ func (h *LogHandlers) HandleSetLevel(w http.ResponseWriter, r *http.Request) {
// 1. Update Runtime
logging.SetGlobalLevel(level)
+ config.Mu.Lock()
h.config.LogLevel = level
+ config.Mu.Unlock()
log.Info().Str("level", level).Msg("Log level updated via API")
// 2. Persist to system.json
diff --git a/internal/api/log_handlers_additional_test.go b/internal/api/log_handlers_additional_test.go
index d099f0f544..ba5eb01b7e 100644
--- a/internal/api/log_handlers_additional_test.go
+++ b/internal/api/log_handlers_additional_test.go
@@ -140,29 +140,19 @@ func TestLogHandlers_HandleDownloadBundle(t *testing.T) {
t.Fatalf("unmarshal system-info: %v", err)
}
- if payload.Config.AuthPass != "[REDACTED]" {
- t.Fatalf("expected AuthPass redacted, got %q", payload.Config.AuthPass)
- }
- if payload.Config.APIToken != "[REDACTED]" {
- t.Fatalf("expected APIToken redacted, got %q", payload.Config.APIToken)
- }
- if payload.Config.ProxyAuthSecret != "[REDACTED]" {
- t.Fatalf("expected ProxyAuthSecret redacted, got %q", payload.Config.ProxyAuthSecret)
- }
- if payload.Config.PVEInstances[0].Password != "[REDACTED]" {
- t.Fatalf("expected PVE password redacted, got %q", payload.Config.PVEInstances[0].Password)
+ // Configuration/environment are an allowlisted diagnostic summary, not a
+ // redacted full configuration backup. Unknown environment is absent.
+ for _, forbidden := range []string{"super-secret", "password", "proxy-secret", "pve-pass", "pve-token", "pbs-pass", "pbs-token", "pmg-pass", "pmg-token"} {
+ if strings.Contains(string(systemInfo), forbidden) {
+ t.Fatalf("system-info disclosed a synthetic credential")
+ }
}
-
- var redactedEnv bool
for _, env := range payload.Env {
if strings.HasPrefix(env, "TEST_SECRET=") {
- redactedEnv = strings.Contains(env, "[REDACTED]")
- break
+ t.Fatal("unknown environment must not be copied")
}
}
- if !redactedEnv {
- t.Fatalf("expected TEST_SECRET to be redacted, got env: %#v", payload.Env)
- }
+
}
func TestLogHandlers_HandleSetLevelAndGetLevel(t *testing.T) {
diff --git a/scripts/tests/test_vm_disk_diagnostics.py b/scripts/tests/test_vm_disk_diagnostics.py
index 8c9a5947c6..e43b95840d 100644
--- a/scripts/tests/test_vm_disk_diagnostics.py
+++ b/scripts/tests/test_vm_disk_diagnostics.py
@@ -835,11 +835,13 @@ class ServerLogSafetyDocsTest(unittest.TestCase):
"Keep the archive private", "manually reviewed, redacted excerpts",
"not a guarantee that all content is safe to publish")
handler = (ROOT / "internal/api/log_handlers.go").read_text().split("func (h *LogHandlers) HandleDownloadBundle", 1)[1].split("type SetLogLevelRequest", 1)[0]
- for source in ('os.Open(h.config.LogFile)', 'zipWriter.Create("pulse.log")',
+ for source in ('os.Open(logFile)', 'zipWriter.Create("pulse.log")',
'io.Copy(wr, f)', 'zipWriter.Create("pulse-tail.log")',
'logging.GetBroadcaster().GetHistory()', 'zipWriter.Create("system-info.json")',
- 'h.config.DeepCopy()', 'os.Environ()'):
+ 'newSupportBundleConfig(h.config)', 'supportBundleEnvironment(os.Environ())'):
self.assertIn(source, handler)
+ self.assertNotIn("h.config.DeepCopy()", handler)
+ self.assertNotIn("*config.Config", handler)
state = (ROOT / "frontend-modern/src/components/Settings/useSystemLogsPanelState.ts").read_text()
self.assertIn("window.location.href = '/api/logs/download'", state)
trouble = " ".join((ROOT / "docs/TROUBLESHOOTING.md").read_text().split("### Collect diagnostics safely\n", 1)[1].split("### Inspect Notification Logs", 1)[0].split())