Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Keep rejected infrastructure credentials out of client diagnostics
pulse-triage[bot]90ad71f9a498
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 84c5781e97..be7663fa11 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -17,6 +17,26 @@## Purpose+### Rejected infrastructure URLs stay out of diagnostics++PVE/PBS constructors validate a host before logging it. URL syntax errors omit+`url.Parse`'s copy of the supplied input; ordinary validation reasons remain.+Cluster logs, health snapshots, recovery summaries and aggregate errors use+display-only labels:+a valid base URL or `[invalid endpoint]`. Health snapshots preserve each entry+even when rejected endpoints share that label, and are built only for enabled+log events. These labels never supply routing,+alias membership, saved configuration or TLS-pin identity. HTTP/HTTPS defaults,+base paths, authentication, CA/pin/opt-out choices and guest fences are unchanged.++`TestClientRejectedHostDiagnosticsContainNoCredentials` and+`TestClusterRejectedEndpointDiagnosticsContainNoCredentials` exercise actual+constructors, single/multiple endpoint routing and recovery with synthetic+userinfo/query/fragment and malformed URLs. Accepted-host and+`TestInfrastructureURLValidationPolicyUnchanged` controls preserve ordinary+routing and diagnostics. This bounds client diagnostics, not arbitrary provider+error text, previously saved logs, native trust recovery or an installed service.+### PBS password renewal publishes one complete shared sessionConcurrent reads of an expired PBS password session share one in-flightdiff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex bfdeb82285..cd79f6a036 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -6354,6 +6354,7 @@"internal/monitoring/issue1613_contract_test.go","internal/monitoring/monitor_pve_guest_lxc_test.go","internal/monitoring/ratetracker_test.go",+ "pkg/proxmox/host_diagnostics_regression_test.go","pkg/proxmox/io_counters_test.go"]},@@ -6384,7 +6385,8 @@"internal/monitoring/monitor_pve_cluster_refresh_test.go","internal/monitoring/monitor_pve_disk_fallback_test.go","pkg/proxmox/cluster_client_additional_api4_test.go",- "pkg/proxmox/cluster_client_api_test.go"+ "pkg/proxmox/cluster_client_api_test.go",+ "pkg/proxmox/host_diagnostics_regression_test.go"]},{@@ -6470,7 +6472,8 @@"exact_files": ["pkg/pbs/auth_session_concurrency_test.go","pkg/pbs/client_http_test.go",- "pkg/pbs/client_test.go"+ "pkg/pbs/client_test.go",+ "pkg/pbs/host_diagnostics_regression_test.go"]},{@@ -7566,6 +7569,7 @@"internal/config/watcher.go","internal/crypto/crypto.go","internal/logging/logging.go",+ "internal/securityutil/infrastructure_url.go","internal/securityutil/private_path_other.go","internal/securityutil/private_path_windows.go","internal/securityutil/secure_storage_dir.go",@@ -7853,6 +7857,21 @@"pkg/auth/sqlite_manager_test.go","pkg/server/server_test.go"]+ },+ {+ "id": "infrastructure-endpoint-diagnostics",+ "label": "rejected infrastructure URL confidentiality proof",+ "match_prefixes": [],+ "match_files": [+ "internal/securityutil/infrastructure_url.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/securityutil/infrastructure_url_test.go",+ "pkg/pbs/host_diagnostics_regression_test.go",+ "pkg/proxmox/host_diagnostics_regression_test.go"+ ]}],"match_files": nulldiff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex df247b26bd..983efc60fe 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -18,6 +18,26 @@## Purpose+### Rejected infrastructure URLs stay out of diagnostics++PVE/PBS constructors validate a host before logging it. URL syntax errors omit+`url.Parse`'s copy of the supplied input; ordinary validation reasons remain.+Cluster logs, health snapshots, recovery summaries and aggregate errors use+display-only labels:+a valid base URL or `[invalid endpoint]`. Health snapshots preserve each entry+even when rejected endpoints share that label, and are built only for enabled+log events. These labels never supply routing,+alias membership, saved configuration or TLS-pin identity. HTTP/HTTPS defaults,+base paths, authentication, CA/pin/opt-out choices and guest fences are unchanged.++`TestClientRejectedHostDiagnosticsContainNoCredentials` and+`TestClusterRejectedEndpointDiagnosticsContainNoCredentials` exercise actual+constructors, single/multiple endpoint routing and recovery with synthetic+userinfo/query/fragment and malformed URLs. Accepted-host and+`TestInfrastructureURLValidationPolicyUnchanged` controls preserve ordinary+routing and diagnostics. This bounds client diagnostics, not arbitrary provider+error text, previously saved logs, native trust recovery or an installed service.+### Startup provisioning cannot replace retained access`pkg/server/server.go` admits environment-selected startup import only into andiff --git a/internal/securityutil/infrastructure_url.go b/internal/securityutil/infrastructure_url.gonew file mode 100644index 0000000000..2e54ecb0f3--- /dev/null+++ b/internal/securityutil/infrastructure_url.go@@ -0,0 +1,38 @@+package securityutil++import (+ "errors"+ "fmt"+ "net/url"+)++// NormalizeInfrastructureBaseURL keeps the ordinary base-URL policy, but must+// not return url.Parse's copy of rejected input in an error. Configuration can+// accidentally put credentials in userinfo, a query, or even invalid syntax.+func NormalizeInfrastructureBaseURL(raw, defaultScheme string) (*url.URL, error) {+ u, err := NormalizeHTTPBaseURL(raw, defaultScheme)+ var parseError *url.Error+ if errors.As(err, &parseError) {+ return nil, fmt.Errorf("URL syntax is invalid")+ }+ return u, err+}++// InfrastructureEndpointDiagnostic is a display-only label, never a routing or+// trust identity. Only validated base URLs may enter logs and error messages.+// Invalid input stays in its owning configuration, not in a diagnostic label.+func InfrastructureEndpointDiagnostic(raw string) string {+ u, err := NormalizeInfrastructureBaseURL(raw, "https")+ if err != nil {+ return "[invalid endpoint]"+ }+ return u.String()+}++func InfrastructureEndpointsDiagnostic(raw []string) []string {+ labels := make([]string, len(raw))+ for i, endpoint := range raw {+ labels[i] = InfrastructureEndpointDiagnostic(endpoint)+ }+ return labels+}diff --git a/internal/securityutil/infrastructure_url_test.go b/internal/securityutil/infrastructure_url_test.gonew file mode 100644index 0000000000..6a939b9124--- /dev/null+++ b/internal/securityutil/infrastructure_url_test.go@@ -0,0 +1,59 @@+package securityutil++import (+ "reflect"+ "strings"+ "testing"+)++func TestInfrastructureURLDiagnosticDoesNotBorrowInput(t *testing.T) {+ for _, raw := range []string{+ "https://fixture:[email protected]",+ "https://pve.invalid?token=synthetic-secret",+ "https://pve.invalid#synthetic-secret",+ "https://fixture:[email protected]:bad-port",+ "https://pve.invalid/%invalid?token=synthetic-secret",+ "https://[synthetic-secret",+ "https://pve.invalid:\nsynthetic-secret",+ } {+ u, err := NormalizeInfrastructureBaseURL(raw, "https")+ if err == nil || u != nil {+ t.Fatal("invalid infrastructure URL admitted")+ }+ if strings.Contains(err.Error(), "synthetic-secret") {+ t.Error("syntax diagnostic copied rejected input")+ }+ if got := InfrastructureEndpointDiagnostic(raw); got != "[invalid endpoint]" {+ t.Error("invalid endpoint acquired a diagnostic label")+ }+ }++ raw := []string{"pve.invalid/tenant", "https://fixture:[email protected]", "pve.invalid/tenant"}+ before := append([]string(nil), raw...)+ labels := InfrastructureEndpointsDiagnostic(raw)+ if !reflect.DeepEqual(labels, []string{"https://pve.invalid/tenant", "[invalid endpoint]", "https://pve.invalid/tenant"}) || !reflect.DeepEqual(raw, before) {+ t.Error("label generation changed membership, order or duplicates")+ }+ labels[0] = "changed-label"+ if !reflect.DeepEqual(raw, before) {+ t.Error("display labels retained mutable routing storage")+ }+}++func TestInfrastructureURLValidationPolicyUnchanged(t *testing.T) {+ for _, raw := range []string{+ "pve.invalid/tenant/../proxy/",+ "http://pve.invalid:8006/proxy",+ "https://[::1]:8006/proxy",+ "https://[fe80::1%25ZoneA]:8006/proxy",+ "https://pve.invalid//proxy",+ "ftp://pve.invalid",+ "",+ } {+ ordinary, ordinaryErr := NormalizeHTTPBaseURL(raw, "https")+ private, privateErr := NormalizeInfrastructureBaseURL(raw, "https")+ if (ordinaryErr == nil) != (privateErr == nil) || !reflect.DeepEqual(ordinary, private) {+ t.Errorf("diagnostic wrapper changed validation/routing for non-secret fixture: %q", raw)+ }+ }+}diff --git a/pkg/pbs/client.go b/pkg/pbs/client.goindex 16f52a1c8c..4473091f8f 100644--- a/pkg/pbs/client.go+++ b/pkg/pbs/client.go@@ -118,21 +118,23 @@ type auth struct {// NewClient creates a new PBS API clientfunc NewClient(cfg ClientConfig) (*Client, error) {// Normalize host URL - ensure it has a protocol- if !strings.HasPrefix(cfg.Host, "http://") && !strings.HasPrefix(cfg.Host, "https://") {+ defaultedScheme := !strings.HasPrefix(cfg.Host, "http://") && !strings.HasPrefix(cfg.Host, "https://")+ if defaultedScheme {// Default to HTTPS if no protocol specifiedcfg.Host = "https://" + cfg.Host- // Log that we're defaulting to HTTPS- log.Debug().Str("host", cfg.Host).Msg("No protocol specified in PBS host, defaulting to HTTPS")}- // Warn if using HTTP- if strings.HasPrefix(cfg.Host, "http://") {- log.Warn().Str("host", cfg.Host).Msg("Using HTTP for PBS connection. PBS typically requires HTTPS. If connection fails, try using https:// instead")- }- baseHostURL, err := securityutil.NormalizeHTTPBaseURL(cfg.Host, "")+ baseHostURL, err := securityutil.NormalizeInfrastructureBaseURL(cfg.Host, "")if err != nil {return nil, fmt.Errorf("invalid PBS host: %w", err)}+ // Logs must use validated input: a refused host can contain credentials.+ if defaultedScheme {+ log.Debug().Str("host", baseHostURL.String()).Msg("No protocol specified in PBS host, defaulting to HTTPS")+ }+ if baseHostURL.Scheme == "http" {+ log.Warn().Str("host", baseHostURL.String()).Msg("Using HTTP for PBS connection. PBS typically requires HTTPS. If connection fails, try using https:// instead")+ }baseAPIURL := securityutil.AppendURLPath(baseHostURL, "api2", "json")var user, realm stringdiff --git a/pkg/pbs/host_diagnostics_regression_test.go b/pkg/pbs/host_diagnostics_regression_test.gonew file mode 100644index 0000000000..a57b0a71b7--- /dev/null+++ b/pkg/pbs/host_diagnostics_regression_test.go@@ -0,0 +1,80 @@+package pbs++import (+ "bytes"+ "encoding/json"+ "fmt"+ "net/url"+ "strings"+ "testing"++ "github.com/rs/zerolog"+ "github.com/rs/zerolog/log"+)++// Non-parallel: temporarily replace the package logger, then restore it before+// parallel tests can run. Only synthetic URLs/credentials enter this fixture.+func TestClientRejectedHostDiagnosticsContainNoCredentials(t *testing.T) {+ for index, host := range []string{+ "https://synthetic-user:[email protected]",+ "http://synthetic-user:[email protected]",+ "synthetic-user:[email protected]",+ "https://pve.invalid?token=synthetic-secret",+ "http://pve.invalid#synthetic-secret",+ "pve.invalid?token=synthetic-secret",+ "https://synthetic-user:[email protected]:bad-port",+ "https://pve.invalid/%invalid?token=synthetic-secret",+ } {+ // Use a safe index rather than the supplied host as the test name/output.+ t.Run(fmt.Sprintf("case-%d", index), func(t *testing.T) {+ var captured bytes.Buffer+ prior := log.Logger+ log.Logger = zerolog.New(&captured).Level(zerolog.DebugLevel)+ defer func() { log.Logger = prior }()+ client, err := NewClient(ClientConfig{Host: host, TokenName: "fixture@pbs!pulse", TokenValue: "synthetic-token"})+ if client != nil || err == nil {+ t.Fatal("invalid URL must be refused before authentication")+ }+ if strings.Contains(err.Error(), "synthetic-secret") || strings.Contains(err.Error(), "synthetic-user") {+ t.Error("constructor diagnostic exposed rejected URL credentials")+ }+ if strings.Contains(captured.String(), "synthetic-secret") || strings.Contains(captured.String(), "synthetic-user") {+ t.Error("constructor log exposed rejected URL credentials")+ }+ t.Logf("refused=true captured_log_bytes=%d private_error=%t", captured.Len(), !strings.Contains(err.Error(), "synthetic-secret"))+ })+ }+}++func TestClientAcceptedHostDiagnosticsRemainUseful(t *testing.T) {+ for _, host := range []string{"pve.invalid/tenant", "http://pve.invalid/tenant", "https://pve.invalid/tenant"} {+ var captured bytes.Buffer+ prior := log.Logger+ log.Logger = zerolog.New(&captured).Level(zerolog.DebugLevel)+ client, err := NewClient(ClientConfig{Host: host, TokenName: "fixture@pbs!pulse", TokenValue: "synthetic-token"})+ log.Logger = prior+ if err != nil {+ t.Fatal(err)+ }+ defer client.httpClient.CloseIdleConnections()+ if !strings.HasSuffix(client.baseURL, "/tenant/api2/json") {+ t.Fatal("diagnostic filtering changed the route")+ }+ if strings.Contains(captured.String(), "synthetic-token") {+ t.Fatal("accepted diagnostic disclosed a token")+ }+ decoder := json.NewDecoder(&captured)+ for decoder.More() {+ var event map[string]interface{}+ if err := decoder.Decode(&event); err != nil {+ t.Fatal(err)+ }+ if value, ok := event["host"].(string); ok {+ parsed, err := url.Parse(value)+ if err != nil || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {+ t.Fatal("host diagnostic is not a validated base URL")+ }+ }+ }+ }+}diff --git a/pkg/proxmox/client.go b/pkg/proxmox/client.goindex 9613d2cca2..c12f0e8f49 100644--- a/pkg/proxmox/client.go+++ b/pkg/proxmox/client.go@@ -319,15 +319,6 @@ type auth struct {func NewClient(cfg ClientConfig) (*Client, error) {var user, realm string- // Log what auth method we're using- log.Debug().- Str("host", cfg.Host).- Bool("hasToken", cfg.TokenName != "").- Bool("hasPassword", cfg.Password != "").- Str("tokenName", cfg.TokenName).- Str("user", cfg.User).- Msg("Creating Proxmox client")-// For token authentication, we don't need user@realm formatif cfg.TokenName != "" && cfg.TokenValue != "" {// Extract user and realm from token name (format: user@realm!tokenname)@@ -364,14 +355,26 @@ func NewClient(cfg ClientConfig) (*Client, error) {if baseHost == "" {return nil, fmt.Errorf("host is required")}- if !strings.HasPrefix(baseHost, "http://") && !strings.HasPrefix(baseHost, "https://") {+ defaultedScheme := !strings.HasPrefix(baseHost, "http://") && !strings.HasPrefix(baseHost, "https://")+ if defaultedScheme {baseHost = "https://" + baseHost- log.Debug().Str("host", baseHost).Msg("No protocol specified in Proxmox host, defaulting to HTTPS")}- baseHostURL, err := securityutil.NormalizeHTTPBaseURL(baseHost, "")+ baseHostURL, err := securityutil.NormalizeInfrastructureBaseURL(baseHost, "")if err != nil {return nil, fmt.Errorf("invalid Proxmox host: %w", err)}+ // Do not log raw configuration before URL validation.+ log.Debug().+ Str("host", baseHostURL.String()).+ Bool("hasToken", cfg.TokenName != "").+ Bool("hasPassword", cfg.Password != "").+ Str("tokenName", cfg.TokenName).+ Str("user", cfg.User).+ Msg("Creating Proxmox client")++ if defaultedScheme {+ log.Debug().Str("host", baseHostURL.String()).Msg("No protocol specified in Proxmox host, defaulting to HTTPS")+ }if baseHostURL.Scheme == "http" {log.Warn().Str("host", baseHostURL.String()).Msg("Using HTTP for Proxmox connection - consider enabling HTTPS")}diff --git a/pkg/proxmox/cluster_client.go b/pkg/proxmox/cluster_client.goindex baeb0574d1..c72eab250a 100644--- a/pkg/proxmox/cluster_client.go+++ b/pkg/proxmox/cluster_client.go@@ -14,6 +14,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/securityutil""github.com/rcourtman/pulse-go-rewrite/pkg/tlsutil"+ "github.com/rs/zerolog""github.com/rs/zerolog/log")@@ -300,7 +301,7 @@ func (cc *ClusterClient) refreshTOFUFingerprintAndRetry(ctx context.Context, endif err != nil {log.Warn().Str("cluster", cc.name).- Str("endpoint", endpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(endpoint)).Err(err).Msg("Failed to refresh TOFU fingerprint after mismatch")return nil, lastErr, false@@ -327,7 +328,7 @@ func (cc *ClusterClient) refreshTOFUFingerprintAndRetry(ctx context.Context, endif captured {log.Warn().Str("cluster", cc.name).- Str("endpoint", endpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(endpoint)).Msg("Trusting cluster member certificate on first use; the pinned primary fingerprint cannot match per-node certificates")}@@ -355,7 +356,7 @@ func (cc *ClusterClient) initialHealthCheck() {if len(cc.endpoints) == 1 {log.Info().Str("cluster", cc.name).- Str("endpoint", cc.endpoints[0]).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(cc.endpoints[0])).Msg("Single endpoint cluster - skipping initial health check")return}@@ -384,7 +385,7 @@ func (cc *ClusterClient) initialHealthCheck() {cc.mu.Unlock()log.Info().Str("cluster", cc.name).- Str("endpoint", ep).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(ep)).Err(err).Msg("Cluster endpoint marked unhealthy on initialization")return@@ -417,7 +418,7 @@ func (cc *ClusterClient) initialHealthCheck() {cc.mu.Unlock()log.Warn().Str("cluster", cc.name).- Str("endpoint", ep).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(ep)).Err(clientErr).Msg("Failed to create full client after successful health check")} else {@@ -429,12 +430,12 @@ func (cc *ClusterClient) initialHealthCheck() {if vmSpecificErr {log.Debug().Str("cluster", cc.name).- Str("endpoint", ep).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(ep)).Msg("Cluster endpoint healthy despite VM-specific errors")} else {log.Info().Str("cluster", cc.name).- Str("endpoint", ep).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(ep)).Msg("Cluster endpoint passed initial health check")}}@@ -447,7 +448,7 @@ func (cc *ClusterClient) initialHealthCheck() {cc.mu.Unlock()log.Info().Str("cluster", cc.name).- Str("endpoint", ep).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(ep)).Err(err).Msg("Cluster endpoint failed initial health check")}@@ -512,6 +513,22 @@ func (cc *ClusterClient) hasRecoverableUnhealthyEndpointLocked(now time.Time) boreturn false}+type endpointHealthDiagnostic struct {+ Endpoint string `json:"endpoint"`+ Healthy bool `json:"healthy"`+}++// endpointHealthDiagnosticsLocked is logging-only. A slice preserves multiple+// invalid endpoints with the same safe label without exposing map keys. cc.mu+// is held by the caller; routing and health storage retain their own identities.+func (cc *ClusterClient) endpointHealthDiagnosticsLocked() []endpointHealthDiagnostic {+ statuses := make([]endpointHealthDiagnostic, 0, len(cc.nodeHealth))+ for endpoint, healthy := range cc.nodeHealth {+ statuses = append(statuses, endpointHealthDiagnostic{securityutil.InfrastructureEndpointDiagnostic(endpoint), healthy})+ }+ return statuses+}+// getHealthyClient returns the first available endpoint in configured priority// order. The first endpoint is the operator-configured cluster URL; discovered// member addresses are failover candidates rather than a random load-balancing@@ -542,7 +559,9 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)Str("cluster", cc.name).Int("healthy", len(healthyEndpoints)).Int("total", len(cc.nodeHealth)).- Interface("nodeHealth", cc.nodeHealth).+ Func(func(event *zerolog.Event) {+ event.Interface("nodeHealth", cc.endpointHealthDiagnosticsLocked())+ }).Msg("No healthy endpoints available - attempting recovery")} else {log.Debug().@@ -550,7 +569,9 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)Int("healthy", len(healthyEndpoints)).Int("cooling", len(coolingEndpoints)).Int("total", len(cc.nodeHealth)).- Interface("nodeHealth", cc.nodeHealth).+ Func(func(event *zerolog.Event) {+ event.Interface("nodeHealth", cc.endpointHealthDiagnosticsLocked())+ }).Msg("Checking for healthy endpoints")}@@ -584,7 +605,7 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)if len(cc.endpoints) == 1 {log.Warn().Str("cluster", cc.name).- Str("endpoint", cc.endpoints[0]).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(cc.endpoints[0])).Msg("Single endpoint appears unhealthy but attempting to use it anyway")healthyEndpoints = cc.endpoints// Mark it as healthy optimistically@@ -602,15 +623,15 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)if !cc.nodeHealth[ep] {unhealthyList = append(unhealthyList, ep)if reason := strings.TrimSpace(cc.lastError[ep]); reason != "" {- endpointReasons = append(endpointReasons, fmt.Sprintf("%s: %s", ep, reason))+ endpointReasons = append(endpointReasons, fmt.Sprintf("%s: %s", securityutil.InfrastructureEndpointDiagnostic(ep), reason))} else {- endpointReasons = append(endpointReasons, fmt.Sprintf("%s: no recorded reason", ep))+ endpointReasons = append(endpointReasons, fmt.Sprintf("%s: no recorded reason", securityutil.InfrastructureEndpointDiagnostic(ep)))}}}log.Error().Str("cluster", cc.name).- Strs("unhealthyEndpoints", unhealthyList).+ Strs("unhealthyEndpoints", securityutil.InfrastructureEndpointsDiagnostic(unhealthyList)).Int("totalEndpoints", len(cc.endpoints)).Msg("All cluster endpoints are unhealthy - verify network connectivity and API accessibility from Pulse server")return nil, fmt.Errorf("no healthy nodes available in cluster %s (%d endpoints failed: %s)", cc.name, len(cc.endpoints), strings.Join(endpointReasons, "; "))@@ -637,10 +658,10 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)cc.nodeHealth[selectedEndpoint] = falselog.Debug().Str("cluster", cc.name).- Str("endpoint", selectedEndpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(selectedEndpoint)).Err(err).Msg("Failed to create client for cluster endpoint")- return nil, fmt.Errorf("failed to create client for %s: %w", selectedEndpoint, err)+ return nil, fmt.Errorf("failed to create client for %s: %w", securityutil.InfrastructureEndpointDiagnostic(selectedEndpoint), err)}// Connectivity test - 5 seconds to allow for TLS handshake (~3s typical)@@ -653,7 +674,7 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)if isRateLimited, _ := isTransientRateLimitError(testErr); isRateLimited {log.Debug().Str("cluster", cc.name).- Str("endpoint", selectedEndpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(selectedEndpoint)).Err(testErr).Msg("Ignoring transient rate limit error during connectivity test")// Continue with client creation since the node is accessible, just rate limited@@ -667,7 +688,7 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)// The node is actually healthy, so don't mark it unhealthylog.Debug().Str("cluster", cc.name).- Str("endpoint", selectedEndpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(selectedEndpoint)).Err(testErr).Msg("Ignoring VM-specific error during connectivity test")// Continue with client creation since the node is actually accessible@@ -676,17 +697,17 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)cc.nodeHealth[selectedEndpoint] = falselog.Warn().Str("cluster", cc.name).- Str("endpoint", selectedEndpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(selectedEndpoint)).Err(testErr).Msg("Failed to connect to Proxmox endpoint; endpoint removed from rotation until next refresh")- return nil, fmt.Errorf("endpoint %s failed connectivity test: %w", selectedEndpoint, testErr)+ return nil, fmt.Errorf("endpoint %s failed connectivity test: %w", securityutil.InfrastructureEndpointDiagnostic(selectedEndpoint), testErr)}}}log.Debug().Str("cluster", cc.name).- Str("endpoint", selectedEndpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(selectedEndpoint)).Int("nodes", len(testNodes)).Msg("Cluster endpoint passed connectivity test")@@ -698,7 +719,7 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)if err != nil {// This shouldn't happen since we just tested itcc.nodeHealth[selectedEndpoint] = false- return nil, fmt.Errorf("failed to create client for %s: %w", selectedEndpoint, err)+ return nil, fmt.Errorf("failed to create client for %s: %w", securityutil.InfrastructureEndpointDiagnostic(selectedEndpoint), err)}cc.clients[selectedEndpoint] = newClient@@ -716,7 +737,7 @@ func (cc *ClusterClient) markUnhealthyWithError(endpoint string, errMsg string)if cc.nodeHealth[endpoint] {log.Warn().Str("cluster", cc.name).- Str("endpoint", endpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(endpoint)).Str("error", errMsg).Msg("Marking cluster node as unhealthy")cc.nodeHealth[endpoint] = false@@ -764,7 +785,7 @@ func (cc *ClusterClient) recoverUnhealthyNodes(ctx context.Context) {if len(throttledEndpoints) > 0 {log.Debug().Str("cluster", cc.name).- Strs("throttledEndpoints", throttledEndpoints).+ Strs("throttledEndpoints", securityutil.InfrastructureEndpointsDiagnostic(throttledEndpoints)).Msg("Skipping recovery check - endpoints checked recently")}return@@ -772,7 +793,7 @@ func (cc *ClusterClient) recoverUnhealthyNodes(ctx context.Context) {log.Info().Str("cluster", cc.name).- Strs("unhealthyEndpoints", unhealthyEndpoints).+ Strs("unhealthyEndpoints", securityutil.InfrastructureEndpointsDiagnostic(unhealthyEndpoints)).Int("count", len(unhealthyEndpoints)).Msg("Attempting to recover unhealthy cluster endpoints")@@ -815,7 +836,7 @@ func (cc *ClusterClient) recoverUnhealthyNodes(ctx context.Context) {recordFailure(ep, err)log.Debug().Str("cluster", cc.name).- Str("endpoint", ep).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(ep)).Err(err).Msg("Failed to create client during recovery attempt")return@@ -852,19 +873,19 @@ func (cc *ClusterClient) recoverUnhealthyNodes(ctx context.Context) {if vmSpecificErr {log.Info().Str("cluster", cc.name).- Str("endpoint", ep).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(ep)).Msg("Recovered unhealthy cluster node (ignoring VM-specific errors)")} else {log.Info().Str("cluster", cc.name).- Str("endpoint", ep).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(ep)).Msg("Recovered unhealthy cluster node")}} else {recordFailure(ep, err)log.Debug().Str("cluster", cc.name).- Str("endpoint", ep).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(ep)).Err(err).Msg("Recovery attempt failed - endpoint still unhealthy")}@@ -898,14 +919,14 @@ func (cc *ClusterClient) recoverUnhealthyNodes(ctx context.Context) {reasons := make([]string, 0, len(failureReasons))for _, ep := range unhealthyEndpoints {if reason, ok := failureReasons[ep]; ok {- reasons = append(reasons, ep+": "+reason)+ reasons = append(reasons, securityutil.InfrastructureEndpointDiagnostic(ep)+": "+reason)}}failureMu.Unlock()log.Warn().Str("cluster", cc.name).Int("attempted", len(unhealthyEndpoints)).- Strs("failedEndpoints", unhealthyEndpoints).+ Strs("failedEndpoints", securityutil.InfrastructureEndpointsDiagnostic(unhealthyEndpoints)).Strs("failureReasons", reasons).Msg("No endpoints recovered - cluster may be unreachable from Pulse server")}@@ -960,7 +981,7 @@ func (cc *ClusterClient) executeWithFailover(ctx context.Context, fn func(*Clienevent := log.Warn().Str("cluster", cc.name).- Str("endpoint", clientEndpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(clientEndpoint)).Err(err).Dur("backoff", backoff).Int("attempt", i+1)@@ -995,7 +1016,7 @@ func (cc *ClusterClient) executeWithFailover(ctx context.Context, fn func(*Cliencc.markUnhealthyWithError(clientEndpoint, err.Error())log.Warn().Str("cluster", cc.name).- Str("endpoint", clientEndpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(clientEndpoint)).Err(err).Int("attempt", i+1).Msg("Connectivity error, trying next cluster endpoint")@@ -1006,7 +1027,7 @@ func (cc *ClusterClient) executeWithFailover(ctx context.Context, fn func(*Clien// (HTTP 4xx/5xx, parsing error, VM-specific error, etc.)log.Debug().Str("cluster", cc.name).- Str("endpoint", clientEndpoint).+ Str("endpoint", securityutil.InfrastructureEndpointDiagnostic(clientEndpoint)).Err(err).Msg("Request-level error, endpoint reachable - not marking unhealthy")return errdiff --git a/pkg/proxmox/host_diagnostics_regression_test.go b/pkg/proxmox/host_diagnostics_regression_test.gonew file mode 100644index 0000000000..947a00e119--- /dev/null+++ b/pkg/proxmox/host_diagnostics_regression_test.go@@ -0,0 +1,159 @@+package proxmox++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "net/url"+ "strings"+ "testing"+ "time"++ "github.com/rs/zerolog"+ "github.com/rs/zerolog/log"+)++// Non-parallel: temporarily replace the package logger, then restore it before+// parallel tests can run. Only synthetic URLs/credentials enter this fixture.+func TestClientRejectedHostDiagnosticsContainNoCredentials(t *testing.T) {+ for index, host := range []string{+ "https://synthetic-user:[email protected]",+ "http://synthetic-user:[email protected]",+ "synthetic-user:[email protected]",+ "https://pve.invalid?token=synthetic-secret",+ "http://pve.invalid#synthetic-secret",+ "pve.invalid?token=synthetic-secret",+ "https://synthetic-user:[email protected]:bad-port",+ "https://pve.invalid/%invalid?token=synthetic-secret",+ } {+ // Use a safe index rather than the supplied host as the test name/output.+ t.Run(fmt.Sprintf("case-%d", index), func(t *testing.T) {+ var captured bytes.Buffer+ prior := log.Logger+ log.Logger = zerolog.New(&captured).Level(zerolog.DebugLevel)+ defer func() { log.Logger = prior }()+ client, err := NewClient(ClientConfig{Host: host, TokenName: "fixture@pve!pulse", TokenValue: "synthetic-token"})+ if client != nil || err == nil {+ t.Fatal("invalid URL must be refused before authentication")+ }+ if strings.Contains(err.Error(), "synthetic-secret") || strings.Contains(err.Error(), "synthetic-user") {+ t.Error("constructor diagnostic exposed rejected URL credentials")+ }+ if strings.Contains(captured.String(), "synthetic-secret") || strings.Contains(captured.String(), "synthetic-user") {+ t.Error("constructor log exposed rejected URL credentials")+ }+ t.Logf("refused=true captured_log_bytes=%d private_error=%t", captured.Len(), !strings.Contains(err.Error(), "synthetic-secret"))+ })+ }+}++func TestClientAcceptedHostDiagnosticsRemainUseful(t *testing.T) {+ for _, host := range []string{"pve.invalid/tenant", "http://pve.invalid/tenant", "https://pve.invalid/tenant"} {+ var captured bytes.Buffer+ prior := log.Logger+ log.Logger = zerolog.New(&captured).Level(zerolog.DebugLevel)+ client, err := NewClient(ClientConfig{Host: host, TokenName: "fixture@pve!pulse", TokenValue: "synthetic-token"})+ log.Logger = prior+ if err != nil {+ t.Fatal(err)+ }+ defer client.httpClient.CloseIdleConnections()+ if !strings.HasSuffix(client.baseURL, "/tenant/api2/json") {+ t.Fatal("diagnostic filtering changed the route")+ }+ if strings.Contains(captured.String(), "synthetic-token") {+ t.Fatal("accepted diagnostic disclosed a token")+ }+ decoder := json.NewDecoder(&captured)+ for decoder.More() {+ var event map[string]interface{}+ if err := decoder.Decode(&event); err != nil {+ t.Fatal(err)+ }+ if value, ok := event["host"].(string); ok {+ parsed, err := url.Parse(value)+ if err != nil || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {+ t.Fatal("host diagnostic is not a validated base URL")+ }+ }+ }+ }+}++func TestClusterRejectedEndpointDiagnosticsContainNoCredentials(t *testing.T) {+ for _, host := range []string{+ "https://synthetic-user:[email protected]",+ "https://pve.invalid?token=synthetic-secret",+ "https://synthetic-user:[email protected]:bad-port",+ } {+ for _, count := range []int{1, 2} {+ var captured bytes.Buffer+ prior := log.Logger+ log.Logger = zerolog.New(zerolog.SyncWriter(&captured)).Level(zerolog.DebugLevel)+ func() {+ defer func() { log.Logger = prior }()+ endpoints := []string{host}+ if count == 2 {+ endpoints = append(endpoints, "https://synthetic-user:[email protected]")+ }+ cc := NewClusterClient("fixture", ClientConfig{Host: host, TokenName: "fixture@pve!pulse", TokenValue: "synthetic-token"}, endpoints, nil)+ _, err := cc.GetNodes(context.Background())+ if err == nil {+ t.Error("rejected endpoints did not stop cluster routing")+ } else if strings.Contains(err.Error(), "synthetic-secret") || strings.Contains(err.Error(), "synthetic-user") {+ t.Error("cluster error exposed rejected endpoint credentials")+ }+ for _, status := range cc.GetHealthStatusWithErrors() {+ if strings.Contains(status.LastError, "synthetic-secret") {+ t.Error("cluster health error exposed rejected input")+ }+ }+ cc.mu.Lock()+ for ep := range cc.lastHealthCheck {+ cc.lastHealthCheck[ep] = time.Now().Add(-time.Hour)+ }+ cc.mu.Unlock()+ cc.recoverUnhealthyNodes(context.Background())+ for ep := range cc.GetHealthStatus() {+ if !strings.Contains(ep, "synthetic-secret") {+ t.Error("diagnostic filtering rewrote configured routing identity")+ }+ }+ }()+ if strings.Contains(captured.String(), "synthetic-secret") || strings.Contains(captured.String(), "synthetic-user") {+ t.Error("cluster log exposed rejected endpoint credentials")+ }+ t.Logf("configured_endpoints=%d captured_log_bytes=%d", count, captured.Len())+ }+ }+}++func TestClusterDiagnosticHealthSnapshotKeepsEveryEndpoint(t *testing.T) {+ cc := &ClusterClient{nodeHealth: map[string]bool{+ "https://pve.invalid/tenant": true,+ "https://fixture:[email protected]": false,+ "https://fixture:[email protected]": true,+ }}+ cc.mu.Lock()+ defer cc.mu.Unlock()+ statuses := cc.endpointHealthDiagnosticsLocked()+ if len(statuses) != 3 || len(cc.nodeHealth) != 3 {+ t.Fatal("diagnostic labels collapsed membership")+ }+ invalid, healthy := 0, 0+ for _, status := range statuses {+ if status.Endpoint == "[invalid endpoint]" {+ invalid+++ }+ if status.Healthy {+ healthy+++ }+ if strings.Contains(status.Endpoint, "synthetic-secret") {+ t.Error("health diagnostic copied a raw map key")+ }+ }+ if invalid != 2 || healthy != 2 {+ t.Error("display snapshot lost endpoint status observations")+ }+}