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
Stop shared-token same-hostname agents collapsing identities
rcourtmana49a4e65d154
diff --git a/internal/api/issue1753_agent_report_auth_test.go b/internal/api/issue1753_agent_report_auth_test.gonew file mode 100644index 0000000000..7c2d5964a7--- /dev/null+++ b/internal/api/issue1753_agent_report_auth_test.go@@ -0,0 +1,236 @@+package api++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/api/agentbinding"+ "github.com/rcourtman/pulse-go-rewrite/internal/api/agenttokens"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"+)++// Issue #1753 (2026-09-01 comment): two standalone Proxmox sites reuse the+// short node name pve01. After upgrading to v6.4.2 and reinstalling both+// Unified Agents, the reporter sees "Unauthorized access attempt" server log+// lines for /api/agents/agent/report. This test models that estate end to end+// through the real router (global auth middleware, RequireAuth, RequireScope,+// ApplyHostReport) and fails if either agent's report path ever loses+// authentication, including across the uninstall/reinstall cycle the reporter+// performed.++func issue1753InstallTokenRecord(t *testing.T, raw, site string) config.APITokenRecord {+ t.Helper()+ record, err := config.NewAPITokenRecord(raw, "Proxmox agent install ("+site+")", agenttokens.ProxmoxScopes(false))+ if err != nil {+ t.Fatalf("NewAPITokenRecord: %v", err)+ }+ record.Metadata = map[string]string{+ "install_type": "pve",+ "issued_via": agentbinding.IssuedViaConfig,+ agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindMonitoringCollector,+ }+ return *record+}++func issue1753Report(agentID, hostname, machineID, reportIP string) agentshost.Report {+ return agentshost.Report{+ Agent: agentshost.AgentInfo{+ ID: agentID,+ Version: "6.4.2",+ Type: "unified",+ IntervalSeconds: 30,+ Hostname: hostname,+ },+ Host: agentshost.HostInfo{+ Hostname: hostname,+ MachineID: machineID,+ Platform: "proxmox",+ OSName: "debian",+ ReportIP: reportIP,+ },+ Timestamp: time.Now().UTC(),+ }+}++func issue1753PostReport(t *testing.T, router *Router, token string, report agentshost.Report) (int, map[string]any) {+ t.Helper()+ body, err := json.Marshal(report)+ if err != nil {+ t.Fatalf("marshal report: %v", err)+ }+ req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/report", bytes.NewReader(body))+ req.Header.Set("X-API-Token", token)+ req.Header.Set("Content-Type", "application/json")+ rec := httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)++ var payload map[string]any+ _ = json.Unmarshal(rec.Body.Bytes(), &payload)+ return rec.Code, payload+}++func TestIssue1753TwoStandaloneSitesSameShortHostnameKeepReportAuth(t *testing.T) {+ const (+ tokenSiteA = "issue1753-site-a-token.12345678"+ tokenSiteB = "issue1753-site-b-token.87654321"+ )++ cfg := newTestConfigWithTokens(t,+ issue1753InstallTokenRecord(t, tokenSiteA, "site-a"),+ issue1753InstallTokenRecord(t, tokenSiteB, "site-b"),+ )+ monitor, err := monitoring.New(cfg)+ if err != nil {+ t.Fatalf("new monitor: %v", err)+ }+ defer monitor.Stop()+ router := NewRouter(cfg, monitor, nil, nil, func() error { return nil }, "6.4.2")++ var ackIDA, ackIDB string+ for round := 0; round < 4; round++ {+ code, payload := issue1753PostReport(t, router, tokenSiteA,+ issue1753Report("", "pve01", "machine-id-site-a", "10.1.0.10"))+ if code != http.StatusOK {+ t.Fatalf("round %d: site A report rejected with %d (%v)", round, code, payload)+ }+ ackIDA, _ = payload["agentId"].(string)++ code, payload = issue1753PostReport(t, router, tokenSiteB,+ issue1753Report("", "pve01", "machine-id-site-b", "10.2.0.10"))+ if code != http.StatusOK {+ t.Fatalf("round %d: site B report rejected with %d (%v)", round, code, payload)+ }+ ackIDB, _ = payload["agentId"].(string)+ }++ if ackIDA == "" || ackIDB == "" {+ t.Fatalf("expected both sites to receive acknowledged agent IDs, got %q and %q", ackIDA, ackIDB)+ }+ if ackIDA == ackIDB {+ t.Fatalf("both standalone sites were acknowledged with the same agent identity %q; uninstalling either agent would act on the other site's record", ackIDA)+ }++ // The reporter's cycle: site B uninstalls its agent (the uninstaller calls+ // the unregister endpoint), then reinstalls with a freshly minted token.+ uninstallBody, _ := json.Marshal(map[string]string{"agentId": ackIDB})+ req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/uninstall", bytes.NewReader(uninstallBody))+ req.Header.Set("X-API-Token", tokenSiteB)+ rec := httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("site B uninstall failed with %d: %s", rec.Code, rec.Body.String())+ }++ // Site A must keep reporting with its original token after site B's+ // uninstall: revoking site A's credential here is the cross-site failure.+ code, payload := issue1753PostReport(t, router, tokenSiteA,+ issue1753Report(ackIDA, "pve01", "machine-id-site-a", "10.1.0.10"))+ if code != http.StatusOK {+ t.Fatalf("site A report rejected with %d after site B uninstall (%v)", code, payload)+ }++ // Site B reinstalls: fresh token, same short hostname, same machine.+ const tokenSiteB2 = "issue1753-site-b-second.11112222"+ recordB2 := issue1753InstallTokenRecord(t, tokenSiteB2, "site-b-reinstall")+ config.Mu.Lock()+ cfg.APITokens = append(cfg.APITokens, recordB2)+ cfg.SortAPITokens()+ config.Mu.Unlock()++ for round := 0; round < 3; round++ {+ code, payload = issue1753PostReport(t, router, tokenSiteB2,+ issue1753Report("", "pve01", "machine-id-site-b", "10.2.0.10"))+ if code != http.StatusOK {+ t.Fatalf("round %d: reinstalled site B report rejected with %d (%v)", round, code, payload)+ }+ code, payload = issue1753PostReport(t, router, tokenSiteA,+ issue1753Report(ackIDA, "pve01", "machine-id-site-a", "10.1.0.10"))+ if code != http.StatusOK {+ t.Fatalf("round %d: site A report rejected with %d after site B reinstall (%v)", round, code, payload)+ }+ }++ // Both live tokens must still be present in the inventory: a silent+ // revocation here is what surfaces as 401 "Unauthorized access attempt".+ config.Mu.RLock()+ defer config.Mu.RUnlock()+ remaining := map[string]bool{}+ for _, record := range cfg.APITokens {+ remaining[record.Name] = true+ }+ for _, name := range []string{"Proxmox agent install (site-a)", "Proxmox agent install (site-b-reinstall)"} {+ if !remaining[name] {+ t.Fatalf("token %q was removed from the inventory (have %v)", name, remaining)+ }+ }+}++func issue1753UninstallAgent(t *testing.T, router *Router, token, agentID string) int {+ t.Helper()+ body, _ := json.Marshal(map[string]string{"agentId": agentID})+ req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/uninstall", bytes.NewReader(body))+ req.Header.Set("X-API-Token", token)+ rec := httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ return rec.Code+}++// TestIssue1753SharedInstallTokenTwoSites models the other common install+// pattern: the operator pastes one existing API token into both sites'+// install commands, so both agents authenticate with the same credential.+func TestIssue1753SharedInstallTokenTwoSites(t *testing.T) {+ const shared = "issue1753-shared-token.99990000"++ cfg := newTestConfigWithTokens(t, issue1753InstallTokenRecord(t, shared, "shared"))+ monitor, err := monitoring.New(cfg)+ if err != nil {+ t.Fatalf("new monitor: %v", err)+ }+ defer monitor.Stop()+ router := NewRouter(cfg, monitor, nil, nil, func() error { return nil }, "6.4.2")++ var ackIDA, ackIDB string+ for round := 0; round < 4; round++ {+ code, payload := issue1753PostReport(t, router, shared,+ issue1753Report("", "pve01", "machine-id-site-a", "10.1.0.10"))+ if code != http.StatusOK {+ t.Fatalf("round %d: site A report rejected with %d (%v)", round, code, payload)+ }+ ackIDA, _ = payload["agentId"].(string)++ code, payload = issue1753PostReport(t, router, shared,+ issue1753Report("", "pve01", "machine-id-site-b", "10.2.0.10"))+ if code != http.StatusOK {+ t.Fatalf("round %d: site B report rejected with %d (%v)", round, code, payload)+ }+ ackIDB, _ = payload["agentId"].(string)+ }++ if ackIDA == ackIDB {+ t.Fatalf("both sites sharing one token were acknowledged with the same agent identity %q", ackIDA)+ }++ // Site B uninstalls, then both keep going. The shared token must survive+ // the uninstall because site A still uses it.+ if code := issue1753UninstallAgent(t, router, shared, ackIDB); code != http.StatusOK {+ t.Fatalf("site B uninstall failed with %d", code)+ }+ code, payload := issue1753PostReport(t, router, shared,+ issue1753Report(ackIDA, "pve01", "machine-id-site-a", "10.1.0.10"))+ if code != http.StatusOK {+ t.Fatalf("site A report rejected with %d after shared-token uninstall (%v)", code, payload)+ }++ config.Mu.RLock()+ tokens := len(cfg.APITokens)+ config.Mu.RUnlock()+ if tokens != 1 {+ t.Fatalf("expected the shared token to survive site B's uninstall, inventory now holds %d tokens", tokens)+ }+}diff --git a/internal/config/host_continuity.go b/internal/config/host_continuity.goindex 6b6d64f805..2f9e0b3449 100644--- a/internal/config/host_continuity.go+++ b/internal/config/host_continuity.go@@ -316,6 +316,7 @@ func (s *HostContinuityStore) Match(candidates := uniqueTrimmedStrings(reportHostID, machineID, agentID)hostname = strings.TrimSpace(hostname)tokenID = strings.TrimSpace(tokenID)+ machineID = strings.TrimSpace(machineID)var best HostContinuityEntrymatched := false@@ -352,6 +353,14 @@ func (s *HostContinuityStore) Match(if tokenID != "" && (entry.TokenID == "" || entry.TokenID != tokenID) {continue}+ // Hostname+token alone must not adopt another machine's identity: two+ // standalone sites reusing one short hostname and one shared install+ // token are distinct machines, and folding them here is what collapsed+ // the reporter's estate in #1753. A recorded machine ID that disagrees+ // with the report's machine ID is proof of a different machine.+ if machineID != "" && strings.TrimSpace(entry.MachineID) != "" && !strings.EqualFold(strings.TrimSpace(entry.MachineID), machineID) {+ continue+ }if !matched || entry.LastSeen.After(best.LastSeen) {best = entrymatched = truediff --git a/internal/config/host_continuity_test.go b/internal/config/host_continuity_test.goindex 241e501682..348a07f39d 100644--- a/internal/config/host_continuity_test.go+++ b/internal/config/host_continuity_test.go@@ -79,6 +79,18 @@ func TestHostContinuityStoreRoundTripAndMatch(t *testing.T) {if _, ok := reloaded.Match("", "", "", "host-1.local", "token-2", now.Add(-time.Minute)); ok {t.Fatal("expected token mismatch not to match")}++ // #1753: hostname+token alone must not fold a different machine into this+ // entry. Two standalone sites reusing one short hostname and one shared+ // install token report distinct machine IDs.+ if _, ok := reloaded.Match("", "machine-other-site", "", "host-1.local", "token-1", now.Add(-time.Minute)); ok {+ t.Fatal("expected hostname+token match to be rejected for a conflicting machine ID")+ }+ if entry, ok := reloaded.Match("", "machine-1", "", "host-1.local", "token-1", now.Add(-time.Minute)); !ok {+ t.Fatal("expected hostname+token match to survive an agreeing machine ID")+ } else if entry.HostID != "host-1" {+ t.Fatalf("matched host ID = %q, want %q", entry.HostID, "host-1")+ }}func TestHostContinuityStoreRecentEntriesFiltersStaleState(t *testing.T) {diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.goindex 0877f4c584..faf036c2a4 100644--- a/internal/monitoring/monitor_agents.go+++ b/internal/monitoring/monitor_agents.go@@ -1346,11 +1346,51 @@ func hostTokenBindingKey(tokenID, hostname string) string {return fmt.Sprintf("%s:%s", tokenID, hostname)}-func lookupHostTokenBinding(bindings map[string]string, tokenID, hostname string) string {+// hostTokenBindingMachineSeparator splits the hostname and machine-ID parts of+// a machine-qualified binding key. The unit separator cannot appear in a+// hostname or /etc/machine-id value.+const hostTokenBindingMachineSeparator = "\x1f"++// hostTokenMachineBindingKey qualifies the token+hostname binding with the+// reporting machine's identity. Two standalone sites reusing one short+// hostname and one shared install token are distinct machines and must hold+// distinct binding slots (#1753); a report without a machine ID keeps the+// legacy token+hostname key.+func hostTokenMachineBindingKey(tokenID, hostname, machineID string) string {+ base := hostTokenBindingKey(tokenID, hostname)+ if base == "" {+ return ""+ }+ machineID = strings.TrimSpace(machineID)+ if machineID == "" {+ return base+ }+ return base + hostTokenBindingMachineSeparator + machineID+}++// splitHostTokenBindingRemainder decomposes the part of a binding key after+// "tokenID:" into its hostname and optional machine-ID components.+func splitHostTokenBindingRemainder(remainder string) (hostname, machineID string) {+ if at := strings.Index(remainder, hostTokenBindingMachineSeparator); at >= 0 {+ return strings.TrimSpace(remainder[:at]), strings.TrimSpace(remainder[at+len(hostTokenBindingMachineSeparator):])+ }+ return strings.TrimSpace(remainder), ""+}++func lookupHostTokenBinding(bindings map[string]string, tokenID, hostname, machineID string) string {if len(bindings) == 0 {return ""}+ machineID = strings.TrimSpace(machineID)+ if machineID != "" {+ if machineKey := hostTokenMachineBindingKey(tokenID, hostname, machineID); machineKey != "" {+ if boundID := strings.TrimSpace(bindings[machineKey]); boundID != "" {+ return boundID+ }+ }+ }+bindingKey := hostTokenBindingKey(tokenID, hostname)if bindingKey == "" {return ""@@ -1365,14 +1405,41 @@ func lookupHostTokenBinding(bindings map[string]string, tokenID, hostname stringif boundID == "" || !strings.HasPrefix(key, prefix) {continue}- boundHostname := strings.TrimSpace(strings.TrimPrefix(key, prefix))- if hostAgentHostnamesMatch(boundHostname, hostname) {- return boundID+ boundHostname, boundMachineID := splitHostTokenBindingRemainder(strings.TrimPrefix(key, prefix))+ if !hostAgentHostnamesMatch(boundHostname, hostname) {+ continue+ }+ // A binding qualified with a different machine's identity belongs to+ // another physical host that happens to share this hostname (#1753).+ if machineID != "" && boundMachineID != "" && !strings.EqualFold(boundMachineID, machineID) {+ continue}+ return boundID}return ""}+// hostTokenBindingMachineConflict reports whether adopting boundID would fold+// this report into a host record that demonstrably belongs to a different+// machine: the record's machine ID and the report's machine ID are both known+// and disagree. Same-machine reinstalls (equal or missing machine IDs) keep+// the binding so host identity stays stable (#1753).+func hostTokenBindingMachineConflict(hosts []models.Host, boundID, machineID string) bool {+ boundID = strings.TrimSpace(boundID)+ machineID = strings.TrimSpace(machineID)+ if boundID == "" || machineID == "" {+ return false+ }+ for _, candidate := range hosts {+ if strings.TrimSpace(candidate.ID) != boundID {+ continue+ }+ boundMachine := strings.TrimSpace(candidate.MachineID)+ return boundMachine != "" && !strings.EqualFold(boundMachine, machineID)+ }+ return false+}+func hostAgentHostnamesMatch(left, right string) bool {left = strings.TrimSpace(left)right = strings.TrimSpace(right)@@ -1707,7 +1774,7 @@ func (m *Monitor) RebuildTokenBindings() {if hostname == "" || agentID == "" {continue}- newHostBindings[hostTokenBindingKey(tokenID, hostname)] = agentID+ newHostBindings[hostTokenMachineBindingKey(tokenID, hostname, host.MachineID())] = agentID}// Log what changed@@ -2889,16 +2956,24 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.}existingHostModels := m.state.GetHosts()+ reportMachineID := strings.TrimSpace(report.Host.MachineID)identifier := baseIdentifierif tokenRecord != nil && strings.TrimSpace(tokenRecord.ID) != "" {tokenID := strings.TrimSpace(tokenRecord.ID)- bindingKey := hostTokenBindingKey(tokenID, hostname)+ bindingKey := hostTokenMachineBindingKey(tokenID, hostname, reportMachineID)m.mu.Lock()if m.hostTokenBindings == nil {m.hostTokenBindings = make(map[string]string)}- boundID := lookupHostTokenBinding(m.hostTokenBindings, tokenID, hostname)+ boundID := lookupHostTokenBinding(m.hostTokenBindings, tokenID, hostname, reportMachineID)+ if boundID != "" && hostTokenBindingMachineConflict(existingHostModels, boundID, reportMachineID) {+ // The binding resolves to a record that provably belongs to a+ // different machine: a second standalone site reusing the same+ // short hostname and shared install token (#1753). Fall through to+ // the unbound path so this machine gets its own identity slot.+ boundID = ""+ }if boundID != "" {m.hostTokenBindings[bindingKey] = boundID}@@ -2968,7 +3043,11 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.if m.hostTokenBindings == nil {m.hostTokenBindings = make(map[string]string)}- if existing := lookupHostTokenBinding(m.hostTokenBindings, tokenID, hostname); existing != "" {+ existing := lookupHostTokenBinding(m.hostTokenBindings, tokenID, hostname, reportMachineID)+ if existing != "" && hostTokenBindingMachineConflict(existingHostModels, existing, reportMachineID) {+ existing = ""+ }+ if existing != "" {m.hostTokenBindings[bindingKey] = existingidentifier = existing} else {@@ -3006,7 +3085,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.if m.hostTokenBindings == nil {m.hostTokenBindings = make(map[string]string)}- m.hostTokenBindings[hostTokenBindingKey(tokenID, hostname)] = identifier+ m.hostTokenBindings[hostTokenMachineBindingKey(tokenID, hostname, report.Host.MachineID)] = identifierm.mu.Unlock()}log.Info().diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.goindex 231b12bc11..e2ce84fa3f 100644--- a/internal/monitoring/monitor_host_agents_test.go+++ b/internal/monitoring/monitor_host_agents_test.go@@ -4931,7 +4931,7 @@ func TestIssue1654FreshInstallReusesStalePhysicalHostIdentity(t *testing.T) {if got := len(monitor.state.GetHosts()); got != 1 {t.Fatalf("host count = %d, want 1", got)}- if got := monitor.hostTokenBindings["fresh-token:disk-host.local"]; got != "original-host-id" {+ if got := monitor.hostTokenBindings[hostTokenMachineBindingKey("fresh-token", "disk-host.local", "machine-stable")]; got != "original-host-id" {t.Fatalf("fresh token binding = %q, want original-host-id", got)}if _, ok := monitor.hostTokenBindings["old-token:disk-host.local"]; ok {@@ -4939,6 +4939,68 @@ func TestIssue1654FreshInstallReusesStalePhysicalHostIdentity(t *testing.T) {}}+// TestIssue1753SharedTokenSameHostnameKeepsMachinesDistinct models two+// standalone Proxmox sites that reuse one short node name and were installed+// with the same pasted install token. The token+hostname binding must not fold+// the second machine into the first one's identity: pre-fix, the two records+// collapsed into a single flip-flopping host, and removing that host revoked+// the shared token, which surfaced as 401 "Unauthorized access attempt" on+// /api/agents/agent/report for the surviving site.+func TestIssue1753SharedTokenSameHostnameKeepsMachinesDistinct(t *testing.T) {+ monitor := issue1654Monitor()+ createdAt := time.Now().UTC().Add(-time.Hour)+ sharedToken := issue1654InstallToken("shared-token", createdAt)++ siteReport := func(machineID string, timestamp time.Time) agentshost.Report {+ return agentshost.Report{+ Agent: agentshost.AgentInfo{+ Version: "6.4.2",+ IntervalSeconds: 30,+ },+ Host: agentshost.HostInfo{+ MachineID: machineID,+ Hostname: "pve01",+ Platform: "proxmox",+ },+ Timestamp: timestamp,+ }+ }++ now := time.Now().UTC()+ var siteAID, siteBID string+ for round := 0; round < 3; round++ {+ hostA, err := monitor.ApplyHostReport(siteReport("machine-site-a", now.Add(time.Duration(round)*time.Minute)), sharedToken)+ if err != nil {+ t.Fatalf("round %d site A ApplyHostReport() error = %v", round, err)+ }+ hostB, err := monitor.ApplyHostReport(siteReport("machine-site-b", now.Add(time.Duration(round)*time.Minute+30*time.Second)), sharedToken)+ if err != nil {+ t.Fatalf("round %d site B ApplyHostReport() error = %v", round, err)+ }+ if round == 0 {+ siteAID, siteBID = hostA.ID, hostB.ID+ if siteAID == siteBID {+ t.Fatalf("both sites resolved to one identity %q", siteAID)+ }+ continue+ }+ if hostA.ID != siteAID || hostB.ID != siteBID {+ t.Fatalf("round %d identities flapped: site A %q (want %q), site B %q (want %q)",+ round, hostA.ID, siteAID, hostB.ID, siteBID)+ }+ }++ hosts := monitor.state.GetHosts()+ if len(hosts) != 2 {+ t.Fatalf("host count = %d, want 2 (one per site)", len(hosts))+ }+ for _, host := range hosts {+ if host.TokenID != "shared-token" {+ t.Fatalf("host %q token = %q, want shared-token", host.ID, host.TokenID)+ }+ }+}+func TestInstallHandoffReusesIdentityAcrossFinalInFlightReport(t *testing.T) {monitor := issue1654Monitor()createdAt := time.Now().UTC().Add(-2 * time.Minute)