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
Preserve shared unified agent credentials
pulse-triage[bot]c9e6a8346ba8
diff --git a/internal/api/agent_ingest.go b/internal/api/agent_ingest.goindex 60f4e90d4d..452c41ab77 100644--- a/internal/api/agent_ingest.go+++ b/internal/api/agent_ingest.go@@ -773,8 +773,6 @@ func (h *UnifiedAgentHandlers) HandleUninstall(w http.ResponseWriter, r *http.Reswitch {case errors.Is(err, monitoring.ErrHostAgentTokenMismatch):writeErrorResponse(w, http.StatusForbidden, "agent_lookup_forbidden", "Agent does not belong to this API token", nil)- case errors.Is(err, monitoring.ErrHostAgentTokenShared):- writeErrorResponse(w, http.StatusConflict, "agent_token_shared", "Collector credential is still used by another agent and must be rotated before uninstall", nil)case errors.Is(err, monitoring.ErrHostAgentNotFound):writeErrorResponse(w, http.StatusNotFound, "agent_not_found", "Agent has not registered with Pulse yet", nil)default:diff --git a/internal/monitoring/agent_token_shared_lifecycle_test.go b/internal/monitoring/agent_token_shared_lifecycle_test.gonew file mode 100644index 0000000000..00973a8902--- /dev/null+++ b/internal/monitoring/agent_token_shared_lifecycle_test.go@@ -0,0 +1,115 @@+package monitoring++import (+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++func newSharedAgentTokenLifecycleMonitor(tokenID string) *Monitor {+ return &Monitor{+ state: models.NewState(),+ config: &config.Config{APITokens: []config.APITokenRecord{{ID: tokenID, Name: "Unified agent"}}},+ hostTokenBindings: make(map[string]string),+ dockerTokenBindings: make(map[string]string),+ kubernetesTokenBindings: make(map[string]string),+ removedKubernetesClusters: make(map[string]time.Time),+ }+}++func requireAgentTokenPresent(t *testing.T, monitor *Monitor, tokenID string) {+ t.Helper()+ if got := len(monitor.config.APITokens); got != 1 || monitor.config.APITokens[0].ID != tokenID {+ t.Fatalf("shared unified token %q was revoked while a sibling module was live: %+v", tokenID, monitor.config.APITokens)+ }+}++func TestRemoveKubernetesClusterKeepsUnifiedTokenUsedByHost(t *testing.T) {+ const tokenID = "unified-kubernetes-token"+ monitor := newSharedAgentTokenLifecycleMonitor(tokenID)+ monitor.state.UpsertHost(models.Host{ID: "host-1", Hostname: "worker-1", TokenID: tokenID})+ monitor.state.UpsertKubernetesCluster(models.KubernetesCluster{+ ID: "cluster-1", Name: "cluster-1", TokenID: tokenID, TokenName: "Unified agent",+ })++ if _, err := monitor.RemoveKubernetesCluster("cluster-1"); err != nil {+ t.Fatalf("RemoveKubernetesCluster: %v", err)+ }+ requireAgentTokenPresent(t, monitor, tokenID)+}++func TestRemoveDockerHostKeepsUnifiedTokenUsedByKubernetes(t *testing.T) {+ const tokenID = "unified-docker-token"+ monitor := newSharedAgentTokenLifecycleMonitor(tokenID)+ monitor.state.UpsertDockerHost(models.DockerHost{+ ID: "docker-1", Hostname: "worker-1", TokenID: tokenID, TokenName: "Unified agent",+ })+ monitor.state.UpsertKubernetesCluster(models.KubernetesCluster{+ ID: "cluster-1", Name: "cluster-1", TokenID: tokenID,+ })++ if _, err := monitor.RemoveDockerHost("docker-1"); err != nil {+ t.Fatalf("RemoveDockerHost: %v", err)+ }+ requireAgentTokenPresent(t, monitor, tokenID)+}++func TestRemoveHostAgentKeepsUnifiedTokenUsedByKubernetes(t *testing.T) {+ const tokenID = "unified-host-token"+ monitor := newSharedAgentTokenLifecycleMonitor(tokenID)+ monitor.state.UpsertHost(models.Host{ID: "host-1", Hostname: "worker-1", TokenID: tokenID})+ monitor.state.UpsertKubernetesCluster(models.KubernetesCluster{+ ID: "cluster-1", Name: "cluster-1", TokenID: tokenID,+ })++ if _, err := monitor.RemoveHostAgent("host-1"); err != nil {+ t.Fatalf("RemoveHostAgent: %v", err)+ }+ requireAgentTokenPresent(t, monitor, tokenID)+}++func TestUninstallHostAgentKeepsCredentialUsedBySiblingHost(t *testing.T) {+ dataPath := t.TempDir()+ monitor := newHostRemovalLifecycleMonitor(t, dataPath)+ monitor.persistence = config.NewConfigPersistence(dataPath)++ now := time.Now().UTC()+ token := config.APITokenRecord{ID: "shared-host-token", Name: "Shared host token", CreatedAt: now.Add(-time.Hour)}+ monitor.config.APITokens = []config.APITokenRecord{token}+ if err := monitor.persistence.SaveAPITokens(monitor.config.APITokens); err != nil {+ t.Fatalf("SaveAPITokens: %v", err)+ }++ firstReport := hostRemovalLifecycleReport("machine-a", "machine-a", "agent-a", "site-a", "linux", now)+ secondReport := hostRemovalLifecycleReport("machine-b", "machine-b", "agent-b", "site-b", "linux", now)+ first, err := monitor.ApplyHostReport(firstReport, &token)+ if err != nil {+ t.Fatalf("ApplyHostReport(first): %v", err)+ }+ second, err := monitor.ApplyHostReport(secondReport, &token)+ if err != nil {+ t.Fatalf("ApplyHostReport(second): %v", err)+ }++ if _, err := monitor.UninstallHostAgent(first.ID, token.ID); err != nil {+ t.Fatalf("UninstallHostAgent(first): %v", err)+ }+ requireAgentTokenPresent(t, monitor, token.ID)+ live := monitor.GetLiveHostsSnapshot()+ if len(live) != 1 || live[0].ID != second.ID {+ t.Fatalf("sibling host %q did not survive first host uninstall: %+v", second.ID, live)+ }+ firstReport.Timestamp = now.Add(time.Minute)+ if _, err := monitor.ApplyHostReport(firstReport, &token); err == nil {+ t.Fatal("uninstalled host resumed reporting through the preserved shared credential")+ }+ persisted, err := monitor.persistence.LoadAPITokens()+ if err != nil {+ t.Fatalf("LoadAPITokens: %v", err)+ }+ if len(persisted) != 1 || persisted[0].ID != token.ID {+ t.Fatalf("shared credential was removed from durable inventory: %+v", persisted)+ }+}diff --git a/internal/monitoring/api_token_lifecycle.go b/internal/monitoring/api_token_lifecycle.goindex 7b3e2165f8..b92ac82ded 100644--- a/internal/monitoring/api_token_lifecycle.go+++ b/internal/monitoring/api_token_lifecycle.go@@ -40,3 +40,31 @@ func (m *Monitor) revokeAPIToken(tokenID string) (*config.APITokenRecord, error)return removed, nil}++// agentTokenUsedByLiveResource reports whether any currently monitored agent+// module still authenticates with tokenID. Unified-agent installs legitimately+// share one credential across host, Docker, and Kubernetes reports, so removing+// one module must not revoke the credential out from under its siblings.+// Callers that are removing a resource should delete it from state first.+func (m *Monitor) agentTokenUsedByLiveResource(tokenID string) bool {+ tokenID = strings.TrimSpace(tokenID)+ if tokenID == "" || m == nil || m.state == nil {+ return false+ }+ for _, host := range m.state.GetHosts() {+ if strings.TrimSpace(host.TokenID) == tokenID {+ return true+ }+ }+ for _, host := range m.state.GetDockerHosts() {+ if strings.TrimSpace(host.TokenID) == tokenID {+ return true+ }+ }+ for _, cluster := range m.state.GetKubernetesClusters() {+ if strings.TrimSpace(cluster.TokenID) == tokenID {+ return true+ }+ }+ return false+}diff --git a/internal/monitoring/kubernetes_agents.go b/internal/monitoring/kubernetes_agents.goindex 778434bf49..e0a75790ec 100644--- a/internal/monitoring/kubernetes_agents.go+++ b/internal/monitoring/kubernetes_agents.go@@ -1071,13 +1071,24 @@ func (m *Monitor) RemoveKubernetesCluster(clusterID string) (models.KubernetesCl}}- // Revoke the API token associated with this Kubernetes cluster+ // Revoke the API token associated with this Kubernetes cluster unless a+ // sibling module still uses it. Unified-agent installs share one credential+ // across host, Docker, and Kubernetes reports; revoking it here would turn a+ // Kubernetes-only removal into 401s for the surviving modules.if cluster.TokenID != "" {- tokenRemoved, err := m.revokeAPIToken(cluster.TokenID)- if err != nil {- log.Warn().Err(err).Str("tokenID", cluster.TokenID).Msg("API token revocation rolled back after Kubernetes cluster removal")- } else if tokenRemoved != nil {- log.Info().Str("tokenID", cluster.TokenID).Str("tokenName", cluster.TokenName).Msg("API token revoked for removed Kubernetes cluster")+ tokenID := strings.TrimSpace(cluster.TokenID)+ if m.agentTokenUsedByLiveResource(tokenID) {+ log.Info().+ Str("tokenID", tokenID).+ Str("k8sClusterID", clusterID).+ Msg("API token still used by other agents; skipping revocation during Kubernetes cluster removal")+ } else {+ tokenRemoved, err := m.revokeAPIToken(tokenID)+ if err != nil {+ log.Warn().Err(err).Str("tokenID", tokenID).Msg("API token revocation rolled back after Kubernetes cluster removal")+ } else if tokenRemoved != nil {+ log.Info().Str("tokenID", tokenID).Str("tokenName", cluster.TokenName).Msg("API token revoked for removed Kubernetes cluster")+ }}}diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.goindex 17019c2b05..7c099846fa 100644--- a/internal/monitoring/monitor_agents.go+++ b/internal/monitoring/monitor_agents.go@@ -356,29 +356,9 @@ func (m *Monitor) RemoveDockerHost(hostID string) (models.DockerHost, error) {// agent's next report with 401.if host.TokenID != "" {tokenID := strings.TrimSpace(host.TokenID)- tokenStillUsed := false- if readState := m.snapshotBackedUnifiedReadState(); readState != nil {- for _, other := range readState.Hosts() {- if other != nil && strings.TrimSpace(other.TokenID()) == tokenID {- tokenStillUsed = true- break- }- }- if !tokenStillUsed {- for _, other := range readState.DockerHosts() {- if other == nil {- continue- }- if dockerHostStableID(other) == hostID || strings.TrimSpace(other.ID()) == hostID {- continue- }- if strings.TrimSpace(other.TokenID()) == tokenID {- tokenStillUsed = true- break- }- }- }- }+ // The Docker host is already gone from state, so any remaining match is+ // a live sibling module (host, Docker, or Kubernetes).+ tokenStillUsed := m.agentTokenUsedByLiveResource(tokenID)if !tokenStillUsed {tokenRemoved, err := m.revokeAPIToken(tokenID)if err != nil {@@ -498,7 +478,6 @@ func (m *Monitor) removeDockerHostsForHostAgent(var (ErrHostAgentNotFound = errors.New("host agent not found")- ErrHostAgentTokenShared = errors.New("host agent token is still used by another resource")ErrHostAgentTokenMismatch = errors.New("host agent token mismatch"))@@ -589,9 +568,6 @@ func (m *Monitor) removeHostAgentLocked(hostID, requiredTokenID string, requireDtokenID := strings.TrimSpace(host.TokenID)hostname := strings.TrimSpace(host.Hostname)tokenStillUsed := m.hostAgentTokenUsedOutsideRemoval(tokenID, hostID, host, tombstone)- if requireDurableRevocation && tokenStillUsed {- return models.Host{}, ErrHostAgentTokenShared- }if m.hostContinuityStore != nil {if err := m.hostContinuityStore.Upsert(tombstone); err != nil {return models.Host{}, fmt.Errorf("persist host agent removal tombstone: %w", err)@@ -748,6 +724,11 @@ func (m *Monitor) hostAgentTokenUsedOutsideRemoval(return true}}+ for _, cluster := range m.state.GetKubernetesClusters() {+ if strings.TrimSpace(cluster.TokenID) == tokenID {+ return true+ }+ }return false}