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.

document integration contracts and canonical proofs

[email protected]1684244f76a8
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 8170f8f489..dc510df2df 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -32,6 +32,13 @@ Unsupported SMART commands, permission failures, and timeouts must never alter
native array membership or turn a present disk into a missing disk. Direct
SATA, SAS, USB-bridge, NVMe, and controller-member inventory must all survive
one compressed unified-agent report without a collector-side suffix cap.
+Appliance-vendored smartctl builds are part of that compatibility boundary.
+`PULSE_SMARTCTL_PATH` may select the installed binary explicitly; rejection of
+the JSON output option must retry the same probe in parseable text mode; DSM
+`/dev/sataN` devices must receive a SAT retry; and `STANDBY (OS)` remains
+standby evidence. Enumeration and each device probe have independent bounded
+deadlines so one slow disk cannot consume the complete SMART pass, while
+command errors retain bounded stderr for compatibility diagnosis.
`internal/monitoring/monitor.go` also serializes shared unified-resource
websocket payloads. Carrying plural availability facets through that serializer
is an adjacent monitoring/API projection and does not change agent enrollment,
@@ -187,6 +194,11 @@ must report compensation truth and attempt rollback rather than declaring a
partially connected replacement successful. The typed host-agent command path
owns durable terminal receipts for that mutation: reconnect or server recovery
may replay a persisted result, but may not execute the Docker mutation twice.
+The typed update preflight must accept the planned image only when the daemon's
+resolved image proves either the expected local content ID or the expected
+registry `RepoDigest`. A tag that resolves to neither digest fails before the
+rename boundary; comparing only a registry digest to a daemon-local image ID is
+not sufficient proof and must not reject an otherwise matching pull.
Automatic Patrol action admission wired through `internal/api/` is API/action-
lifecycle authority, not agent enrollment or command authority. Agent command
@@ -1439,6 +1451,11 @@ the intentionally sparse public response.
or no-data results, and partial or plain-text smartctl output must still
preserve model, serial, health, and temperature data through the same
host-agent runtime boundary instead of leaving monitoring to guess.
+ Vendor smartctl compatibility is proved in
+ `internal/hostagent/smartctl_standby_guard_test.go`: a JSON-option rejection
+ retries in text mode, DSM `/dev/sataN` gains a SAT attempt, an explicit
+ binary path bypasses PATH lookup, `STANDBY (OS)` is recognized, and stderr
+ survives command failure wrapping.
macOS thermal telemetry belongs in the same host-agent sensor contract, but
it must report Darwin `pmset` thermal and performance pressure as
`sensors.thermalState` instead of inventing Celsius readings from unavailable
@@ -3484,7 +3501,11 @@ from the saved-connection APIs instead of falling back to provider-local
inference or agent-first setup guidance. Saved-connection retests must use the
server-owned test routes, must allow masked-secret continuity on edit, and
must refresh the shared connection-summary state after a save or retest
-completes. `frontend-modern/src/utils/clusterEndpointPresentation.ts` and
+completes. A TrueNAS edit always sends the fingerprint field: a non-empty value
+updates the TLS pin and an explicit empty string clears a previously persisted
+pin. Omitting the field when the operator clears it would silently retain stale
+trust state and is outside the saved-connection lifecycle contract.
+`frontend-modern/src/utils/clusterEndpointPresentation.ts` and
`frontend-modern/src/utils/proxmoxSettingsPresentation.ts` remain part of that
same governed lifecycle surface, so endpoint reachability state,
discovery-prefill defaults, and variant copy do not drift into card-local
@@ -5368,6 +5389,17 @@ expired, missing-scope, and pre-removal credentials remain denied. The
operator-only `allow-reenroll` action is the explicit override that may clear
both the tombstone and detached-token lineage.
+A fresh installation can also arrive while an older same-machine host record
+is merely stale rather than tombstoned. When the presenting token's `CreatedAt`
+is newer than that record's last observation and machine ID plus normalized
+hostname identify the same physical host, report admission treats the event as
+explicit re-enrollment: it preserves the established canonical host ID,
+rebinds the new token, removes older duplicate generations and their token
+bindings, and therefore preserves physical-disk resource continuity. A
+pre-existing generation observed at or after the new token was created is live
+and must not be superseded. The focused proof lives in
+`internal/monitoring/monitor_host_agents_test.go`.
+
Report ingestion holds a shared lifecycle lock for the full state transition;
deletion, manual allowance, and tombstone expiry hold the exclusive side.
Reports that began before deletion complete first, then deletion removes their
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 8702933e71..31d26dbef4 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -232,6 +232,13 @@ wrap rebases that counter and produces a valid zero for the reset interval. A
source-uptime rollback rebases the complete counter epoch and leaves the first
post-restart rate unknown, including when a busy guest already surpassed its
pre-restart counter value before the next poll.
+LXC rows may merge `cluster/resources` with the independently sampled
+`/nodes/{node}/lxc/{vmid}/status/current` response. When both describe the same
+uptime epoch, a lower status/current disk counter is lagging evidence and must
+not overwrite a higher cumulative counter already observed from the cluster
+row. Only an uptime rollback proves a restart and permits the lower value to
+start a new epoch. This merge rule applies before rate calculation so endpoint
+ordering cannot fabricate a reset, zero interval, or negative disk rate.
First-sample and missing-field unknowns remain internal validity state; the
legacy API/websocket guest number fields stay numeric, while history, unified
metrics, and alerts omit the unknown observation instead of manufacturing
@@ -632,6 +639,13 @@ must never prevent the remaining configured hosts from being suppressed.
CORE/FreeNAS. Unknown or current versions fail closed. The decision and
persistent socket belong to one configured client, so reconnects or
legacy negotiation for one appliance cannot alter another appliance.
+ On a connection already configured as HTTPS, an `/api/current` handshake
+ that redirects to the same appliance's HTTPS web UI is unsupported-endpoint
+ evidence, not successful JSON-RPC negotiation. It may open only the bounded
+ REST version probe described above: recognized CORE/legacy releases select
+ REST, while current SCALE and unknown releases still fail closed. This
+ exception does not treat authentication, TLS, protocol, or method failures
+ as downgrade signals.
A plaintext `ws://` handshake answered with a redirect is not an
unsupported endpoint and must never wake the REST bridge. When the
redirect target is an https URL on the same host — TrueNAS's HTTP to
@@ -2445,6 +2459,15 @@ allowance is the only path that clears that lineage. Focused proofs are
`internal/api/host_agent_removal_lifecycle_integration_test.go`; the concurrency
proof must also pass under the Go race detector.
+Fresh-install reconciliation also applies before a tombstone exists. A token
+created after a stale same-machine, same-normalized-hostname observation is
+explicit re-enrollment evidence: monitoring preserves the established host ID,
+removes older duplicate generations and token bindings, and keeps physical-disk
+resource identities attached to that host. A generation observed at or after
+the new token's creation remains live and is never removed by this rule.
+`internal/monitoring/monitor_host_agents_test.go` proves stable-ID reuse,
+duplicate cleanup, and the live-generation guard.
+
### Native pool-health collection and appliance isolation
TrueNAS monitoring preserves the complete native `pool.query` observation
diff --git a/internal/hostagent/issue1653_synology_smart_test.go b/internal/hostagent/issue1653_synology_smart_test.go
deleted file mode 100644
index a1ab60092b..0000000000
--- a/internal/hostagent/issue1653_synology_smart_test.go
+++ /dev/null
@@ -1,111 +0,0 @@
-package hostagent
-
-import (
- "context"
- "errors"
- "os/exec"
- "slices"
- "strings"
- "testing"
-)
-
-func TestIssue1653OldSmartctlRetriesWithoutJSON(t *testing.T) {
- originalRun := smartRunCommandOutput
- originalLookPath := execLookPath
- t.Cleanup(func() {
- smartRunCommandOutput = originalRun
- execLookPath = originalLookPath
- })
-
- execLookPath = func(string) (string, error) { return "/usr/sbin/smartctl", nil }
- var calls [][]string
- smartRunCommandOutput = func(_ context.Context, _ string, args ...string) ([]byte, error) {
- calls = append(calls, slices.Clone(args))
- if slices.Contains(args, "--json=o") {
- return nil, errors.New("smartctl: unrecognized option '--json=o'")
- }
- return []byte(strings.Join([]string{
- "Device Model: Synology SATA Disk",
- "Serial Number: DSM1653",
- "SMART overall-health self-assessment test result: PASSED",
- "194 Temperature_Celsius 0x0022 100 100 000 Old_age Always - 31",
- }, "\n")), nil
- }
-
- result, err := collectSMARTTarget(context.Background(), smartctlTarget{Path: "/dev/sata1"})
- if err != nil {
- t.Fatalf("collectSMARTTarget() error = %v", err)
- }
- if result.Serial != "DSM1653" || result.Temperature != 31 || result.Health != "PASSED" {
- t.Fatalf("legacy text result = %+v", result)
- }
- if len(calls) != 2 || !slices.Contains(calls[0], "--json=o") || slices.Contains(calls[1], "--json=o") {
- t.Fatalf("smartctl calls = %v, want JSON attempt followed by text-compatible retry", calls)
- }
-}
-
-func TestIssue1653DSMDeviceGetsSATRetry(t *testing.T) {
- originalGOOS := runtimeGOOS
- t.Cleanup(func() { runtimeGOOS = originalGOOS })
- runtimeGOOS = "linux"
-
- attempts := smartctlProbeAttempts(smartctlTarget{Path: "/dev/sata7"})
- if len(attempts) < 2 {
- t.Fatalf("smartctlProbeAttempts(/dev/sata7) = %v, want untyped and SAT probes", attempts)
- }
- foundSAT := false
- for _, args := range attempts {
- for i := 0; i+1 < len(args); i++ {
- if args[i] == "-d" && args[i+1] == "sat" {
- foundSAT = true
- }
- }
- }
- if !foundSAT {
- t.Fatalf("smartctlProbeAttempts(/dev/sata7) = %v, want -d sat retry", attempts)
- }
-}
-
-func TestIssue1653SmartctlPathOverride(t *testing.T) {
- t.Setenv("PULSE_SMARTCTL_PATH", "/opt/syno/bin/smartctl")
- originalLookPath := execLookPath
- t.Cleanup(func() { execLookPath = originalLookPath })
- execLookPath = func(string) (string, error) {
- return "", errors.New("PATH lookup must not run")
- }
-
- path, err := resolveSmartctlPath()
- if err != nil {
- t.Fatalf("resolveSmartctlPath() error = %v", err)
- }
- if path != "/opt/syno/bin/smartctl" {
- t.Fatalf("resolveSmartctlPath() = %q", path)
- }
-}
-
-func TestIssue1653StandbyOSIsRecognized(t *testing.T) {
- fallback := parseSMARTTextFallback("Device is in STANDBY (OS) mode")
- if !fallback.Standby {
- t.Fatal("STANDBY (OS) text was not recognized")
- }
-}
-
-func TestIssue1653CommandErrorIncludesStderr(t *testing.T) {
- if _, err := exec.LookPath("sh"); err != nil {
- t.Skip("sh is unavailable")
- }
- _, err := runCommandOutputLimited(
- context.Background(),
- 1024,
- "sh",
- "-c",
- "printf 'smartctl: unrecognized option --json=o' >&2; exit 2",
- )
- if err == nil || !strings.Contains(err.Error(), "unrecognized option") {
- t.Fatalf("runCommandOutputLimited() error = %v, want captured stderr", err)
- }
- var exitErr *exec.ExitError
- if !errors.As(err, &exitErr) {
- t.Fatalf("wrapped error %T does not preserve exec.ExitError", err)
- }
-}
diff --git a/internal/hostagent/smartctl_standby_guard_test.go b/internal/hostagent/smartctl_standby_guard_test.go
index 5533c09531..4c1f7162c8 100644
--- a/internal/hostagent/smartctl_standby_guard_test.go
+++ b/internal/hostagent/smartctl_standby_guard_test.go
@@ -1,8 +1,12 @@
package hostagent
import (
+ "context"
+ "errors"
"fmt"
"io/fs"
+ "os/exec"
+ "slices"
"strings"
"testing"
)
@@ -130,3 +134,104 @@ func TestLinuxNonRotationalBlockDeviceUsesLinuxSysfsPath(t *testing.T) {
t.Fatal("expected Linux /dev/sda to resolve as a confirmed non-rotational device")
}
}
+
+func TestIssue1653OldSmartctlRetriesWithoutJSON(t *testing.T) {
+ originalRun := smartRunCommandOutput
+ originalLookPath := execLookPath
+ t.Cleanup(func() {
+ smartRunCommandOutput = originalRun
+ execLookPath = originalLookPath
+ })
+
+ execLookPath = func(string) (string, error) { return "/usr/sbin/smartctl", nil }
+ var calls [][]string
+ smartRunCommandOutput = func(_ context.Context, _ string, args ...string) ([]byte, error) {
+ calls = append(calls, slices.Clone(args))
+ if slices.Contains(args, "--json=o") {
+ return nil, errors.New("smartctl: unrecognized option '--json=o'")
+ }
+ return []byte(strings.Join([]string{
+ "Device Model: Synology SATA Disk",
+ "Serial Number: DSM1653",
+ "SMART overall-health self-assessment test result: PASSED",
+ "194 Temperature_Celsius 0x0022 100 100 000 Old_age Always - 31",
+ }, "\n")), nil
+ }
+
+ result, err := collectSMARTTarget(context.Background(), smartctlTarget{Path: "/dev/sata1"})
+ if err != nil {
+ t.Fatalf("collectSMARTTarget() error = %v", err)
+ }
+ if result.Serial != "DSM1653" || result.Temperature != 31 || result.Health != "PASSED" {
+ t.Fatalf("legacy text result = %+v", result)
+ }
+ if len(calls) != 2 || !slices.Contains(calls[0], "--json=o") || slices.Contains(calls[1], "--json=o") {
+ t.Fatalf("smartctl calls = %v, want JSON attempt followed by text-compatible retry", calls)
+ }
+}
+
+func TestIssue1653DSMDeviceGetsSATRetry(t *testing.T) {
+ originalGOOS := runtimeGOOS
+ t.Cleanup(func() { runtimeGOOS = originalGOOS })
+ runtimeGOOS = "linux"
+
+ attempts := smartctlProbeAttempts(smartctlTarget{Path: "/dev/sata7"})
+ if len(attempts) < 2 {
+ t.Fatalf("smartctlProbeAttempts(/dev/sata7) = %v, want untyped and SAT probes", attempts)
+ }
+ foundSAT := false
+ for _, args := range attempts {
+ for i := 0; i+1 < len(args); i++ {
+ if args[i] == "-d" && args[i+1] == "sat" {
+ foundSAT = true
+ }
+ }
+ }
+ if !foundSAT {
+ t.Fatalf("smartctlProbeAttempts(/dev/sata7) = %v, want -d sat retry", attempts)
+ }
+}
+
+func TestIssue1653SmartctlPathOverride(t *testing.T) {
+ t.Setenv("PULSE_SMARTCTL_PATH", "/opt/syno/bin/smartctl")
+ originalLookPath := execLookPath
+ t.Cleanup(func() { execLookPath = originalLookPath })
+ execLookPath = func(string) (string, error) {
+ return "", errors.New("PATH lookup must not run")
+ }
+
+ path, err := resolveSmartctlPath()
+ if err != nil {
+ t.Fatalf("resolveSmartctlPath() error = %v", err)
+ }
+ if path != "/opt/syno/bin/smartctl" {
+ t.Fatalf("resolveSmartctlPath() = %q", path)
+ }
+}
+
+func TestIssue1653StandbyOSIsRecognized(t *testing.T) {
+ fallback := parseSMARTTextFallback("Device is in STANDBY (OS) mode")
+ if !fallback.Standby {
+ t.Fatal("STANDBY (OS) text was not recognized")
+ }
+}
+
+func TestIssue1653CommandErrorIncludesStderr(t *testing.T) {
+ if _, err := exec.LookPath("sh"); err != nil {
+ t.Skip("sh is unavailable")
+ }
+ _, err := runCommandOutputLimited(
+ context.Background(),
+ 1024,
+ "sh",
+ "-c",
+ "printf 'smartctl: unrecognized option --json=o' >&2; exit 2",
+ )
+ if err == nil || !strings.Contains(err.Error(), "unrecognized option") {
+ t.Fatalf("runCommandOutputLimited() error = %v, want captured stderr", err)
+ }
+ var exitErr *exec.ExitError
+ if !errors.As(err, &exitErr) {
+ t.Fatalf("wrapped error %T does not preserve exec.ExitError", err)
+ }
+}
diff --git a/internal/monitoring/issue1654_host_reenrollment_test.go b/internal/monitoring/issue1654_host_reenrollment_test.go
deleted file mode 100644
index f102d7b8b2..0000000000
--- a/internal/monitoring/issue1654_host_reenrollment_test.go
+++ /dev/null
@@ -1,136 +0,0 @@
-package monitoring
-
-import (
- "testing"
- "time"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/config"
- "github.com/rcourtman/pulse-go-rewrite/internal/models"
- agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
-)
-
-func issue1654Monitor() *Monitor {
- return &Monitor{
- state: models.NewState(),
- config: &config.Config{},
- rateTracker: NewRateTracker(),
- hostTokenBindings: make(map[string]string),
- hostReportOrders: make(map[string]hostReportOrder),
- }
-}
-
-func issue1654Report(timestamp time.Time) agentshost.Report {
- return agentshost.Report{
- Agent: agentshost.AgentInfo{
- ID: "new-agent-install",
- Version: "6.2.0",
- IntervalSeconds: 30,
- },
- Host: agentshost.HostInfo{
- ID: "new-install-id",
- MachineID: "machine-stable",
- Hostname: "disk-host.local",
- Platform: "linux",
- },
- Timestamp: timestamp,
- }
-}
-
-func TestIssue1654FreshInstallReusesStalePhysicalHostIdentity(t *testing.T) {
- monitor := issue1654Monitor()
- createdAt := time.Now().UTC()
- monitor.state.UpsertHost(models.Host{
- ID: "original-host-id",
- Hostname: "disk-host.local",
- MachineID: "machine-stable",
- TokenID: "old-token",
- LastSeen: createdAt.Add(-time.Minute),
- Status: "offline",
- })
- monitor.hostTokenBindings["old-token:disk-host.local"] = "original-host-id"
-
- host, err := monitor.ApplyHostReport(
- issue1654Report(createdAt.Add(time.Minute)),
- &config.APITokenRecord{ID: "fresh-token", CreatedAt: createdAt},
- )
- if err != nil {
- t.Fatalf("ApplyHostReport() error = %v", err)
- }
- if host.ID != "original-host-id" {
- t.Fatalf("host ID = %q, want stable original-host-id", host.ID)
- }
- 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" {
- t.Fatalf("fresh token binding = %q, want original-host-id", got)
- }
- if _, ok := monitor.hostTokenBindings["old-token:disk-host.local"]; ok {
- t.Fatal("pre-install token binding survived stable-ID re-enrollment")
- }
-}
-
-func TestIssue1654ExistingDuplicateGenerationIsSuperseded(t *testing.T) {
- monitor := issue1654Monitor()
- createdAt := time.Now().UTC()
- monitor.state.UpsertHost(models.Host{
- ID: "stale-host-id",
- Hostname: "disk-host.local",
- MachineID: "machine-stable",
- TokenID: "old-token",
- LastSeen: createdAt.Add(-time.Minute),
- Status: "offline",
- })
- monitor.state.UpsertHost(models.Host{
- ID: "current-host-id",
- Hostname: "disk-host.local",
- MachineID: "machine-stable",
- TokenID: "fresh-token",
- LastSeen: createdAt.Add(time.Minute),
- Status: "online",
- })
- monitor.hostTokenBindings["old-token:disk-host.local"] = "stale-host-id"
- monitor.hostTokenBindings["fresh-token:disk-host.local"] = "current-host-id"
-
- host, err := monitor.ApplyHostReport(
- issue1654Report(createdAt.Add(2*time.Minute)),
- &config.APITokenRecord{ID: "fresh-token", CreatedAt: createdAt},
- )
- if err != nil {
- t.Fatalf("ApplyHostReport() error = %v", err)
- }
- if host.ID != "current-host-id" {
- t.Fatalf("host ID = %q, want current-host-id", host.ID)
- }
- hosts := monitor.state.GetHosts()
- if len(hosts) != 1 || hosts[0].ID != "current-host-id" {
- t.Fatalf("hosts after supersession = %+v", hosts)
- }
- if _, ok := monitor.hostTokenBindings["old-token:disk-host.local"]; ok {
- t.Fatal("stale token binding survived supersession")
- }
-}
-
-func TestIssue1654LivePreexistingAgentIsNotSuperseded(t *testing.T) {
- monitor := issue1654Monitor()
- createdAt := time.Now().UTC()
- monitor.state.UpsertHost(models.Host{
- ID: "still-live-host",
- Hostname: "disk-host.local",
- MachineID: "machine-stable",
- TokenID: "old-token",
- LastSeen: createdAt.Add(time.Minute),
- Status: "online",
- })
-
- _, err := monitor.ApplyHostReport(
- issue1654Report(createdAt.Add(2*time.Minute)),
- &config.APITokenRecord{ID: "fresh-token", CreatedAt: createdAt},
- )
- if err != nil {
- t.Fatalf("ApplyHostReport() error = %v", err)
- }
- if got := len(monitor.state.GetHosts()); got != 2 {
- t.Fatalf("host count = %d, want both live identities preserved", got)
- }
-}
diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.go
index 6165b0016a..9f93cb0c0c 100644
--- a/internal/monitoring/monitor_host_agents_test.go
+++ b/internal/monitoring/monitor_host_agents_test.go
@@ -4329,3 +4329,129 @@ func TestCleanupRRDCachePrunesStaleGuestAgentMemCache(t *testing.T) {
t.Error("fresh guest-agent meminfo cache entry pruned")
}
}
+
+func issue1654Monitor() *Monitor {
+ return &Monitor{
+ state: models.NewState(),
+ config: &config.Config{},
+ rateTracker: NewRateTracker(),
+ hostTokenBindings: make(map[string]string),
+ hostReportOrders: make(map[string]hostReportOrder),
+ }
+}
+
+func issue1654Report(timestamp time.Time) agentshost.Report {
+ return agentshost.Report{
+ Agent: agentshost.AgentInfo{
+ ID: "new-agent-install",
+ Version: "6.2.0",
+ IntervalSeconds: 30,
+ },
+ Host: agentshost.HostInfo{
+ ID: "new-install-id",
+ MachineID: "machine-stable",
+ Hostname: "disk-host.local",
+ Platform: "linux",
+ },
+ Timestamp: timestamp,
+ }
+}
+
+func TestIssue1654FreshInstallReusesStalePhysicalHostIdentity(t *testing.T) {
+ monitor := issue1654Monitor()
+ createdAt := time.Now().UTC()
+ monitor.state.UpsertHost(models.Host{
+ ID: "original-host-id",
+ Hostname: "disk-host.local",
+ MachineID: "machine-stable",
+ TokenID: "old-token",
+ LastSeen: createdAt.Add(-time.Minute),
+ Status: "offline",
+ })
+ monitor.hostTokenBindings["old-token:disk-host.local"] = "original-host-id"
+
+ host, err := monitor.ApplyHostReport(
+ issue1654Report(createdAt.Add(time.Minute)),
+ &config.APITokenRecord{ID: "fresh-token", CreatedAt: createdAt},
+ )
+ if err != nil {
+ t.Fatalf("ApplyHostReport() error = %v", err)
+ }
+ if host.ID != "original-host-id" {
+ t.Fatalf("host ID = %q, want stable original-host-id", host.ID)
+ }
+ 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" {
+ t.Fatalf("fresh token binding = %q, want original-host-id", got)
+ }
+ if _, ok := monitor.hostTokenBindings["old-token:disk-host.local"]; ok {
+ t.Fatal("pre-install token binding survived stable-ID re-enrollment")
+ }
+}
+
+func TestIssue1654ExistingDuplicateGenerationIsSuperseded(t *testing.T) {
+ monitor := issue1654Monitor()
+ createdAt := time.Now().UTC()
+ monitor.state.UpsertHost(models.Host{
+ ID: "stale-host-id",
+ Hostname: "disk-host.local",
+ MachineID: "machine-stable",
+ TokenID: "old-token",
+ LastSeen: createdAt.Add(-time.Minute),
+ Status: "offline",
+ })
+ monitor.state.UpsertHost(models.Host{
+ ID: "current-host-id",
+ Hostname: "disk-host.local",
+ MachineID: "machine-stable",
+ TokenID: "fresh-token",
+ LastSeen: createdAt.Add(time.Minute),
+ Status: "online",
+ })
+ monitor.hostTokenBindings["old-token:disk-host.local"] = "stale-host-id"
+ monitor.hostTokenBindings["fresh-token:disk-host.local"] = "current-host-id"
+
+ host, err := monitor.ApplyHostReport(
+ issue1654Report(createdAt.Add(2*time.Minute)),
+ &config.APITokenRecord{ID: "fresh-token", CreatedAt: createdAt},
+ )
+ if err != nil {
+ t.Fatalf("ApplyHostReport() error = %v", err)
+ }
+ if host.ID != "current-host-id" {
+ t.Fatalf("host ID = %q, want current-host-id", host.ID)
+ }
+ hosts := monitor.state.GetHosts()
+ if len(hosts) != 1 || hosts[0].ID != "current-host-id" {
+ t.Fatalf("hosts after supersession = %+v", hosts)
+ }
+ if _, ok := monitor.hostTokenBindings["old-token:disk-host.local"]; ok {
+ t.Fatal("stale token binding survived supersession")
+ }
+}
+
+func TestIssue1654LivePreexistingAgentIsNotSuperseded(t *testing.T) {
+ monitor := issue1654Monitor()
+ createdAt := time.Now().UTC()
+ monitor.state.UpsertHost(models.Host{
+ ID: "still-live-host",
+ Hostname: "disk-host.local",
+ MachineID: "machine-stable",
+ TokenID: "old-token",
+ LastSeen: createdAt.Add(time.Minute),
+ Status: "online",
+ })
+
+ _, err := monitor.ApplyHostReport(
+ issue1654Report(createdAt.Add(2*time.Minute)),
+ &config.APITokenRecord{ID: "fresh-token", CreatedAt: createdAt},
+ )
+ if err != nil {
+ t.Fatalf("ApplyHostReport() error = %v", err)
+ }
+ if got := len(monitor.state.GetHosts()); got != 2 {
+ t.Fatalf("host count = %d, want both live identities preserved", got)
+ }
+}