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.

Refuse conflicting saved TLS pins for equivalent Proxmox URLs

pulse-triage[bot]bea93859d333
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 4b54080404..e47eebf2a5 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -17,6 +17,36 @@
## Purpose
+### Conflicting saved endpoint pins cannot select certificate trust
+
+For equivalent Proxmox endpoint URL spellings, all nonempty saved member pins
+must agree under the TLS verifier's existing case/colon normalization. Exact
+spelling and map iteration can no longer select one of contradictory pins.
+Resolution returns a fixed, credential-free trust-conflict error before a TLS
+probe, password login, token read, first-use capture or polling-client creation.
+The member stays unreachable to Pulse; an independently trusted sibling can
+continue ordinary monitoring. No saved pin is removed or overwritten, and the
+error cannot become an empty pin/CA or opt-out fallback. Agreeing pin formats,
+nonempty invalid pins, primary-pin fallback, declared-member first-use and the
+existing scheme/port/base-path/IPv4-mapped trust boundaries remain unchanged.
+
+`TestClusterConflictingSavedPinsNeverAuthenticate` covers startup, recovery and
+lazy selection in token/JSON/form modes, three URL spellings and both VerifySSL
+settings with real TLS sockets. It checks zero TLS/login/read work for conflicts,
+no installed client or trust mutation, sibling use, and accepted monitoring
+following a normal reload with reconciled fixture pins. Existing established-pin,
+first-use, cancellation, ownership and guest-admission controls still apply.
+`TestClusterSavedPinResolutionRejectsConflicts` and
+`TestClusterFirstUseCaptureDoesNotReconcileConflictingPins` retain the conflict
+through normalized authorities, invalid nonempty pins and a capture race.
+`TestClusterConflictingPinsEndpointProjection` uses the production endpoint
+builder, real clients and monitor projection in all three auth modes: native
+Online, identity and saved trust are not changed by failed Pulse reachability.
+This establishes source/consumer behaviour, not native recovery or attribution
+of a guest, PBS or certificate report. Exact duplicate saved rows collapsed by
+the builder's map are outside this URL-alias resolver contract.
+
+
### Cluster recovery requires success of the operation actually probed
Startup and unhealthy-member recovery read `/nodes`; lazy construction uses the
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 76dfda7013..339264d843 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -18,6 +18,36 @@
## Purpose
+### Conflicting saved endpoint pins cannot select certificate trust
+
+For equivalent Proxmox endpoint URL spellings, all nonempty saved member pins
+must agree under the TLS verifier's existing case/colon normalization. Exact
+spelling and map iteration can no longer select one of contradictory pins.
+Resolution returns a fixed, credential-free trust-conflict error before a TLS
+probe, password login, token read, first-use capture or polling-client creation.
+The member stays unreachable to Pulse; an independently trusted sibling can
+continue ordinary monitoring. No saved pin is removed or overwritten, and the
+error cannot become an empty pin/CA or opt-out fallback. Agreeing pin formats,
+nonempty invalid pins, primary-pin fallback, declared-member first-use and the
+existing scheme/port/base-path/IPv4-mapped trust boundaries remain unchanged.
+
+`TestClusterConflictingSavedPinsNeverAuthenticate` covers startup, recovery and
+lazy selection in token/JSON/form modes, three URL spellings and both VerifySSL
+settings with real TLS sockets. It checks zero TLS/login/read work for conflicts,
+no installed client or trust mutation, sibling use, and accepted monitoring
+following a normal reload with reconciled fixture pins. Existing established-pin,
+first-use, cancellation, ownership and guest-admission controls still apply.
+`TestClusterSavedPinResolutionRejectsConflicts` and
+`TestClusterFirstUseCaptureDoesNotReconcileConflictingPins` retain the conflict
+through normalized authorities, invalid nonempty pins and a capture race.
+`TestClusterConflictingPinsEndpointProjection` uses the production endpoint
+builder, real clients and monitor projection in all three auth modes: native
+Online, identity and saved trust are not changed by failed Pulse reachability.
+This establishes source/consumer behaviour, not native recovery or attribution
+of a guest, PBS or certificate report. Exact duplicate saved rows collapsed by
+the builder's map are outside this URL-alias resolver contract.
+
+
### First-use cluster trust includes password construction
Declared, previously untrusted Proxmox members use the existing credential-free
diff --git a/internal/monitoring/monitor_pve_pin_conflict_test.go b/internal/monitoring/monitor_pve_pin_conflict_test.go
new file mode 100644
index 0000000000..15aef0cbb5
--- /dev/null
+++ b/internal/monitoring/monitor_pve_pin_conflict_test.go
@@ -0,0 +1,134 @@
+package monitoring
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
+)
+
+// Use saved configuration, the production endpoint builder and real TLS
+// clients. Carry failed trust into the same member fields served to Settings.
+// A subsequent normal config reload has independently reconciled fixture
+// trust; this does not edit a live client's trust, probe guests or prove native
+// deployment/recovery, and says nothing about any reported incident's cause.
+func TestClusterConflictingPinsEndpointProjection(t *testing.T) {
+ for _, mode := range []string{"token", "password-json", "password-form"} {
+ t.Run(mode, func(t *testing.T) {
+ var badRequests atomic.Int32
+ endpoint := func(bad bool) *httptest.Server {
+ s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if bad {
+ badRequests.Add(1)
+ }
+ switch r.URL.Path {
+ case "/api2/json/access/ticket":
+ if mode == "password-form" && r.Header.Get("Content-Type") == "application/json" {
+ w.WriteHeader(http.StatusUnsupportedMediaType)
+ fmt.Fprint(w, `{"message":"fixture requires form encoding"}`)
+ return
+ }
+ fmt.Fprint(w, `{"data":{"ticket":"fixture-ticket","CSRFPreventionToken":"fixture-csrf"}}`)
+ case "/api2/json/nodes":
+ if mode == "token" {
+ if r.Header.Get("Authorization") != "PVEAPIToken=fixture@pve!pulse=fixture" {
+ t.Error("lost token fixture auth")
+ }
+ } else if r.Header.Get("Cookie") != "PVEAuthCookie=fixture-ticket" {
+ t.Error("lost fixture session")
+ }
+ fmt.Fprint(w, `{"data":[{"node":"primary","status":"online","cpu":0.125},{"node":"member","status":"online","cpu":0.25},{"node":"member-alias","status":"online","cpu":0.25}]}`)
+ default:
+ t.Errorf("left ordinary login/nodes path: %s", r.URL.Path)
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(s.Close)
+ return s
+ }
+ primary, member := endpoint(false), endpoint(true)
+ pin := func(s *httptest.Server) string {
+ sum := sha256.Sum256(s.Certificate().Raw)
+ return hex.EncodeToString(sum[:])
+ }
+ inst := config.PVEInstance{Name: "pin-conflict-cluster", Host: primary.URL, IsCluster: true, ClusterName: "Fixture cluster", VerifySSL: true, Fingerprint: pin(primary), ClusterEndpoints: []config.ClusterEndpoint{
+ {NodeName: "primary", NodeIdentity: "primary-identity", Host: primary.URL, Fingerprint: pin(primary)},
+ {NodeName: "member", NodeIdentity: "member-identity", Host: member.URL, Fingerprint: pin(member)},
+ {NodeName: "member-alias", NodeIdentity: "alias-identity", Host: member.URL + "/./", Fingerprint: strings.Repeat("0", 64)},
+ }}
+ m := &Monitor{config: &config.Config{PVEInstances: []config.PVEInstance{inst}}}
+ construct := func() *proxmox.ClusterClient {
+ endpoints, pins := m.buildClusterEndpointsForInit(inst)
+ if len(endpoints) != 3 || len(pins) != 3 {
+ t.Fatalf("saved alias evidence was collapsed: endpoints=%d pins=%d", len(endpoints), len(pins))
+ }
+ cfg := proxmox.ClientConfig{Host: inst.Host, Fingerprint: inst.Fingerprint, VerifySSL: true, Timeout: 2 * time.Second}
+ if mode == "token" {
+ cfg.TokenName = "fixture@pve!pulse"
+ cfg.TokenValue = "fixture"
+ } else {
+ cfg.User = "fixture@pam"
+ cfg.Password = "fixture-password"
+ }
+ return proxmox.NewClusterClient(inst.Name, cfg, endpoints, pins)
+ }
+ project := func(cc *proxmox.ClusterClient, phase string, conflict bool) {
+ nodes, err := cc.GetNodes(context.Background())
+ if err != nil || len(nodes) != 3 {
+ t.Fatalf("trusted primary lost ordinary monitoring: %v", err)
+ }
+ model := make([]models.Node, len(nodes))
+ for i, node := range nodes {
+ model[i] = models.Node{Name: node.Node, Status: node.Status}
+ }
+ m.updateClusterEndpointStatus(inst.Name, &inst, cc, model)
+ for i, ep := range inst.ClusterEndpoints {
+ if !ep.Online || ep.NodeIdentity != []string{"primary-identity", "member-identity", "alias-identity"}[i] {
+ t.Fatal("trust refusal changed native online state or identity")
+ }
+ if ep.PulseReachable == nil || *ep.PulseReachable != (i == 0 || !conflict) || ep.LastPulseCheck == nil {
+ t.Fatalf("missing/false Pulse reachability observation: %+v", ep)
+ }
+ if i > 0 && conflict && !strings.Contains(ep.PulseError, "TLS trust conflict") {
+ t.Fatalf("member lost actionable trust diagnostic: %+v", ep)
+ }
+ if !conflict && ep.PulseError != "" {
+ t.Fatalf("agreed trust kept a stale failure: %+v", ep)
+ }
+ }
+ wire, err := json.Marshal(struct {
+ Case, Phase string
+ Endpoints []config.ClusterEndpoint
+ }{mode, phase, inst.ClusterEndpoints})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("PIN_CONFLICT_ENDPOINT_PROJECTION_JSON=%s", wire)
+ }
+ refused := construct()
+ project(refused, "conflicting-saved-trust", true)
+ if badRequests.Load() != 0 || inst.ClusterEndpoints[2].Fingerprint != strings.Repeat("0", 64) {
+ t.Fatal("conflict reached credentials or rewrote saved trust")
+ }
+ // Normal source configuration reload, not mutation of the owned map or a
+ // forced/favourable repeat on the refused source. Native state stays online.
+ inst.ClusterEndpoints[2].Fingerprint = pin(member)
+ accepted := construct()
+ project(accepted, "reconciled-config-reload", false)
+ if badRequests.Load() == 0 {
+ t.Fatal("agreed saved trust never reached accepted ordinary use")
+ }
+ })
+ }
+}
diff --git a/pkg/proxmox/cluster_client.go b/pkg/proxmox/cluster_client.go
index 9dd1e0b39f..e6a3a4914b 100644
--- a/pkg/proxmox/cluster_client.go
+++ b/pkg/proxmox/cluster_client.go
@@ -53,6 +53,8 @@ var transientRateLimitStatusCodes = map[int]struct{}{
504: {},
}
+var errConflictingEndpointFingerprints = errors.New("TLS trust conflict - equivalent endpoint URLs have different saved fingerprints; independently verify and reconcile saved trust")
+
// isEndpointConnectivityError reports whether an error indicates the endpoint
// itself is unreachable (TCP, DNS, TLS failures). Application-level errors
// (HTTP responses, parsing errors) mean the endpoint IS reachable.
@@ -97,6 +99,9 @@ func sanitizeEndpointError(errMsg string) string {
if errMsg == "" {
return errMsg
}
+ if strings.Contains(errMsg, errConflictingEndpointFingerprints.Error()) {
+ return errConflictingEndpointFingerprints.Error()
+ }
lower := strings.ToLower(errMsg)
@@ -209,17 +214,17 @@ func NewClusterClientWithContext(ctx context.Context, name string, config Client
// getEndpointFingerprint returns the TLS fingerprint to use for a specific endpoint.
// It prefers the per-endpoint fingerprint (TOFU) over the base config fingerprint.
-func (cc *ClusterClient) getEndpointFingerprint(endpoint string) string {
+func (cc *ClusterClient) getEndpointFingerprint(endpoint string) (string, error) {
cc.mu.RLock()
defer cc.mu.RUnlock()
return cc.getEndpointFingerprintLocked(endpoint)
}
-func (cc *ClusterClient) getEndpointFingerprintLocked(endpoint string) string {
- if fp, ok := cc.knownEndpointFingerprintLocked(endpoint); ok {
- return fp
+func (cc *ClusterClient) getEndpointFingerprintLocked(endpoint string) (string, error) {
+ if fp, known, err := cc.knownEndpointFingerprintLocked(endpoint); known || err != nil {
+ return fp, err
}
- return cc.config.Fingerprint
+ return cc.config.Fingerprint, nil
}
func clusterEndpointKey(endpoint string) (string, bool) {
@@ -233,20 +238,34 @@ func clusterEndpointKey(endpoint string) (string, bool) {
return proxmoxEndpointKey(u.String(), false)
}
-func (cc *ClusterClient) knownEndpointFingerprintLocked(endpoint string) (string, bool) {
- if fp := cc.endpointFingerprints[endpoint]; fp != "" {
- return fp, true
- }
+func (cc *ClusterClient) knownEndpointFingerprintLocked(endpoint string) (string, bool, error) {
key, valid := clusterEndpointKey(endpoint)
- if !valid {
- return "", false
- }
+ var fingerprint string
+ known := false
for storedEndpoint, fp := range cc.endpointFingerprints {
- if storedKey, ok := clusterEndpointKey(storedEndpoint); ok && storedKey == key && fp != "" {
- return fp, true
+ if fp == "" {
+ continue
}
+ storedKey, storedValid := clusterEndpointKey(storedEndpoint)
+ if storedEndpoint != endpoint && (!valid || !storedValid || storedKey != key) {
+ continue
+ }
+ // Compare the same colon/case normalization used by the TLS verifier.
+ // Exact URL spelling must not choose a winner over another saved pin
+ // for this authority, nor may Go map order decide which leaf is trusted.
+ normalized := strings.ToLower(strings.ReplaceAll(fp, ":", ""))
+ if known && strings.ToLower(strings.ReplaceAll(fingerprint, ":", "")) != normalized {
+ return "", true, errConflictingEndpointFingerprints
+ }
+ // Keep a nonempty, malformed saved pin nonempty: returning its empty
+ // normalized form would accidentally select CA or explicit opt-out mode.
+ // Agreeing representations use a deterministic original spelling.
+ if !known || fp < fingerprint {
+ fingerprint = fp
+ }
+ known = true
}
- return "", false
+ return fingerprint, known, nil
}
// Only a declared, previously untrusted member may use the primary pin as a
@@ -258,7 +277,7 @@ func (cc *ClusterClient) canTrustMemberOnFirstUseLocked(endpoint string) bool {
if !valid || !primaryValid || key == primary || cc.config.Fingerprint == "" {
return false
}
- if _, known := cc.knownEndpointFingerprintLocked(endpoint); known {
+ if _, known, err := cc.knownEndpointFingerprintLocked(endpoint); known || err != nil {
return false
}
for _, member := range cc.endpoints {
@@ -311,7 +330,10 @@ func (cc *ClusterClient) refreshTOFUFingerprintAndRetry(ctx context.Context, end
captured := false
// A concurrent first-use capture may have established trust while the TLS
// probe was in flight. Use that winner's pin, not our later certificate.
- if existing, known := cc.knownEndpointFingerprintLocked(endpoint); known {
+ if existing, known, trustErr := cc.knownEndpointFingerprintLocked(endpoint); trustErr != nil {
+ cc.mu.Unlock()
+ return nil, trustErr, false
+ } else if known {
newFingerprint = existing
} else {
if !cc.canTrustMemberOnFirstUseLocked(endpoint) {
@@ -352,6 +374,11 @@ func (cc *ClusterClient) refreshTOFUFingerprintAndRetry(ctx context.Context, end
// member can establish a pin; a saved/primary pin is never replaced.
// The returned client is a disposable probe, not an accepted polling session.
func (cc *ClusterClient) probeEndpoint(ctx context.Context, cfg ClientConfig) (*Client, []Node, error) {
+ fingerprint, err := cc.getEndpointFingerprint(cfg.Host)
+ if err != nil {
+ return nil, nil, err
+ }
+ cfg.Fingerprint = fingerprint
client, err := NewClientWithContext(ctx, cfg)
var nodes []Node
if err == nil {
@@ -370,6 +397,17 @@ func (cc *ClusterClient) probeEndpoint(ctx context.Context, cfg ClientConfig) (*
return client, nodes, err
}
+// Resolve saved trust again before constructing the full polling session.
+// Never turn a resolution failure into an empty pin (CA or opt-out mode).
+func (cc *ClusterClient) newEndpointClient(ctx context.Context, cfg ClientConfig) (*Client, error) {
+ fingerprint, err := cc.getEndpointFingerprint(cfg.Host)
+ if err != nil {
+ return nil, err
+ }
+ cfg.Fingerprint = fingerprint
+ return NewClientWithContext(ctx, cfg)
+}
+
// initialHealthCheck performs a quick parallel health check on all endpoints
func (cc *ClusterClient) initialHealthCheck(ctx context.Context) {
// Skip initial health check if there's only one endpoint
@@ -394,7 +432,6 @@ func (cc *ClusterClient) initialHealthCheck(ctx context.Context) {
// Try a quick connection test with slightly longer timeout for initial check
cfg := cc.config
cfg.Host = ep
- cfg.Fingerprint = cc.getEndpointFingerprint(ep)
cfg.Timeout = 5 * time.Second
testClient, _, err := cc.probeEndpoint(ctx, cfg)
@@ -408,8 +445,7 @@ func (cc *ClusterClient) initialHealthCheck(ctx context.Context) {
// Node is healthy - create a proper client with full timeout for actual use
fullCfg := cc.config
fullCfg.Host = ep
- fullCfg.Fingerprint = cc.getEndpointFingerprint(ep)
- fullClient, clientErr := NewClientWithContext(ctx, fullCfg)
+ fullClient, clientErr := cc.newEndpointClient(ctx, fullCfg)
cc.mu.Lock()
if clientErr != nil {
@@ -662,7 +698,6 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)
// Create new client with shorter timeout for initial test
cfg := cc.config
cfg.Host = selectedEndpoint
- cfg.Fingerprint = cc.getEndpointFingerprintLocked(selectedEndpoint)
// First try with a short timeout to quickly detect offline nodes
testCfg := cfg
@@ -721,7 +756,14 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)
}
// Use the first-use winner's pin for the full polling session too.
- cfg.Fingerprint = cc.getEndpointFingerprintLocked(selectedEndpoint)
+ fingerprint, trustErr := cc.getEndpointFingerprintLocked(selectedEndpoint)
+ if trustErr != nil {
+ cc.nodeHealth[selectedEndpoint] = false
+ cc.lastError[selectedEndpoint] = sanitizeEndpointError(trustErr.Error())
+ cc.lastHealthCheck[selectedEndpoint] = time.Now()
+ return nil, trustErr
+ }
+ cfg.Fingerprint = fingerprint
// Create the actual client with full timeout
newClient, err := NewClientWithContext(ctx, cfg)
if err != nil {
@@ -858,7 +900,6 @@ func (cc *ClusterClient) recoverUnhealthyNodes(ctx context.Context) {
// typically takes ~3 seconds on local networks
cfg := cc.config
cfg.Host = ep
- cfg.Fingerprint = cc.getEndpointFingerprint(ep)
cfg.Timeout = 5 * time.Second
testClient, _, err := cc.probeEndpoint(ctx, cfg)
@@ -874,8 +915,7 @@ func (cc *ClusterClient) recoverUnhealthyNodes(ctx context.Context) {
if err == nil {
// Store the client with original timeout
cfg.Timeout = cc.config.Timeout
- cfg.Fingerprint = cc.getEndpointFingerprint(ep)
- fullClient, clientErr := NewClientWithContext(ctx, cfg)
+ fullClient, clientErr := cc.newEndpointClient(ctx, cfg)
if clientErr != nil {
// A short probe is not a usable polling session. Password
// authentication may fail when constructing the actual client;
diff --git a/pkg/proxmox/cluster_client_api_test.go b/pkg/proxmox/cluster_client_api_test.go
index b460d77f76..bcc26019ef 100644
--- a/pkg/proxmox/cluster_client_api_test.go
+++ b/pkg/proxmox/cluster_client_api_test.go
@@ -661,14 +661,14 @@ func TestGuestAgentIPv4MappedTrustScope(t *testing.T) {
if !okA || !okB || a == b {
t.Error("admission equivalence broadened the existing TLS trust identity")
}
- if _, known := cc.knownEndpointFingerprintLocked(pair[1]); known || cc.getEndpointFingerprint(pair[1]) != "primary-pin" {
+ if _, known, trustErr := cc.knownEndpointFingerprintLocked(pair[1]); trustErr != nil || known || checkedClusterFingerprint(t, cc, pair[1]) != "primary-pin" {
t.Error("coordination shared another configured authority's saved pin")
}
if !cc.canTrustMemberOnFirstUseLocked(pair[1]) {
t.Error("unchanged declared-member first-use policy lost its distinct origin")
}
cc.endpointFingerprints[pair[1]] = "other-saved-pin"
- if cc.getEndpointFingerprint(pair[0]) != "saved-pin" || cc.getEndpointFingerprint(pair[1]) != "other-saved-pin" || cc.canTrustMemberOnFirstUseLocked(pair[1]) {
+ if checkedClusterFingerprint(t, cc, pair[0]) != "saved-pin" || checkedClusterFingerprint(t, cc, pair[1]) != "other-saved-pin" || cc.canTrustMemberOnFirstUseLocked(pair[1]) {
t.Error("distinct established pins or no-replacement policy changed")
}
}
@@ -742,7 +742,7 @@ func TestClusterClientFirstUseCaptureCancellation(t *testing.T) {
if client != nil {
defer client.httpClient.CloseIdleConnections()
}
- if err != nil || !retried || client == nil || cc.getEndpointFingerprint(f.server.URL) != clusterTrustPin(f.active.Load()) || f.requests.Load() != 1 {
+ if err != nil || !retried || client == nil || checkedClusterFingerprint(t, cc, f.server.URL) != clusterTrustPin(f.active.Load()) || f.requests.Load() != 1 {
t.Errorf("ordinary first use after cancelled probe failed: retried=%t requests=%d err=%v", retried, f.requests.Load(), err)
}
})
@@ -815,7 +815,7 @@ func TestClusterNodeProbeRequiresSuccess(t *testing.T) {
if f.logins.Load() != f.loginAttempts() || f.nodes.Load() != wantNodes {
t.Errorf("failed probe was retried/advanced: logins=%d want=%d nodes=%d want=%d", f.logins.Load(), f.loginAttempts(), f.nodes.Load(), wantNodes)
}
- if cc.getEndpointFingerprint(f.server.URL) != cfg.Fingerprint || saved[f.server.URL] != cfg.Fingerprint || cc.config.VerifySSL != true {
+ if checkedClusterFingerprint(t, cc, f.server.URL) != cfg.Fingerprint || saved[f.server.URL] != cfg.Fingerprint || cc.config.VerifySSL != true {
t.Error("failed probe changed saved trust")
}
// A distinct later recovery uses this fixture's normal accepted reply.
@@ -911,3 +911,83 @@ func TestClusterNodeProbeRateLimitKeepsOrdinaryRead(t *testing.T) {
t.Fatalf("temporary probe rate limit blocked ordinary read: %+v err=%v calls=%d", nodes, err, calls.Load())
}
}
+
+// Existing non-conflicting trust controls explicitly require resolution to
+// succeed. A resolution failure must never fall back to an unpinned client.
+func checkedClusterFingerprint(t *testing.T, cc *ClusterClient, endpoint string) string {
+ t.Helper()
+ fingerprint, err := cc.getEndpointFingerprint(endpoint)
+ if err != nil {
+ t.Fatalf("unexpected saved-trust ambiguity: %v", err)
+ }
+ return fingerprint
+}
+
+func TestClusterSavedPinResolutionRejectsConflicts(t *testing.T) {
+ pairs := [][2]string{
+ {"https://MEMBER.example.invalid:0443/tenant/", "https://member.example.invalid/tenant"},
+ {"https://[2001:db8:0:0::1]:8006/tenant/", "https://[2001:db8::1]:08006/tenant"},
+ {"member.example.invalid:8006/tenant/./", "https://member.example.invalid:8006/tenant"},
+ }
+ for _, pair := range pairs {
+ cc := NewClusterClient("resolution", ClientConfig{Host: "https://primary.example.invalid", Fingerprint: "base-pin"}, nil, map[string]string{pair[0]: "saved-pin", pair[1]: "other-pin"})
+ for _, endpoint := range pair {
+ fingerprint, err := cc.getEndpointFingerprint(endpoint)
+ if fingerprint != "" || !errors.Is(err, errConflictingEndpointFingerprints) {
+ t.Errorf("exact spelling selected contradictory trust: pin=%q err=%v", fingerprint, err)
+ }
+ cc.mu.RLock()
+ _, known, trustErr := cc.knownEndpointFingerprintLocked(endpoint)
+ mayCapture := cc.canTrustMemberOnFirstUseLocked(endpoint)
+ cc.mu.RUnlock()
+ if !known || !errors.Is(trustErr, errConflictingEndpointFingerprints) || mayCapture {
+ t.Error("conflicting saved trust became unknown first-use trust")
+ }
+ }
+ }
+ // Invalid nonempty pin presentation cannot turn into unpinned CA/opt-out
+ // admission, even when every saved spelling agrees after normalization.
+ for _, pin := range []string{":", "::", " ", "not-a-pin"} {
+ cc := NewClusterClient("invalid-pin", ClientConfig{Host: "https://primary.example.invalid", Fingerprint: "base-pin", VerifySSL: false}, nil, map[string]string{"https://member.example.invalid:443/": pin, "https://MEMBER.example.invalid": pin})
+ got, err := cc.getEndpointFingerprint("https://member.example.invalid")
+ if err != nil || got != pin || got == "" {
+ t.Errorf("invalid saved pin became absent trust: %q %v", got, err)
+ }
+ }
+}
+
+func TestClusterFirstUseCaptureDoesNotReconcileConflictingPins(t *testing.T) {
+ f := newClusterTrustFixture(t)
+ cc := NewClusterClient("capture-conflict", clusterTrustConfig("https://primary.capture.invalid", clusterTrustPin(clusterTrustCertificate(t))), []string{f.server.URL}, nil)
+ lastErr := clusterTrustMismatch(t, f, cc.config.Fingerprint)
+ f.capture.Store(true)
+ done := make(chan error, 1)
+ go func() {
+ client, err, retried := cc.refreshTOFUFingerprintAndRetry(context.Background(), f.server.URL, time.Second, lastErr)
+ if client != nil {
+ client.httpClient.CloseIdleConnections()
+ err = fmt.Errorf("conflicting capture constructed an authenticated client")
+ }
+ if retried {
+ err = fmt.Errorf("conflicting capture attempted a pinned retry")
+ }
+ done <- err
+ }()
+ select {
+ case <-f.entered:
+ case <-time.After(5 * time.Second):
+ close(f.resume)
+ t.Fatal("capture did not reach fixture handshake")
+ }
+ cc.mu.Lock()
+ cc.endpointFingerprints[f.server.URL] = clusterTrustPin(f.active.Load())
+ cc.endpointFingerprints[f.server.URL+"/./"] = strings.Repeat("0", 64)
+ cc.mu.Unlock()
+ close(f.resume)
+ if err := <-done; !errors.Is(err, errConflictingEndpointFingerprints) {
+ t.Errorf("completed capture chose a conflicting pin: %v", err)
+ }
+ if f.requests.Load() != 0 || len(cc.endpointFingerprints) != 2 {
+ t.Error("capture authenticated or reconciled contradictory saved trust")
+ }
+}
diff --git a/pkg/proxmox/cluster_client_cancellation_test.go b/pkg/proxmox/cluster_client_cancellation_test.go
index c01b2ca999..658b3de256 100644
--- a/pkg/proxmox/cluster_client_cancellation_test.go
+++ b/pkg/proxmox/cluster_client_cancellation_test.go
@@ -139,7 +139,7 @@ func testClusterSessionConstructionHonoursCallerBudget(t *testing.T) {
case <-time.After(time.Second):
t.Error("ended caller left its fixture request active")
}
- if len(cc.clients) != 0 || cc.nodeHealth[server.URL] != (path == "selection") || cc.lastError[server.URL] != "previous fixture outage" || cc.getEndpointFingerprint(server.URL) != cfg.Fingerprint {
+ if len(cc.clients) != 0 || cc.nodeHealth[server.URL] != (path == "selection") || cc.lastError[server.URL] != "previous fixture outage" || checkedClusterFingerprint(t, cc, server.URL) != cfg.Fingerprint {
t.Errorf("cancelled construction published a session/recovery or changed prior trust/error: clients=%d healthy=%t error=%q", len(cc.clients), cc.nodeHealth[server.URL], cc.lastError[server.URL])
}
wantLogins, wantReads := int32(1), int32(0)
diff --git a/pkg/proxmox/cluster_client_endpoint_ownership_test.go b/pkg/proxmox/cluster_client_endpoint_ownership_test.go
index 177f183eb9..1e748ee227 100644
--- a/pkg/proxmox/cluster_client_endpoint_ownership_test.go
+++ b/pkg/proxmox/cluster_client_endpoint_ownership_test.go
@@ -51,10 +51,10 @@ func testClusterClientEndpointOwnershipRoutingAndTrust(t *testing.T) {
cc.mu.RLock()
_, captured := cc.endpointFingerprints[other.server.URL]
cc.mu.RUnlock()
- if captured || cc.getEndpointFingerprint(declared.server.URL) != declaredPin {
+ if captured || checkedClusterFingerprint(t, cc, declared.server.URL) != declaredPin {
t.Error("caller-owned endpoint edit changed the client's trust state")
}
- t.Logf("observed injected endpoint authenticated requests=%d; original pin unchanged=%t", other.requests.Load(), cc.getEndpointFingerprint(declared.server.URL) == declaredPin)
+ t.Logf("observed injected endpoint authenticated requests=%d; original pin unchanged=%t", other.requests.Load(), checkedClusterFingerprint(t, cc, declared.server.URL) == declaredPin)
}
func testClusterClientEndpointOwnershipGuestAdmission(t *testing.T) {
diff --git a/pkg/proxmox/cluster_client_fingerprint_trust_test.go b/pkg/proxmox/cluster_client_fingerprint_trust_test.go
index c9775de280..1d80bb96a3 100644
--- a/pkg/proxmox/cluster_client_fingerprint_trust_test.go
+++ b/pkg/proxmox/cluster_client_fingerprint_trust_test.go
@@ -131,7 +131,10 @@ func testClusterClientFingerprintTrust(t *testing.T) {
cc.recoverUnhealthyNodes(context.Background())
}
cc.mu.RLock()
- stored := cc.getEndpointFingerprintLocked(f.server.URL)
+ stored, trustErr := cc.getEndpointFingerprintLocked(f.server.URL)
+ if trustErr != nil {
+ t.Fatal(trustErr)
+ }
healthy, diagnostic := cc.nodeHealth[f.server.URL], cc.lastError[f.server.URL]
cc.mu.RUnlock()
if f.requests.Load() != 0 || stored != pin || healthy || !strings.Contains(diagnostic, "independently verify") {
@@ -146,7 +149,7 @@ func testClusterClientFingerprintTrust(t *testing.T) {
cc.mu.Unlock()
before := f.requests.Load()
cc.recoverUnhealthyNodes(context.Background())
- if !cc.GetHealthStatus()[f.server.URL] || f.requests.Load() != before+1 || cc.getEndpointFingerprint(f.server.URL) != pin {
+ if !cc.GetHealthStatus()[f.server.URL] || f.requests.Load() != before+1 || checkedClusterFingerprint(t, cc, f.server.URL) != pin {
t.Error("restored original certificate did not resume ordinary monitoring under the same pin")
}
t.Logf("changed leaf: no authenticated requests; original leaf: one authenticated recovery, retained %s pin", role)
@@ -218,7 +221,7 @@ func testClusterClientFingerprintTrust(t *testing.T) {
if err := <-done; err != nil {
t.Errorf("retry did not use concurrently established trust: %v", err)
}
- if cc.getEndpointFingerprint(f.server.URL) != winnerPin || f.requests.Load() != 1 {
+ if checkedClusterFingerprint(t, cc, f.server.URL) != winnerPin || f.requests.Load() != 1 {
t.Error("older first-use capture replaced the winner or failed its authenticated acceptance")
}
})
@@ -234,7 +237,7 @@ func testClusterClientFingerprintTrust(t *testing.T) {
if client != nil {
defer client.httpClient.CloseIdleConnections()
}
- if err != nil || !retried || client == nil || f.requests.Load() != 1 || cc.getEndpointFingerprint(f.server.URL) != clusterTrustPin(f.active.Load()) {
+ if err != nil || !retried || client == nil || f.requests.Load() != 1 || checkedClusterFingerprint(t, cc, f.server.URL) != clusterTrustPin(f.active.Load()) {
t.Fatalf("declared new member cannot establish first-use trust: %v", err)
}
if len(input) != 0 {
@@ -260,11 +263,11 @@ func testClusterClientFingerprintTrust(t *testing.T) {
t.Run("equivalent-known-endpoint", func(t *testing.T) {
cc := NewClusterClient("trust", clusterTrustConfig("https://primary.trust.invalid", "primary-pin"), nil,
map[string]string{"https://MEMBER.trust.invalid:443/tenant/": "member-pin"})
- if cc.getEndpointFingerprint("https://member.trust.invalid/tenant") != "member-pin" {
+ if checkedClusterFingerprint(t, cc, "https://member.trust.invalid/tenant") != "member-pin" {
t.Error("equivalent URL spelling forgot established member trust")
}
for _, endpoint := range []string{"http://member.trust.invalid/tenant", "https://member.trust.invalid:8006/tenant", "https://member.trust.invalid/Tenant"} {
- if cc.getEndpointFingerprint(endpoint) != "primary-pin" {
+ if checkedClusterFingerprint(t, cc, endpoint) != "primary-pin" {
t.Errorf("independent authority/path inherited another endpoint's pin: %s", endpoint)
}
}
diff --git a/pkg/proxmox/cluster_client_first_use_session_test.go b/pkg/proxmox/cluster_client_first_use_session_test.go
index 9d08d1e32a..dc2307478e 100644
--- a/pkg/proxmox/cluster_client_first_use_session_test.go
+++ b/pkg/proxmox/cluster_client_first_use_session_test.go
@@ -156,10 +156,10 @@ func testClusterFirstUseSessionAdmission(t *testing.T) {
client := cc.clients[f.server.URL]
healthy := cc.nodeHealth[f.server.URL]
cc.mu.RUnlock()
- if !healthy || client == nil || cc.getEndpointFingerprint(f.server.URL) != clusterTrustPin(f.cert.Load()) {
+ if !healthy || client == nil || checkedClusterFingerprint(t, cc, f.server.URL) != clusterTrustPin(f.cert.Load()) {
t.Fatalf("declared new member has no usable pinned session: healthy=%t client=%t logins=%d nodes=%d", healthy, client != nil, f.logins.Load(), f.nodes.Load())
}
- if len(saved) != 0 || cc.config.VerifySSL != true || cc.config.Fingerprint == cc.getEndpointFingerprint(f.server.URL) {
+ if len(saved) != 0 || cc.config.VerifySSL != true || cc.config.Fingerprint == checkedClusterFingerprint(t, cc, f.server.URL) {
t.Fatal("first use changed saved trust or primary policy")
}
if client.config.Timeout != cfg.Timeout {
@@ -215,7 +215,7 @@ func TestClusterFirstUseSessionRefusalKeepsTrust(t *testing.T) {
if cc.GetHealthStatus()[f.server.URL] || cc.clients[f.server.URL] != nil || f.logins.Load() != 1 || f.nodes.Load() != 0 {
t.Fatalf("refused first-use session became healthy or replayed: login=%d nodes=%d", f.logins.Load(), f.nodes.Load())
}
- pin := cc.getEndpointFingerprint(f.server.URL)
+ pin := checkedClusterFingerprint(t, cc, f.server.URL)
if pin != clusterTrustPin(f.cert.Load()) || cc.lastError[f.server.URL] == "" {
t.Fatal("refusal lost its fixed pin or diagnostic")
}
@@ -224,7 +224,7 @@ func TestClusterFirstUseSessionRefusalKeepsTrust(t *testing.T) {
delete(cc.lastHealthCheck, f.server.URL)
before := f.handshakes.Load()
cc.recoverUnhealthyNodes(context.Background())
- if !cc.GetHealthStatus()[f.server.URL] || cc.clients[f.server.URL] == nil || cc.getEndpointFingerprint(f.server.URL) != pin || f.handshakes.Load() != before+2 || f.logins.Load() != 3 || f.nodes.Load() != 1 {
+ if !cc.GetHealthStatus()[f.server.URL] || cc.clients[f.server.URL] == nil || checkedClusterFingerprint(t, cc, f.server.URL) != pin || f.handshakes.Load() != before+2 || f.logins.Load() != 3 || f.nodes.Load() != 1 {
t.Fatal("separate ordinary recovery failed, recaptured trust or replayed the refusal")
}
})
@@ -257,13 +257,13 @@ func TestClusterPasswordEstablishedPinsAreNotFirstUse(t *testing.T) {
case "selection":
_, _ = cc.GetNodes(context.Background())
}
- if f.logins.Load() != 0 || f.nodes.Load() != 0 || f.handshakes.Load() != 1 || cc.getEndpointFingerprint(f.server.URL) != pin || cc.GetHealthStatus()[f.server.URL] {
+ if f.logins.Load() != 0 || f.nodes.Load() != 0 || f.handshakes.Load() != 1 || checkedClusterFingerprint(t, cc, f.server.URL) != pin || cc.GetHealthStatus()[f.server.URL] {
t.Fatal("known leaf change captured new trust or sent a password")
}
f.cert.Store(trusted)
delete(cc.lastHealthCheck, f.server.URL)
cc.recoverUnhealthyNodes(context.Background())
- if !cc.GetHealthStatus()[f.server.URL] || cc.getEndpointFingerprint(f.server.URL) != pin || f.logins.Load() != 2 || f.nodes.Load() != 1 {
+ if !cc.GetHealthStatus()[f.server.URL] || checkedClusterFingerprint(t, cc, f.server.URL) != pin || f.logins.Load() != 2 || f.nodes.Load() != 1 {
t.Fatal("re-presenting trusted leaf did not recover")
}
})
diff --git a/pkg/proxmox/cluster_client_more_test.go b/pkg/proxmox/cluster_client_more_test.go
index 93a95dc9ba..d4fa4ec979 100644
--- a/pkg/proxmox/cluster_client_more_test.go
+++ b/pkg/proxmox/cluster_client_more_test.go
@@ -16,10 +16,10 @@ func TestClusterClientEndpointFingerprint(t *testing.T) {
},
}
- if got := cc.getEndpointFingerprint("node1"); got != "node-fp" {
+ if got := checkedClusterFingerprint(t, cc, "node1"); got != "node-fp" {
t.Fatalf("expected node fingerprint, got %s", got)
}
- if got := cc.getEndpointFingerprint("node2"); got != "base" {
+ if got := checkedClusterFingerprint(t, cc, "node2"); got != "base" {
t.Fatalf("expected base fingerprint, got %s", got)
}
}
diff --git a/pkg/proxmox/cluster_client_recovery_session_test.go b/pkg/proxmox/cluster_client_recovery_session_test.go
index b8d578c1fc..7100cea178 100644
--- a/pkg/proxmox/cluster_client_recovery_session_test.go
+++ b/pkg/proxmox/cluster_client_recovery_session_test.go
@@ -96,7 +96,7 @@ func testClusterRecoveryRequiresUsableSession(t *testing.T) {
if refusal == "form-refused" {
wantLogins = 3
}
- if logins.Load() != wantLogins || nodeReads.Load() != 1 || cc.getEndpointFingerprint(server.URL) != cfg.Fingerprint {
+ if logins.Load() != wantLogins || nodeReads.Load() != 1 || checkedClusterFingerprint(t, cc, server.URL) != cfg.Fingerprint {
t.Fatalf("refusal replayed, changed trust or lost its probe: logins=%d nodes=%d", logins.Load(), nodeReads.Load())
}
diff --git a/pkg/proxmox/cluster_node_inventory_test.go b/pkg/proxmox/cluster_node_inventory_test.go
index 3329d73f05..febb63a11b 100644
--- a/pkg/proxmox/cluster_node_inventory_test.go
+++ b/pkg/proxmox/cluster_node_inventory_test.go
@@ -105,7 +105,7 @@ func TestClusterNodeInventoryRequiresCompleteResponse(t *testing.T) {
if f.nodes.Load() != 1 || f.logins.Load() != f.loginAttempts() {
t.Fatalf("invalid probe replayed or advanced: nodes=%d logins=%d", f.nodes.Load(), f.logins.Load())
}
- if cc.getEndpointFingerprint(f.server.URL) != cfg.Fingerprint || saved[f.server.URL] != cfg.Fingerprint || !cc.config.VerifySSL {
+ if checkedClusterFingerprint(t, cc, f.server.URL) != cfg.Fingerprint || saved[f.server.URL] != cfg.Fingerprint || !cc.config.VerifySSL {
t.Fatal("invalid inventory changed saved trust")
}
// Advance only this synthetic endpoint's eligibility for a distinct accepted
diff --git a/pkg/proxmox/cluster_pin_conflict_test.go b/pkg/proxmox/cluster_pin_conflict_test.go
new file mode 100644
index 0000000000..52bbc79398
--- /dev/null
+++ b/pkg/proxmox/cluster_pin_conflict_test.go
@@ -0,0 +1,185 @@
+package proxmox
+
+import (
+ "context"
+ "crypto/tls"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// Real TLS sockets with fixture-only credentials. Conflicting pins must be
+// refused before a dial, not merely when one of the selected leaves mismatches.
+type conflictingPinFixture struct {
+ server *httptest.Server
+ handshakes, logins, reads atomic.Int32
+ pin string
+}
+
+func newConflictingPinFixture(t *testing.T, mode string) *conflictingPinFixture {
+ t.Helper()
+ cert := clusterTrustCertificate(t)
+ f := &conflictingPinFixture{pin: clusterTrustPin(cert)}
+ f.server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api2/json/access/ticket":
+ f.logins.Add(1)
+ if mode == "password-form" && r.Header.Get("Content-Type") == "application/json" {
+ w.WriteHeader(http.StatusUnsupportedMediaType)
+ fmt.Fprint(w, `{"message":"fixture requires form encoding"}`)
+ return
+ }
+ fmt.Fprint(w, `{"data":{"ticket":"fixture-ticket","CSRFPreventionToken":"fixture-csrf"}}`)
+ case "/api2/json/nodes":
+ f.reads.Add(1)
+ if mode == "token" {
+ if r.Header.Get("Authorization") != "PVEAPIToken=fixture@pve!pulse=fixture" {
+ t.Error("lost token fixture authentication")
+ }
+ } else if r.Header.Get("Cookie") != "PVEAuthCookie=fixture-ticket" {
+ t.Error("lost password fixture authentication")
+ }
+ fmt.Fprint(w, `{"data":[{"node":"fixture","status":"online"}]}`)
+ default:
+ t.Errorf("left ordinary authentication/nodes path: %s", r.URL.Path)
+ http.NotFound(w, r)
+ }
+ }))
+ f.server.Config.ErrorLog = log.New(io.Discard, "", 0)
+ f.server.TLS = &tls.Config{GetConfigForClient: func(*tls.ClientHelloInfo) (*tls.Config, error) {
+ f.handshakes.Add(1)
+ return &tls.Config{MinVersion: tls.VersionTLS12, Certificates: []tls.Certificate{*cert}}, nil
+ }}
+ f.server.StartTLS()
+ t.Cleanup(f.server.Close)
+ return f
+}
+
+func conflictPinConfig(host, pin, mode string, verify bool) ClientConfig {
+ cfg := ClientConfig{Host: host, Fingerprint: pin, VerifySSL: verify, Timeout: 2 * time.Second}
+ if mode == "token" {
+ cfg.TokenName = "fixture@pve!pulse"
+ cfg.TokenValue = "fixture"
+ } else {
+ cfg.User = "fixture@pam"
+ cfg.Password = "fixture-password"
+ }
+ return cfg
+}
+
+func TestClusterConflictingSavedPinsNeverAuthenticate(t *testing.T) {
+ const diagnostic = "TLS trust conflict - equivalent endpoint URLs have different saved fingerprints; independently verify and reconcile saved trust"
+ for _, phase := range []string{"startup", "recovery", "selection"} {
+ for _, mode := range []string{"token", "password-json", "password-form"} {
+ for _, spelling := range []string{"exact-valid", "exact-other", "normalized-only"} {
+ for _, verify := range []bool{true, false} {
+ t.Run(fmt.Sprintf("%s/%s/%s/verify=%t", phase, mode, spelling, verify), func(t *testing.T) {
+ bad, safe := newConflictingPinFixture(t, mode), newConflictingPinFixture(t, mode)
+ otherPin := strings.Repeat("0", 64)
+ alias := bad.server.URL + "/./"
+ pins := map[string]string{bad.server.URL: bad.pin, alias: otherPin, safe.server.URL: safe.pin}
+ endpoint := bad.server.URL
+ if spelling == "exact-other" {
+ endpoint = alias
+ }
+ if spelling == "normalized-only" {
+ endpoint = bad.server.URL + "/"
+ }
+ key, _ := clusterEndpointKey(endpoint)
+ if aliasKey, ok := clusterEndpointKey(alias); !ok || key != aliasKey {
+ t.Fatal("fixture URLs are not equivalent under existing TLS identity")
+ }
+ saved := make(map[string]string, len(pins))
+ for k, v := range pins {
+ saved[k] = v
+ }
+ endpoints := []string{endpoint}
+ if phase == "startup" {
+ endpoints = append(endpoints, safe.server.URL)
+ }
+ cc := NewClusterClient("pin-conflict", conflictPinConfig(safe.server.URL, safe.pin, mode, verify), endpoints, pins)
+ if phase == "recovery" {
+ cc.mu.Lock()
+ cc.nodeHealth[endpoint] = false
+ cc.mu.Unlock()
+ cc.recoverUnhealthyNodes(context.Background())
+ }
+ if phase != "recovery" {
+ _, err := cc.GetNodes(context.Background())
+ if phase == "selection" && (err == nil || !strings.Contains(err.Error(), diagnostic)) {
+ t.Errorf("selection did not refuse ambiguous trust: %v", err)
+ }
+ if phase == "startup" && (err != nil || safe.reads.Load() == 0) {
+ t.Errorf("independent trusted endpoint lost ordinary monitoring: %v", err)
+ }
+ }
+ cc.mu.RLock()
+ healthy, reason, client := cc.nodeHealth[endpoint], cc.lastError[endpoint], cc.clients[endpoint]
+ unchanged := reflect.DeepEqual(cc.endpointFingerprints, saved)
+ cc.mu.RUnlock()
+ if healthy || reason != diagnostic || client != nil {
+ t.Errorf("conflicting trust became usable: healthy=%t reason=%q client=%t", healthy, reason, client != nil)
+ }
+ if bad.handshakes.Load() != 0 || bad.logins.Load() != 0 || bad.reads.Load() != 0 {
+ t.Errorf("conflicting saved trust reached the provider: TLS=%d login=%d reads=%d", bad.handshakes.Load(), bad.logins.Load(), bad.reads.Load())
+ }
+ if !unchanged || !reflect.DeepEqual(pins, saved) {
+ t.Error("conflicting trust was silently reconciled or caller pins mutated")
+ }
+ // A normal configuration reload can use independently reconciled saved
+ // trust. Case/colon presentation does not create a new certificate pin.
+ formatted := strings.ToUpper(strings.Join(splitPinPairs(bad.pin), ":"))
+ corrected := map[string]string{bad.server.URL: bad.pin, alias: formatted}
+ recovered := NewClusterClient("pin-reconciled", conflictPinConfig(safe.server.URL, safe.pin, mode, verify), []string{endpoint}, corrected)
+ nodes, err := recovered.GetNodes(context.Background())
+ if err != nil || len(nodes) != 1 || !recovered.GetHealthStatus()[endpoint] || bad.reads.Load() == 0 {
+ t.Errorf("agreed saved pins did not resume ordinary monitoring: %v", err)
+ }
+ if !reflect.DeepEqual(corrected, map[string]string{bad.server.URL: bad.pin, alias: formatted}) {
+ t.Error("reconciled trust input changed")
+ }
+ for _, cluster := range []*ClusterClient{cc, recovered} {
+ for _, client := range cluster.clients {
+ client.httpClient.CloseIdleConnections()
+ }
+ }
+ })
+ }
+ }
+ }
+ }
+}
+
+func splitPinPairs(pin string) []string {
+ pairs := make([]string, 0, len(pin)/2)
+ for i := 0; i < len(pin); i += 2 {
+ pairs = append(pairs, pin[i:i+2])
+ }
+ return pairs
+}
+
+func TestClusterSavedPinScopesStayDistinct(t *testing.T) {
+ const endpoint = "https://member.scope.invalid:8006/tenant"
+ const pin = "saved-pin"
+ for _, other := range []string{"http://member.scope.invalid:8006/tenant", "https://member.scope.invalid:8007/tenant", "https://other.scope.invalid:8006/tenant", "https://member.scope.invalid:8006/Tenant", "https://member.scope.invalid:8006/other"} {
+ cc := NewClusterClient("scope", ClientConfig{Host: endpoint, Fingerprint: "primary-pin"}, nil, map[string]string{endpoint: pin, other: "independent-pin"})
+ fingerprint, err := cc.getEndpointFingerprint(endpoint)
+ if err != nil || fingerprint != pin {
+ t.Errorf("distinct endpoint created a saved-trust conflict: %q %v", fingerprint, err)
+ }
+ // Exercise the pre-existing scope predicate without network. Neither a
+ // distinct origin nor another base path may create a conflict for this URL.
+ a, okA := clusterEndpointKey(endpoint)
+ b, okB := clusterEndpointKey(other)
+ if !okA || !okB || a == b {
+ t.Error("independent TLS authority/path was collapsed")
+ }
+ }
+}