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.

Harden host agent re-enrollment lifecycle

rcourtman0a95b25f4154
diff --git a/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-host-agent-reenrollment-2026-07-23.md b/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-host-agent-reenrollment-2026-07-23.md
new file mode 100644
index 0000000000..a8143ef2a6
--- /dev/null
+++ b/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-host-agent-reenrollment-2026-07-23.md
@@ -0,0 +1,68 @@
+# Known RC Issue Closure For GA Host Agent Re-enrollment Record
+
+- Date: `2026-07-23`
+- Gate: `known-rc-issue-closure-for-ga`
+- Issue: `#1581`
+- Result: `fixed-main-proof`
+
+## Context
+
+Issue `#1581` reported that deleting a host could leave its machine identity
+permanently rejected, preventing the agent from re-enrolling. The first fix,
+commit `2bc48774c216ff53c6e8060e321f2edbb6d368fd`, shipped in `v6.1.0-rc.2`
+and is present in `v6.1.1`. It made a token created after removal explicit
+re-enrollment intent and corrected expiry of the removal entries stored in the
+live monitor state.
+
+The issue's restart test did not reconstruct a monitor from disk. It created a
+new in-memory state and manually inserted a removal entry, while the production
+`models.State` removal list is not persisted. A real server restart therefore
+lost the deny boundary rather than proving its expiry or re-enrollment
+semantics. A report already in flight could also complete after deletion and
+recreate the host.
+
+## Disposition
+
+The existing durable `host_continuity.json` identity record is now the atomic
+host lifecycle journal. Deletion writes a tombstone before revoking an unused
+token or cleaning live resources. Monitor construction hydrates tombstones
+before accepting reports. Active continuity, monitored-system, licensing, and
+remote-config reads exclude removed entries. Journal load, write, and expiry
+fail closed; failed deletion restores the live host.
+
+Re-enrollment requires a different token created after removal plus the
+retained canonical or agent/report alias, compatible machine ID, and compatible
+hostname. It preserves the canonical host ID across Linux systemd machine IDs,
+Docker unified-agent IDs, and Windows MachineGuid IDs. The detached old token
+remains denied for that identity after re-enrollment, even when it is shared
+and valid for another active agent. Manual admin `allow-reenroll` remains the
+explicit override.
+
+A dedicated lifecycle read/write lock orders report ingestion against delete,
+allow, and expiry. Concurrent reports complete before deletion or observe the
+tombstone afterward; a successful delete cannot be undone by an in-flight
+report.
+
+## Proof
+
+- `go test ./internal/config -run TestHostContinuityStore -count=1`
+- `go test ./internal/monitoring -run 'TestHostAgentRemovalLifecycle|TestApplyHostReport_FreshTokenClearsRemovalBlock|TestAllowHostAgentReenroll_ClearsStateMirrorWithoutMemoryEntry|TestCleanupRemovedHostAgents_ExpiresStateMirrorEntries|TestMatchHostConfigContinuity' -count=1`
+- `go test -race ./internal/monitoring -run TestHostAgentRemovalLifecycle -count=1`
+- `go test ./internal/api -run TestHostAgentRemovalLifecycleThroughAuthenticatedRouterAndRestart -count=1`
+- `go test ./scripts/installtests -run 'TestPulseAgentStateDirLifecycleIntegration|TestInstallSHRecoversSavedStateForPartialUninstallContext|TestInstallPS1OwnsWindowsServiceLoggingAndRecovery|TestInstallPS1PersistsAndRecoversConnectionIdentity' -count=1`
+- `go test ./internal/config -count=1`
+- `go test ./internal/monitoring -count=1`
+- `go test ./internal/api -count=1`
+- `go vet ./internal/config ./internal/monitoring ./internal/api`
+- subsystem registry, contract, status, control-plane, staged-shape, and
+ canonical-completion audits
+
+## Outcome
+
+`v6.1.1` already contains the `rc.2` fresh-token fix for the reported
+same-process symptom. The durable restart, detached-shared-token, and
+concurrent-report hardening in this record is on `main` for a future release;
+it is not retroactively part of `v6.1.1`, and no publication date is promised
+by this proof. The gate remains satisfied for current source because both the
+original regression and the residual production lifecycle gaps have objective
+coverage.
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index b6fb7b97b8..f4d812c921 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -7777,6 +7777,12 @@
"kind": "file",
"evidence_tier": "managed-runtime-exercise"
},
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-host-agent-reenrollment-2026-07-23.md",
+ "kind": "file",
+ "evidence_tier": "managed-runtime-exercise"
+ },
{
"repo": "pulse",
"path": "docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-installer-bundle-fallback-2026-05-01.md",
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 53a5908087..b93d6dc081 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -321,8 +321,9 @@ update, profile rollout, command reachability, or fleet-control authority.
Linux commands must keep custom CA, insecure/plain-HTTP, and optional-auth
behavior aligned so the Machines onboarding path does not diverge by OS.
18. `frontend-modern/src/utils/infrastructureSettingsPresentation.ts` shared with `api-contracts`: the infrastructure settings presentation helper is both an agent lifecycle control surface and an API-backed direct-node/discovery settings boundary.
-19. `internal/api/agent_install_command_shared.go` shared with `api-contracts`: agent install command assembly is both an agent lifecycle control surface and a canonical API payload contract boundary.
- 19a. `internal/api/cloud_agent_install_command.go` shared with `api-contracts`, `cloud-paid`: hosted tenant agent install command generation is both an agent lifecycle enrollment surface and a provider-hosted tenant boundary.
+19. `internal/api/agent_ingest.go` shared with `api-contracts`: Unified Agent report admission, removal, remote-config identity binding, and re-enrollment responses are both an agent lifecycle authority and a canonical authenticated API contract boundary.
+20. `internal/api/agent_install_command_shared.go` shared with `api-contracts`: agent install command assembly is both an agent lifecycle control surface and a canonical API payload contract boundary.
+ 20a. `internal/api/cloud_agent_install_command.go` shared with `api-contracts`, `cloud-paid`: hosted tenant agent install command generation is both an agent lifecycle enrollment surface and a provider-hosted tenant boundary.
The hosted PVE/PBS install command path must stay on the same token-file
command transport as the normal lifecycle install helpers, while failing
closed unless hosted mode is active, the target org exists, and the minted
@@ -332,8 +333,8 @@ update, profile rollout, command reachability, or fleet-control authority.
with tenant-local tokens; branding is report rendering configuration inside
that runtime, not a control-plane token, agent profile, or cross-client
ingest path.
-20. `internal/api/config_setup_handlers.go` shared with `api-contracts`: auto-register and setup handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.
-21. `internal/api/setup_script_render.go` shared with `api-contracts`, `storage-recovery`: the generated Proxmox setup-script is a shared boundary across agent lifecycle (forced-command keys, install/uninstall edits), API contracts (rendered token shape and encoded rerun URL), and storage/recovery (backup visibility grants, Pulse-managed temperature SSH keys, and SMART disk-temperature collection).
+21. `internal/api/config_setup_handlers.go` shared with `api-contracts`: auto-register and setup handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.
+22. `internal/api/setup_script_render.go` shared with `api-contracts`, `storage-recovery`: the generated Proxmox setup-script is a shared boundary across agent lifecycle (forced-command keys, install/uninstall edits), API contracts (rendered token shape and encoded rerun URL), and storage/recovery (backup visibility grants, Pulse-managed temperature SSH keys, and SMART disk-temperature collection).
PBS setup-script auto-registration remains lifecycle-owned bootstrap
transport: rendered scripts must post registration payloads to the canonical
Pulse base URL plus `/api/auto-register`, not to the script download
@@ -345,9 +346,13 @@ update, profile rollout, command reachability, or fleet-control authority.
that would be sent to Pulse. A failed smoke check may leave manual token
details for the operator, but it must not POST an unproven token as a
completed lifecycle registration.
-22. `internal/api/unified_agent.go` shared with `api-contracts`: unified agent download and installer handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.
-23. `internal/kubernetesagent/agent.go` shared with `monitoring`: the Kubernetes native agent runtime is both a monitoring inventory source and an agent lifecycle Pulse control-plane transport client.
-24. `pkg/agents/host/report.go` shared with `monitoring`: the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host maintenance posture.
+23. `internal/api/unified_agent.go` shared with `api-contracts`: unified agent download and installer handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.
+24. `internal/config/host_continuity.go` shared with `monitoring`: the durable host identity, report-order watermark, and removal tombstone journal is jointly owned by agent lifecycle admission and monitoring report continuity.
+25. `internal/kubernetesagent/agent.go` shared with `monitoring`: the Kubernetes native agent runtime is both a monitoring inventory source and an agent lifecycle Pulse control-plane transport client.
+26. `internal/models/models.go` shared with `monitoring`: removed host-agent identity aliases and tombstone state are both agent lifecycle authority and monitoring runtime report state.
+27. `internal/monitoring/monitor.go` shared with `monitoring`: monitor construction owns both monitoring runtime initialization and fail-closed agent lifecycle journal hydration before report admission.
+28. `internal/monitoring/monitor_agents.go` shared with `monitoring`: server-side Unified Agent report, removal, token binding, tombstone expiry, and re-enrollment semantics are jointly owned by agent lifecycle authority and monitoring ingest.
+29. `pkg/agents/host/report.go` shared with `monitoring`: the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host maintenance posture.
Every current agent process authors a process-unique report stream and a
monotonic sequence within that stream. Reconnect delivery must preserve
collection order by draining each destination's persisted FIFO before
@@ -357,7 +362,7 @@ update, profile rollout, command reachability, or fleet-control authority.
retain it. Unraid collection treats positive `mdResyncPos` / `mdResync` as
authoritative active-operation evidence and emits zero progress whenever
no active sync action exists, even if terminal percentage fields linger.
-25. `scripts/install.ps1` shared with `deployment-installability`: the Windows installer is both a deployment installability entry point and a canonical agent lifecycle runtime continuity boundary.
+30. `scripts/install.ps1` shared with `deployment-installability`: the Windows installer is both a deployment installability entry point and a canonical agent lifecycle runtime continuity boundary.
The Windows installer must support a non-mutating download preflight that
can run before Administrator-only install work, must accept token-file
enrollment input, and must persist plain-HTTP/insecure runtime continuity
@@ -373,7 +378,7 @@ update, profile rollout, command reachability, or fleet-control authority.
version replacement, logged readiness, forced-process recovery, service
restart or OS reboot persistence, and complete uninstall cleanup through
the reusable lifecycle harness under `scripts/installtests/`.
-26. `scripts/install.sh` shared with `deployment-installability`: the shell installer is both a deployment installability entry point and a canonical agent lifecycle runtime continuity boundary.
+31. `scripts/install.sh` shared with `deployment-installability`: the shell installer is both a deployment installability entry point and a canonical agent lifecycle runtime continuity boundary.
`--state-dir` is a whole-lifecycle ownership boundary, not only a runtime
flag. The resolved directory owns the protected bootstrap token,
enrollment runtime token, server-acknowledged `agent-id`, buffered and
@@ -4936,3 +4941,52 @@ Neither an expected-transient decision nor an indeterminate UDP outcome may be
translated into an agent action. Any later customer-infrastructure mutation
still requires the canonical Actions planner, approval, executor, receipt,
audit, and verification boundaries.
+
+### Server-side host deletion and re-enrollment authority
+
+Agent lifecycle owns the complete server-side host deletion transition through
+`internal/config/host_continuity.go`, `internal/monitoring/monitor.go`,
+`internal/monitoring/monitor_agents.go`, `internal/models/models.go`, and
+`internal/api/agent_ingest.go`. Removing a host must atomically convert its
+active continuity record into a durable removal tombstone before token
+revocation, live-state deletion, alert cleanup, resource unlinking, or remote
+configuration cleanup can be reported as successful. A journal write failure
+restores the live host and returns a server error. An unreadable journal blocks
+monitor startup rather than starting with an empty deny set.
+
+The tombstone retains the canonical host ID, machine ID, agent-reported ID,
+report-host ID, hostname, platform, token ID, and removal time. Monitor
+construction hydrates non-expired tombstones before report admission; active
+continuity, licensing, inventory, and remote-config lookups exclude them.
+Tombstones expire durably after 24 hours. If expiry cannot be persisted, the
+server keeps the deny boundary in memory and on the next restart.
+
+A report may clear a tombstone automatically only when it presents a different
+token created after removal and its canonical or retained alias, machine ID,
+and hostname still identify the removed machine. A fresh token for a cloned
+machine, different hostname, or conflicting machine ID must not clear the
+record. Successful re-enrollment preserves the original canonical host ID and
+retains the detached old token in the identity's deny lineage. This lets a
+shared old token continue serving an unrelated active agent without allowing
+that credential to recreate or remote-configure the removed host. Revoked,
+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.
+
+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
+result. Reports arriving after deletion see the tombstone. A completed delete
+therefore cannot be undone by an in-flight report, while unrelated and
+duplicate-machine agents remain concurrent and independently bound by token
+plus hostname.
+
+The server transition does not introduce a second installer lifecycle.
+Generated host install commands still mint the canonical scoped token, and the
+existing Unix systemd/state-directory and Windows ProgramData/service
+installers remain idempotent across rerun, process restart, and service
+restart. `internal/api/host_agent_removal_lifecycle_integration_test.go`,
+`internal/config/host_continuity_test.go`,
+`internal/monitoring/monitor_host_agent_removal_lifecycle_test.go`, and the
+existing `scripts/installtests/agent_state_dir_lifecycle_test.go`,
+`install_sh_test.go`, and `install_ps1_test.go` are the production-path proofs.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 41fe57e522..3c5c84ccc1 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1303,7 +1303,8 @@ payload shape change when the portal presents compact client rows.
controls. That sequence is presentation guidance for the existing setup
payload phases; it does not create a second node setup API model or allow
page-local payload ownership.
-63. `internal/api/agent_install_command_shared.go` shared with `agent-lifecycle`: agent install command assembly is both an agent lifecycle control surface and a canonical API payload contract boundary.
+63. `internal/api/agent_ingest.go` shared with `agent-lifecycle`: Unified Agent report admission, removal, remote-config identity binding, and re-enrollment responses are both an agent lifecycle authority and a canonical authenticated API contract boundary.
+64. `internal/api/agent_install_command_shared.go` shared with `agent-lifecycle`: agent install command assembly is both an agent lifecycle control surface and a canonical API payload contract boundary.
Frontend and backend Unix install command builders must stay on the same
token-file and preflight transport contract: tokens are passed to the
installer as ephemeral files, and host install snippets must verify the
@@ -8147,3 +8148,37 @@ rollback, and preview behavior.
`frontend-modern/src/api/__tests__/alertIntentPolicies.test.ts` and the
availability target API and settings tests prove the canonical browser routes
and additive UDP wire fields.
+
+### Host-agent removal and re-enrollment transport
+
+The canonical host lifecycle routes are
+`POST /api/agents/agent/report`,
+`DELETE /api/agents/agent/{agentId}`,
+`POST /api/agents/agent/{agentId}/allow-reenroll`,
+`GET /api/agents/agent/{agentId}/config`, and
+`POST /api/agent-install-command`; the `/api/agents/host/` forms remain legacy
+aliases only. Deletion and manual allowance require an authenticated admin
+credential with `settings:write`. Report and config reads retain their
+agent-report/config scope gates and exact token-to-agent binding.
+
+A successful delete means the durable removal tombstone exists before the API
+returns. Journal persistence failure returns `500 agent_removal_failed` and
+leaves the live host present. A removed or detached host report reaches the
+handler with a valid token but returns `400 invalid_report`; an absent,
+revoked, or expired token returns `401` in authentication; a valid token
+without `agent:report` returns `403 missing_scope`. Remote configuration for a
+removed host or for a shared token bound to a different requested host returns
+`404 agent_not_found`, never another host's configuration.
+
+`POST /api/agent-install-command` remains the explicit automatic re-enrollment
+intent: its newly created scoped token can clear only the matching persisted
+machine tombstone and receives the original canonical agent ID. The prior
+credential remains denied for that identity after re-enrollment, even if it is
+still valid for another active agent. The admin-only `allow-reenroll` route is
+the explicit policy override that permits the prior credential again.
+
+`internal/api/host_agent_removal_lifecycle_integration_test.go` exercises the
+real router middleware, token persistence/reload, monitor reconstruction,
+delete and config handlers, generated install token, alias re-enrollment, and
+shared-token isolation. It is the production-path contract proof alongside the
+monitoring race and continuity-store tests.
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index a829bcc605..a8830c90fe 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -224,9 +224,13 @@ data cannot wrap into a fabricated healthy value.
## Shared Boundaries
-1. `internal/kubernetesagent/agent.go` shared with `agent-lifecycle`: the Kubernetes native agent runtime is both a monitoring inventory source and an agent lifecycle Pulse control-plane transport client.
-2. `internal/proxmoxidentity/backup_identity.go` shared with `alerts`, `storage-recovery`: Proxmox PBS backup subject identity is a shared runtime boundary for monitoring backup freshness, backup-age alert attribution, and recovery-point guest mapping.
-3. `pkg/agents/host/report.go` shared with `agent-lifecycle`: the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host maintenance posture.
+1. `internal/config/host_continuity.go` shared with `agent-lifecycle`: the durable host identity, report-order watermark, and removal tombstone journal is jointly owned by agent lifecycle admission and monitoring report continuity.
+2. `internal/kubernetesagent/agent.go` shared with `agent-lifecycle`: the Kubernetes native agent runtime is both a monitoring inventory source and an agent lifecycle Pulse control-plane transport client.
+3. `internal/models/models.go` shared with `agent-lifecycle`: removed host-agent identity aliases and tombstone state are both agent lifecycle authority and monitoring runtime report state.
+4. `internal/monitoring/monitor.go` shared with `agent-lifecycle`: monitor construction owns both monitoring runtime initialization and fail-closed agent lifecycle journal hydration before report admission.
+5. `internal/monitoring/monitor_agents.go` shared with `agent-lifecycle`: server-side Unified Agent report, removal, token binding, tombstone expiry, and re-enrollment semantics are jointly owned by agent lifecycle authority and monitoring ingest.
+6. `internal/proxmoxidentity/backup_identity.go` shared with `alerts`, `storage-recovery`: Proxmox PBS backup subject identity is a shared runtime boundary for monitoring backup freshness, backup-age alert attribution, and recovery-point guest mapping.
+7. `pkg/agents/host/report.go` shared with `agent-lifecycle`: the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host maintenance posture.
## Extension Points
@@ -2027,3 +2031,40 @@ reachability. `internal/monitoring/availability_udp_test.go`,
`internal/monitoring/monitor_alert_intent_test.go`, and the backup polling
assertion in `internal/monitoring/monitor_full_coverage_test.go` are the focused
proofs.
+
+### Durable host-agent removal admission
+
+Monitoring ingest shares server-side host lifecycle authority with the
+agent-lifecycle subsystem. `Monitor.RemoveHostAgent` must persist a tombstone
+in the host continuity journal before it revokes an unused token, removes the
+live record, unlinks resources, clears connection health, or resolves alerts.
+The journal transition is rollback-safe. Persistence failure leaves the live
+host present; journal load failure prevents monitor construction; expiry
+failure retains the block. Monitoring must never convert an unavailable
+security journal into an empty in-memory removal map.
+
+`Monitor.New` hydrates canonical ID plus report-host, agent, machine, hostname,
+platform, and token aliases from every non-expired tombstone. Removed entries
+are excluded from active standalone-host continuity, monitored-system
+projection, and remote-config fallback. The 24-hour expiry is based on the
+persisted `removedAt` timestamp and deletes durable state before clearing the
+snapshot and cache.
+
+`ApplyHostReport` and removal are ordered by the dedicated host lifecycle
+read/write lock. Concurrent reports may proceed together, but deletion waits
+for earlier reports and prevents later reports from resurrecting the host.
+Only a post-removal token and matching retained machine identity may transition
+the tombstone back to active continuity. The canonical host ID survives report
+ID or persisted-agent-ID alias changes across Linux/systemd, Docker unified
+agents, and Windows MachineGuid identities. Token-plus-hostname disambiguation
+continues to keep simultaneous cloned or duplicate machine IDs distinct.
+
+After fresh-token re-enrollment, the old token stays attached to the host's
+denied-token lineage even when that token is intentionally shared and remains
+valid for another active agent. Monitoring rejects the detached credential
+before token binding can manufacture a duplicate host. Manual operator
+allowance is the only path that clears that lineage. Focused proofs are
+`internal/monitoring/monitor_host_agent_removal_lifecycle_test.go`,
+`internal/monitoring/monitor_host_agents_test.go`, and
+`internal/api/host_agent_removal_lifecycle_integration_test.go`; the concurrency
+proof must also pass under the Go race detector.
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 103b64d7e2..c49721eae0 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -723,6 +723,14 @@
"organization-settings"
]
},
+ {
+ "path": "internal/api/agent_ingest.go",
+ "rationale": "Unified Agent report admission, removal, remote-config identity binding, and re-enrollment responses are both an agent lifecycle authority and a canonical authenticated API contract boundary",
+ "subsystems": [
+ "agent-lifecycle",
+ "api-contracts"
+ ]
+ },
{
"path": "internal/api/agent_install_command_shared.go",
"rationale": "agent install command assembly is both an agent lifecycle control surface and a canonical API payload contract boundary",
@@ -980,6 +988,14 @@
"deployment-installability"
]
},
+ {
+ "path": "internal/config/host_continuity.go",
+ "rationale": "the durable host identity, report-order watermark, and removal tombstone journal is jointly owned by agent lifecycle admission and monitoring report continuity",
+ "subsystems": [
+ "agent-lifecycle",
+ "monitoring"
+ ]
+ },
{
"path": "internal/kubernetesagent/agent.go",
"rationale": "the Kubernetes native agent runtime is both a monitoring inventory source and an agent lifecycle Pulse control-plane transport client",
@@ -988,6 +1004,30 @@
"monitoring"
]
},
+ {
+ "path": "internal/models/models.go",
+ "rationale": "removed host-agent identity aliases and tombstone state are both agent lifecycle authority and monitoring runtime report state",
+ "subsystems": [
+ "agent-lifecycle",
+ "monitoring"
+ ]
+ },
+ {
+ "path": "internal/monitoring/monitor.go",
+ "rationale": "monitor construction owns both monitoring runtime initialization and fail-closed agent lifecycle journal hydration before report admission",
+ "subsystems": [
+ "agent-lifecycle",
+ "monitoring"
+ ]
+ },
+ {
+ "path": "internal/monitoring/monitor_agents.go",
+ "rationale": "server-side Unified Agent report, removal, token binding, tombstone expiry, and re-enrollment semantics are jointly owned by agent lifecycle authority and monitoring ingest",
+ "subsystems": [
+ "agent-lifecycle",
+ "monitoring"
+ ]
+ },
{
"path": "internal/operationaltrust/contracts.go",
"rationale": "the operational trust contract is jointly consumed by canonical alert lifecycle ownership and notification delivery linkage without making delivery state operational truth",
@@ -1187,14 +1227,19 @@
"frontend-modern/src/utils/unifiedAgentInventoryPresentation.ts",
"frontend-modern/src/utils/unifiedAgentStatusPresentation.ts",
"internal/agenttls/config.go",
+ "internal/api/agent_ingest.go",
"internal/api/agent_install_command_shared.go",
"internal/api/config_setup_handlers.go",
"internal/api/setup_script_render.go",
"internal/api/unified_agent.go",
+ "internal/config/host_continuity.go",
"internal/dockeragent/agent.go",
"internal/dockeragent/container_update.go",
"internal/dockeragent/container_update_typed.go",
"internal/kubernetesagent/agent.go",
+ "internal/models/models.go",
+ "internal/monitoring/monitor.go",
+ "internal/monitoring/monitor_agents.go",
"internal/remoteconfig/client.go",
"internal/securityutil/httpurl.go",
"pkg/agents/host/report.go",
@@ -1279,6 +1324,29 @@
"internal/api/unified_agent_test.go"
]
},
+ {
+ "id": "host-agent-server-lifecycle",
+ "label": "server-side host-agent deletion and re-enrollment lifecycle proof",
+ "match_prefixes": [],
+ "match_files": [
+ "internal/api/agent_ingest.go",
+ "internal/config/host_continuity.go",
+ "internal/models/models.go",
+ "internal/monitoring/monitor.go",
+ "internal/monitoring/monitor_agents.go"
+ ],
+ "allow_same_subsystem_tests": false,
+ "test_prefixes": [],
+ "exact_files": [
+ "internal/api/host_agent_removal_lifecycle_integration_test.go",
+ "internal/config/host_continuity_test.go",
+ "internal/monitoring/monitor_host_agent_removal_lifecycle_test.go",
+ "internal/monitoring/monitor_host_agents_test.go",
+ "scripts/installtests/agent_state_dir_lifecycle_test.go",
+ "scripts/installtests/install_ps1_test.go",
+ "scripts/installtests/install_sh_test.go"
+ ]
+ },
{
"id": "agent-update-runtime",
"label": "agent update runtime proof",
@@ -2754,6 +2822,7 @@
"frontend-modern/src/types/api.ts",
"internal/api/ai_handlers_patrol_actions_additional_test.go",
"internal/api/contract_test.go",
+ "internal/api/host_agent_removal_lifecycle_integration_test.go",
"internal/api/patrol_autopilot_test.go"
]
},
@@ -5131,6 +5200,7 @@
"internal/config/host_continuity_test.go",
"internal/monitoring/issue1485_unraid_lifecycle_test.go",
"internal/monitoring/issue1595_collection_trust_test.go",
+ "internal/monitoring/monitor_host_agent_removal_lifecycle_test.go",
"internal/monitoring/monitor_host_agents_test.go",
"internal/monitoring/monitor_package_updates_test.go",
"internal/unifiedresources/code_standards_test.go"
@@ -5297,6 +5367,7 @@
"internal/models/state_host_test.go",
"internal/monitoring/issue1595_collection_trust_test.go",
"internal/monitoring/monitor_full_coverage_test.go",
+ "internal/monitoring/monitor_host_agent_removal_lifecycle_test.go",
"internal/monitoring/monitor_host_agents_test.go",
"internal/monitoring/monitor_package_updates_test.go",
"internal/unifiedresources/adapter_coverage_test.go",
@@ -5469,6 +5540,7 @@
"internal/monitoring/monitor_alert_intent_test.go",
"internal/monitoring/monitor_alert_override_migration_test.go",
"internal/monitoring/monitor_backups_readstate_test.go",
+ "internal/monitoring/monitor_host_agent_removal_lifecycle_test.go",
"internal/monitoring/monitor_host_agents_test.go",
"internal/unifiedresources/code_standards_test.go"
]
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 5e70e7b147..10a9f1a948 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -2279,6 +2279,15 @@ while storage detail drawers and filter controls must route summary series IDs,
source tones, and disk metrics through the shared storage helpers instead of
reconstructing them from local table state.
+Host-agent removal tombstones in `internal/config/host_continuity.go` are an
+adjacent agent-lifecycle security journal, not storage or recovery inventory.
+Storage/recovery consumers may observe the resulting absence of a removed host
+from canonical resources, but they must not load, repair, discard, or project
+that journal. If it is unreadable, monitor startup fails closed; recovery code
+must not substitute a backup continuity file or an empty removal set. Re-linking
+storage resources after a fresh-token agent re-enrollment follows the canonical
+resource ingest path and does not create a storage-local identity override.
+
### Backup-aware alert intent is not recovery assurance
The alerts subsystem may defer an offline alert while monitoring supplies
diff --git a/internal/api/agent_ingest.go b/internal/api/agent_ingest.go
index 6536131414..8882cdfecf 100644
--- a/internal/api/agent_ingest.go
+++ b/internal/api/agent_ingest.go
@@ -276,7 +276,7 @@ func (h *UnifiedAgentHandlers) HandleDeleteHost(w http.ResponseWriter, r *http.R
// Remove the agent from state.
host, err := h.getMonitor(r.Context()).RemoveHostAgent(agentID)
if err != nil {
- writeErrorResponse(w, http.StatusNotFound, "agent_not_found", err.Error(), nil)
+ writeErrorResponse(w, http.StatusInternalServerError, "agent_removal_failed", err.Error(), nil)
return
}
diff --git a/internal/api/host_agent_removal_lifecycle_integration_test.go b/internal/api/host_agent_removal_lifecycle_integration_test.go
new file mode 100644
index 0000000000..00c3e6f1c7
--- /dev/null
+++ b/internal/api/host_agent_removal_lifecycle_integration_test.go
@@ -0,0 +1,321 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "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"
+)
+
+type hostRemovalLifecycleHTTPRuntime struct {
+ config *config.Config
+ monitor *monitoring.Monitor
+ router *Router
+}
+
+func newHostRemovalLifecycleHTTPRuntime(
+ t *testing.T,
+ dataPath string,
+ tokens []config.APITokenRecord,
+) *hostRemovalLifecycleHTTPRuntime {
+ t.Helper()
+ cfg := &config.Config{
+ DataPath: dataPath,
+ ConfigPath: dataPath,
+ MetricsDBPath: filepath.Join(dataPath, "lifecycle-metrics.db"),
+ APITokens: append([]config.APITokenRecord(nil), tokens...),
+ }
+ monitor, err := monitoring.New(cfg)
+ if err != nil {
+ t.Fatalf("monitoring.New: %v", err)
+ }
+ router := NewRouter(cfg, monitor, nil, nil, func() error { return nil }, "6.1.1")
+ return &hostRemovalLifecycleHTTPRuntime{
+ config: cfg,
+ monitor: monitor,
+ router: router,
+ }
+}
+
+func (runtime *hostRemovalLifecycleHTTPRuntime) stop() {
+ if runtime == nil {
+ return
+ }
+ if runtime.router != nil {
+ runtime.router.shutdownBackgroundWorkers()
+ runtime.router = nil
+ }
+ if runtime.monitor != nil {
+ runtime.monitor.Stop()
+ runtime.monitor = nil
+ }
+}
+
+func serveHostRemovalLifecycleRequest(
+ t *testing.T,
+ runtime *hostRemovalLifecycleHTTPRuntime,
+ method string,
+ path string,
+ rawToken string,
+ body []byte,
+) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(method, path, bytes.NewReader(body))
+ req.Header.Set("Accept", "application/json")
+ if rawToken != "" {
+ req.Header.Set("X-API-Token", rawToken)
+ }
+ rec := httptest.NewRecorder()
+ runtime.router.Handler().ServeHTTP(rec, req)
+ return rec
+}
+
+func postHostRemovalLifecycleReport(
+ t *testing.T,
+ runtime *hostRemovalLifecycleHTTPRuntime,
+ rawToken string,
+ report agentshost.Report,
+) (int, string, string) {
+ t.Helper()
+ body, err := json.Marshal(report)
+ if err != nil {
+ t.Fatalf("marshal report: %v", err)
+ }
+ rec := serveHostRemovalLifecycleRequest(
+ t,
+ runtime,
+ http.MethodPost,
+ "/api/agents/agent/report",
+ rawToken,
+ body,
+ )
+ var response struct {
+ AgentID string `json:"agentId"`
+ }
+ if rec.Code == http.StatusOK {
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode report response: %v", err)
+ }
+ }
+ return rec.Code, response.AgentID, rec.Body.String()
+}
+
+func TestHostAgentRemovalLifecycleThroughAuthenticatedRouterAndRestart(t *testing.T) {
+ dataPath := t.TempDir()
+ now := time.Now().UTC()
+ const (
+ adminRaw = "issue-1581-admin-token-123.12345678"
+ sharedRaw = "issue-1581-shared-agent-token-123.12345678"
+ expiredRaw = "issue-1581-expired-agent-token-123.12345678"
+ wrongRaw = "issue-1581-wrong-scope-token-123.12345678"
+ revokedRaw = "issue-1581-revoked-token-123.12345678"
+ )
+
+ admin := newTokenRecord(t, adminRaw, []string{config.ScopeWildcard}, nil)
+ shared := newTokenRecord(
+ t,
+ sharedRaw,
+ []string{config.ScopeAgentReport, config.ScopeAgentConfigRead},
+ nil,
+ )
+ expired := newTokenRecord(t, expiredRaw, []string{config.ScopeAgentReport}, nil)
+ expiredAt := now.Add(-time.Hour)
+ expired.ExpiresAt = &expiredAt
+ wrongScope := newTokenRecord(t, wrongRaw, []string{config.ScopeMonitoringRead}, nil)
+ initialTokens := []config.APITokenRecord{admin, shared, expired, wrongScope}
+ if err := config.NewConfigPersistence(dataPath).SaveAPITokens(initialTokens); err != nil {
+ t.Fatalf("SaveAPITokens: %v", err)
+ }
+
+ targetReport := agentshost.Report{
+ Host: agentshost.HostInfo{
+ ID: "systemd-machine-id",
+ MachineID: "systemd-machine-id",
+ Hostname: "target.local",
+ Platform: "linux",
+ },
+ Agent: agentshost.AgentInfo{
+ ID: "persisted-target-agent-id",
+ Version: "6.1.1",
+ Type: "unified",
+ },
+ Timestamp: now,
+ }
+ keeperReport := agentshost.Report{
+ Host: agentshost.HostInfo{
+ ID: "keeper-machine-id",
+ MachineID: "keeper-machine-id",
+ Hostname: "keeper.local",
+ Platform: "linux",
+ },
+ Agent: agentshost.AgentInfo{
+ ID: "keeper-agent-id",
+ Version: "6.1.1",
+ Type: "unified",
+ },
+ Timestamp: now,
+ }
+
+ runtime := newHostRemovalLifecycleHTTPRuntime(t, dataPath, initialTokens)
+ t.Cleanup(func() { runtime.stop() })
+
+ targetStatus, targetID, targetBody := postHostRemovalLifecycleReport(t, runtime, sharedRaw, targetReport)
+ if targetStatus != http.StatusOK {
+ t.Fatalf("target report status = %d: %s", targetStatus, targetBody)
+ }
+ keeperStatus, keeperID, keeperBody := postHostRemovalLifecycleReport(t, runtime, sharedRaw, keeperReport)
+ if keeperStatus != http.StatusOK {
+ t.Fatalf("keeper report status = %d: %s", keeperStatus, keeperBody)
+ }
+ if targetID == "" || keeperID == "" || targetID == keeperID {
+ t.Fatalf("active IDs target=%q keeper=%q, want distinct", targetID, keeperID)
+ }
+
+ deleteRec := serveHostRemovalLifecycleRequest(
+ t,
+ runtime,
+ http.MethodDelete,
+ "/api/agents/agent/"+targetID,
+ adminRaw,
+ nil,
+ )
+ if deleteRec.Code != http.StatusOK {
+ t.Fatalf("delete status = %d: %s", deleteRec.Code, deleteRec.Body.String())
+ }
+ if _, ok := runtime.config.ValidateAPIToken(sharedRaw); !ok {
+ t.Fatal("shared token was revoked while the keeper still uses it")
+ }
+ if status, _, body := postHostRemovalLifecycleReport(t, runtime, sharedRaw, targetReport); status != http.StatusBadRequest {
+ t.Fatalf("same-process stale target status = %d, want 400: %s", status, body)
+ }
+ configRec := serveHostRemovalLifecycleRequest(
+ t,
+ runtime,
+ http.MethodGet,
+ "/api/agents/agent/"+targetID+"/config",
+ sharedRaw,
+ nil,
+ )
+ if configRec.Code != http.StatusOK {
+ t.Fatalf("shared-token keeper config status = %d, want 200: %s", configRec.Code, configRec.Body.String())
+ }
+ var configBody struct {
+ AgentID string `json:"agentId"`
+ }
+ if err := json.NewDecoder(configRec.Body).Decode(&configBody); err != nil {
+ t.Fatalf("decode shared-token keeper config after removal: %v", err)
+ }
+ if configBody.AgentID != keeperID {
+ t.Fatalf("removed target leaked through config as %q; want active keeper %q", configBody.AgentID, keeperID)
+ }
+
+ runtime.stop()
+ reloadedTokens, err := config.NewConfigPersistence(dataPath).LoadAPITokens()
+ if err != nil {
+ t.Fatalf("LoadAPITokens after restart: %v", err)
+ }
+ runtime = newHostRemovalLifecycleHTTPRuntime(t, dataPath, reloadedTokens)
+
+ targetReport.Host.ID = targetReport.Agent.ID
+ targetReport.Timestamp = now.Add(2 * time.Minute)
+ if status, _, body := postHostRemovalLifecycleReport(t, runtime, sharedRaw, targetReport); status != http.StatusBadRequest {
+ t.Fatalf("post-restart stale target status = %d, want 400: %s", status, body)
+ }
+ keeperReport.Timestamp = now.Add(2 * time.Minute)
+ if status, gotID, body := postHostRemovalLifecycleReport(t, runtime, sharedRaw, keeperReport); status != http.StatusOK || gotID != keeperID {
+ t.Fatalf("post-restart keeper = (%d, %q), want (200, %q): %s", status, gotID, keeperID, body)
+ }
+
+ for _, test := range []struct {
+ name string
+ token string
+ want int
+ }{
+ {name: "revoked", token: revokedRaw, want: http.StatusUnauthorized},
+ {name: "expired", token: expiredRaw, want: http.StatusUnauthorized},
+ {name: "wrong scope", token: wrongRaw, want: http.StatusForbidden},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ probe := targetReport
+ probe.Host.ID = "probe-" + test.name
+ probe.Host.MachineID = "probe-" + test.name
+ probe.Host.Hostname = "probe-" + test.name + ".local"
+ status, _, body := postHostRemovalLifecycleReport(t, runtime, test.token, probe)
+ if status != test.want {
+ t.Fatalf("status = %d, want %d: %s", status, test.want, body)
+ }
+ })
+ }
+
+ installRec := serveHostRemovalLifecycleRequest(
+ t,
+ runtime,
+ http.MethodPost,
+ "/api/agent-install-command",
+ adminRaw,
+ []byte(`{"type":"host","enableCommands":false,"name":"issue-1581-reenroll"}`),
+ )
+ install := decodeHostAgentInstallResponse(t, installRec)
+ freshRecord, freshRecordOK := runtime.config.ValidateAPIToken(install.Token)
+ if install.Token == "" ||
+ install.Record == nil ||
+ !freshRecordOK ||
+ !freshRecord.HasScope(config.ScopeAgentReport) {
+ t.Fatalf("fresh install response lacks report token: %+v", install)
+ }
+
+ freshStatus, freshID, freshBody := postHostRemovalLifecycleReport(t, runtime, install.Token, targetReport)
+ if freshStatus != http.StatusOK {
+ t.Fatalf("fresh-token re-enrollment status = %d: %s", freshStatus, freshBody)
+ }
+ if freshID != targetID {
+ t.Fatalf("fresh-token re-enrollment ID = %q, want canonical %q", freshID, targetID)
+ }
+
+ targetReport.Timestamp = now.Add(3 * time.Minute)
+ if status, _, body := postHostRemovalLifecycleReport(t, runtime, sharedRaw, targetReport); status != http.StatusBadRequest {
+ t.Fatalf("detached shared token status = %d, want 400: %s", status, body)
+ }
+ if hosts := runtime.monitor.GetLiveHostsSnapshot(); len(hosts) != 2 {
+ t.Fatalf("detached shared token changed active inventory: %+v", hosts)
+ }
+
+ freshConfig := serveHostRemovalLifecycleRequest(
+ t,
+ runtime,
+ http.MethodGet,
+ "/api/agents/agent/"+targetID+"/config",
+ install.Token,
+ nil,
+ )
+ if freshConfig.Code != http.StatusOK {
+ t.Fatalf("fresh-token config status = %d: %s", freshConfig.Code, freshConfig.Body.String())
+ }
+ oldConfig := serveHostRemovalLifecycleRequest(
+ t,
+ runtime,
+ http.MethodGet,
+ "/api/agents/agent/"+targetID+"/config",
+ sharedRaw,
+ nil,
+ )
+ if oldConfig.Code != http.StatusOK {
+ t.Fatalf("shared-token keeper config status = %d, want 200: %s", oldConfig.Code, oldConfig.Body.String())
+ }
+ var oldConfigBody struct {
+ AgentID string `json:"agentId"`
+ }
+ if err := json.NewDecoder(oldConfig.Body).Decode(&oldConfigBody); err != nil {
+ t.Fatalf("decode shared-token keeper config: %v", err)
+ }
+ if oldConfigBody.AgentID != keeperID {
+ t.Fatalf("shared token resolved config for %q, want active keeper %q", oldConfigBody.AgentID, keeperID)
+ }
+}
diff --git a/internal/config/host_continuity.go b/internal/config/host_continuity.go
index b52c661582..6b6d64f805 100644
--- a/internal/config/host_continuity.go
+++ b/internal/config/host_continuity.go
@@ -25,6 +25,7 @@ type HostContinuityEntry struct {
DisplayName string `json:"displayName,omitempty"`
MachineID string `json:"machineId,omitempty"`
TokenID string `json:"tokenId,omitempty"`
+ DeniedTokenIDs []string `json:"deniedTokenIds,omitempty"`
AgentVersion string `json:"agentVersion,omitempty"`
Platform string `json:"platform,omitempty"`
LinkedNodeID string `json:"linkedNodeId,omitempty"`
@@ -42,6 +43,7 @@ type HostContinuityEntry struct {
ReportStreamID string `json:"reportStreamId,omitempty"`
ReportSequence uint64 `json:"reportSequence,omitempty"`
RetiredReportStreamIDs []string `json:"retiredReportStreamIds,omitempty"`
+ RemovedAt time.Time `json:"removedAt,omitempty"`
}
// HostContinuityStore persists recent standalone host identity and report
@@ -52,6 +54,7 @@ type HostContinuityStore struct {
entries map[string]HostContinuityEntry
dataPath string
fs FileSystem
+ loadErr error
}
func NewHostContinuityStore(dataPath string, fs FileSystem) *HostContinuityStore {
@@ -64,6 +67,9 @@ func NewHostContinuityStore(dataPath string, fs FileSystem) *HostContinuityStore
store.fs = defaultFileSystem{}
}
if err := store.Load(); err != nil {
+ store.mu.Lock()
+ store.loadErr = err
+ store.mu.Unlock()
log.Warn().Err(err).Msg("Failed to load host continuity state")
}
return store
@@ -81,6 +87,8 @@ func normalizeHostContinuityEntry(entry HostContinuityEntry) (HostContinuityEntr
entry.DisplayName = strings.TrimSpace(entry.DisplayName)
entry.MachineID = strings.TrimSpace(entry.MachineID)
entry.TokenID = strings.TrimSpace(entry.TokenID)
+ entry.DeniedTokenIDs = uniqueTrimmedStrings(entry.DeniedTokenIDs...)
+ sort.Strings(entry.DeniedTokenIDs)
entry.AgentVersion = strings.TrimSpace(entry.AgentVersion)
entry.Platform = strings.TrimSpace(entry.Platform)
entry.LinkedNodeID = strings.TrimSpace(entry.LinkedNodeID)
@@ -94,9 +102,33 @@ func normalizeHostContinuityEntry(entry HostContinuityEntry) (HostContinuityEntr
if entry.ReportStreamID == "" {
entry.ReportSequence = 0
}
+ if !entry.LastSeen.IsZero() {
+ entry.LastSeen = entry.LastSeen.UTC()
+ }
+ if !entry.ReportObservedAt.IsZero() {
+ entry.ReportObservedAt = entry.ReportObservedAt.UTC()
+ }
+ if !entry.ReportLastReceivedAt.IsZero() {
+ entry.ReportLastReceivedAt = entry.ReportLastReceivedAt.UTC()
+ }
+ if !entry.RemovedAt.IsZero() {
+ entry.RemovedAt = entry.RemovedAt.UTC()
+ }
return entry, true
}
+// LoadError returns the error observed while loading the continuity journal.
+// Once removal tombstones are present this journal is security-sensitive:
+// callers must not silently start with an empty blocklist when it is unreadable.
+func (s *HostContinuityStore) LoadError() error {
+ if s == nil {
+ return nil
+ }
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.loadErr
+}
+
func (s *HostContinuityStore) Load() error {
filePath := filepath.Join(s.dataPath, "host_continuity.json")
@@ -122,6 +154,7 @@ func (s *HostContinuityStore) Load() error {
s.mu.Lock()
s.entries = normalized
+ s.loadErr = nil
s.mu.Unlock()
return nil
}
@@ -145,8 +178,17 @@ func (s *HostContinuityStore) Upsert(entry HostContinuityEntry) error {
s.mu.Lock()
defer s.mu.Unlock()
+ previous, existed := s.entries[normalized.HostID]
s.entries[normalized.HostID] = normalized
- return s.save()
+ if err := s.save(); err != nil {
+ if existed {
+ s.entries[normalized.HostID] = previous
+ } else {
+ delete(s.entries, normalized.HostID)
+ }
+ return err
+ }
+ return nil
}
func (s *HostContinuityStore) Delete(hostID string) error {
@@ -157,8 +199,51 @@ func (s *HostContinuityStore) Delete(hostID string) error {
s.mu.Lock()
defer s.mu.Unlock()
+ previous, existed := s.entries[hostID]
delete(s.entries, hostID)
- return s.save()
+ if err := s.save(); err != nil {
+ if existed {
+ s.entries[hostID] = previous
+ }
+ return err
+ }
+ return nil
+}
+
+// ClearRemoval atomically converts a tombstone back into an active continuity
+// entry. The identity metadata is retained so an explicitly re-enrolled agent
+// keeps its canonical host ID across the transition.
+func (s *HostContinuityStore) ClearRemoval(
+ hostID string,
+ replacementTokenID string,
+ clearDeniedTokens bool,
+) (bool, error) {
+ hostID = strings.TrimSpace(hostID)
+ if hostID == "" {
+ return false, nil
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ entry, ok := s.entries[hostID]
+ if !ok || entry.RemovedAt.IsZero() {
+ return false, nil
+ }
+ previous := entry
+ entry.RemovedAt = time.Time{}
+ if replacementTokenID = strings.TrimSpace(replacementTokenID); replacementTokenID != "" {
+ entry.TokenID = replacementTokenID
+ }
+ if clearDeniedTokens {
+ entry.DeniedTokenIDs = nil
+ }
+ s.entries[hostID] = entry
+ if err := s.save(); err != nil {
+ s.entries[hostID] = previous
+ return false, err
+ }
+ return true, nil
}
func (s *HostContinuityStore) Get(hostID string) (HostContinuityEntry, bool) {
@@ -179,6 +264,9 @@ func (s *HostContinuityStore) RecentEntries(since time.Time) []HostContinuityEnt
out := make([]HostContinuityEntry, 0, len(s.entries))
for _, entry := range s.entries {
+ if !entry.RemovedAt.IsZero() {
+ continue
+ }
if !since.IsZero() && entry.LastSeen.Before(since) {
continue
}
@@ -193,6 +281,27 @@ func (s *HostContinuityStore) RecentEntries(since time.Time) []HostContinuityEnt
return out
}
+// RemovedEntries returns all persisted removal tombstones, newest first.
+func (s *HostContinuityStore) RemovedEntries() []HostContinuityEntry {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ out := make([]HostContinuityEntry, 0, len(s.entries))
+ for _, entry := range s.entries {
+ if entry.RemovedAt.IsZero() {
+ continue
+ }
+ out = append(out, entry)
+ }
+ sort.Slice(out, func(i, j int) bool {
+ if out[i].RemovedAt.Equal(out[j].RemovedAt) {
+ return out[i].HostID < out[j].HostID
+ }
+ return out[i].RemovedAt.After(out[j].RemovedAt)
+ })
+ return out
+}
+
func (s *HostContinuityStore) Match(
reportHostID string,
machineID string,
@@ -212,16 +321,19 @@ func (s *HostContinuityStore) Match(
matched := false
for _, entry := range s.entries {
+ if !entry.RemovedAt.IsZero() {
+ continue
+ }
if !since.IsZero() && entry.LastSeen.Before(since) {
continue
}
matchedByAlias := false
for _, candidate := range candidates {
- if entry.HostID == candidate ||
- entry.ReportHostID == candidate ||
- entry.MachineID == candidate ||
- entry.AgentReportedID == candidate {
+ if hostContinuityIdentityMatches(entry.HostID, candidate) ||
+ hostContinuityIdentityMatches(entry.ReportHostID, candidate) ||
+ hostContinuityIdentityMatches(entry.MachineID, candidate) ||
+ hostContinuityIdentityMatches(entry.AgentReportedID, candidate) {
if !matched || entry.LastSeen.After(best.LastSeen) {
best = entry
matched = true
@@ -249,6 +361,12 @@ func (s *HostContinuityStore) Match(
return best, matched
}
+func hostContinuityIdentityMatches(left, right string) bool {
+ left = strings.TrimSpace(left)
+ right = strings.TrimSpace(right)
+ return left != "" && right != "" && strings.EqualFold(left, right)
+}
+
func hostContinuityHostnameMatches(left, right string) bool {
left = strings.TrimSpace(left)
right = strings.TrimSpace(right)
diff --git a/internal/config/host_continuity_test.go b/internal/config/host_continuity_test.go
index 2503d89dcd..241e501682 100644
--- a/internal/config/host_continuity_test.go
+++ b/internal/config/host_continuity_test.go
@@ -1,6 +1,9 @@
package config
import (
+ "errors"
+ "os"
+ "path/filepath"
"testing"
"time"
)
@@ -51,6 +54,11 @@ func TestHostContinuityStoreRoundTripAndMatch(t *testing.T) {
} else if entry.HostID != "host-1" {
t.Fatalf("matched host ID = %q, want %q", entry.HostID, "host-1")
}
+ if entry, ok := reloaded.Match("MACHINE-1", "", "", "", "", now.Add(-time.Minute)); !ok {
+ t.Fatal("expected machine identity aliases to match case-insensitively")
+ } else if entry.HostID != "host-1" {
+ t.Fatalf("case-insensitive alias matched host ID = %q, want %q", entry.HostID, "host-1")
+ }
if entry, ok := reloaded.Match("", "", "", "host-1.local", "token-1", now.Add(-time.Minute)); !ok {
t.Fatal("expected match by hostname and token")
@@ -95,3 +103,148 @@ func TestHostContinuityStoreRecentEntriesFiltersStaleState(t *testing.T) {
t.Fatalf("RecentEntries[0].HostID = %q, want %q", recent[0].HostID, "host-new")
}
}
+
+func TestHostContinuityStoreRemovalTombstoneRoundTrip(t *testing.T) {
+ dir := t.TempDir()
+ store := NewHostContinuityStore(dir, nil)
+ now := time.Now().UTC().Truncate(time.Second)
+
+ entry := HostContinuityEntry{
+ HostID: "host-removed",
+ ReportHostID: "systemd-machine-id",
+ AgentReportedID: "persisted-agent-id",
+ Hostname: "removed.local",
+ MachineID: "systemd-machine-id",
+ TokenID: "old-token",
+ DeniedTokenIDs: []string{"old-token"},
+ LastSeen: now.Add(-time.Minute),
+ RemovedAt: now,
+ }
+ if err := store.Upsert(entry); err != nil {
+ t.Fatalf("Upsert tombstone: %v", err)
+ }
+
+ reloaded := NewHostContinuityStore(dir, nil)
+ if err := reloaded.LoadError(); err != nil {
+ t.Fatalf("LoadError: %v", err)
+ }
+ removed := reloaded.RemovedEntries()
+ if len(removed) != 1 || removed[0].HostID != entry.HostID || !removed[0].RemovedAt.Equal(now) {
+ t.Fatalf("RemovedEntries = %+v, want tombstone for %q at %v", removed, entry.HostID, now)
+ }
+ if got := reloaded.RecentEntries(time.Time{}); len(got) != 0 {
+ t.Fatalf("RecentEntries included tombstone: %+v", got)
+ }
+ if _, ok := reloaded.Match(entry.ReportHostID, entry.MachineID, entry.AgentReportedID, entry.Hostname, entry.TokenID, time.Time{}); ok {
+ t.Fatal("Match returned a removal tombstone as active continuity")
+ }
+
+ cleared, err := reloaded.ClearRemoval(entry.HostID, "fresh-token", false)
+ if err != nil {
+ t.Fatalf("ClearRemoval: %v", err)
+ }
+ if !cleared {
+ t.Fatal("ClearRemoval reported no tombstone")
+ }
+ if got := NewHostContinuityStore(dir, nil).RemovedEntries(); len(got) != 0 {
+ t.Fatalf("tombstone survived ClearRemoval: %+v", got)
+ }
+ if active := reloaded.RecentEntries(time.Time{}); len(active) != 1 || active[0].HostID != entry.HostID {
+ t.Fatalf("active continuity after ClearRemoval = %+v", active)
+ } else if active[0].TokenID != "fresh-token" ||
+ len(active[0].DeniedTokenIDs) != 1 ||
+ active[0].DeniedTokenIDs[0] != "old-token" {
+ t.Fatalf("ClearRemoval lost token lineage: %+v", active[0])
+ }
+
+ if err := reloaded.Upsert(entry); err != nil {
+ t.Fatalf("restore tombstone for manual allowance: %v", err)
+ }
+ if cleared, err := reloaded.ClearRemoval(entry.HostID, "", true); err != nil || !cleared {
+ t.Fatalf("manual ClearRemoval = (%v, %v)", cleared, err)
+ }
+ if active := reloaded.RecentEntries(time.Time{}); len(active) != 1 || len(active[0].DeniedTokenIDs) != 0 {
+ t.Fatalf("manual ClearRemoval retained denied token lineage: %+v", active)
+ }
+}
+
+func TestHostContinuityStoreLoadsLegacyEntryWithoutRemoval(t *testing.T) {
+ dir := t.TempDir()
+ legacy := []byte(`{"legacy-host":{"hostId":"legacy-host","hostname":"legacy.local","lastSeen":"2026-07-01T12:00:00Z"}}`)
+ if err := os.WriteFile(filepath.Join(dir, "host_continuity.json"), legacy, 0o600); err != nil {
+ t.Fatalf("write legacy continuity: %v", err)
+ }
+
+ store := NewHostContinuityStore(dir, nil)
+ if err := store.LoadError(); err != nil {
+ t.Fatalf("LoadError: %v", err)
+ }
+ if got := store.RemovedEntries(); len(got) != 0 {
+ t.Fatalf("legacy entry migrated as removed: %+v", got)
+ }
+ if got := store.RecentEntries(time.Time{}); len(got) != 1 || got[0].HostID != "legacy-host" {
+ t.Fatalf("legacy active continuity = %+v", got)
+ }
+}
+
+func TestHostContinuityStoreMutationsRollbackWhenPersistenceFails(t *testing.T) {
+ dir := t.TempDir()
+ store := NewHostContinuityStore(dir, nil)
+ original := HostContinuityEntry{
+ HostID: "host-rollback",
+ Hostname: "rollback.local",
+ LastSeen: time.Now().UTC().Truncate(time.Second),
+ }
+ if err := store.Upsert(original); err != nil {
+ t.Fatalf("initial Upsert: %v", err)
+ }
+
+ store.fs = &mockFSError{
+ FileSystem: defaultFileSystem{},
+ writeError: errors.New("write failed"),
+ }
+ tombstone := original
+ tombstone.RemovedAt = time.Now().UTC()
+ if err := store.Upsert(tombstone); err == nil {
+ t.Fatal("Upsert succeeded despite persistence failure")
+ }
+ if got, ok := store.Get(original.HostID); !ok || !got.RemovedAt.IsZero() {
+ t.Fatalf("failed Upsert changed in-memory entry: %+v, ok=%v", got, ok)
+ }
+
+ if err := store.Delete(original.HostID); err == nil {
+ t.Fatal("Delete succeeded despite persistence failure")
+ }
+ if _, ok := store.Get(original.HostID); !ok {
+ t.Fatal("failed Delete removed in-memory entry")
+ }
+
+ store.fs = defaultFileSystem{}
+ if err := store.Upsert(tombstone); err != nil {
+ t.Fatalf("persist tombstone: %v", err)
+ }
+ store.fs = &mockFSError{
+ FileSystem: defaultFileSystem{},
+ writeError: errors.New("write failed"),
+ }
+ if cleared, err := store.ClearRemoval(original.HostID, "fresh-token", false); err == nil || cleared {
+ t.Fatalf("ClearRemoval = (%v, %v), want persistence error", cleared, err)
+ }
+ if got, ok := store.Get(original.HostID); !ok || got.RemovedAt.IsZero() {
+ t.Fatalf("failed ClearRemoval erased in-memory tombstone: %+v, ok=%v", got, ok)
+ }
+}
+
+func TestHostContinuityStoreReportsLoadFailure(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "host_continuity.json"), []byte("{}"), 0o600); err != nil {
+ t.Fatalf("write continuity fixture: %v", err)
+ }
+ store := NewHostContinuityStore(dir, &mockFSError{
+ FileSystem: defaultFileSystem{},
+ readError: errors.New("read failed"),
+ })
+ if err := store.LoadError(); err == nil {
+ t.Fatal("LoadError = nil, want continuity read failure")
+ }
+}
diff --git a/internal/models/models.go b/internal/models/models.go
index 81a592befc..a48be6c0d8 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -919,6 +919,8 @@ type RemovedDockerHost struct {
// RemovedHostAgent tracks a host agent that was deliberately removed and blocked from reporting.
type RemovedHostAgent struct {
ID string `json:"id"`
+ ReportHostID string `json:"reportHostId,omitempty"`
+ AgentReportedID string `json:"agentReportedId,omitempty"`
Hostname string `json:"hostname,omitempty"`
DisplayName string `json:"displayName,omitempty"`
Platform string `json:"platform,omitempty"` // last-known reported platform, retained for host-side cleanup guidance
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index e09f48c3cb..a30317ab34 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -686,7 +686,8 @@ func TestMonitoredSystemUsageReadinessGuardrailsRemainCanonical(t *testing.T) {
"type MonitorSupplementalInventoryReadinessProvider interface {",
"SupplementalInventoryReadyAt(m *Monitor, orgID string) (time.Time, bool)",
"hostContinuityStore *config.HostContinuityStore",
- "hostContinuityStore: config.NewHostContinuityStore(cfg.DataPath, nil),",
+ "hostContinuityStore := config.NewHostContinuityStore(cfg.DataPath, nil)",
+ "hostContinuityStore: hostContinuityStore,",
"func (m *Monitor) HostsSnapshot() []models.Host {",
"readState = m.readStateWithStandaloneHostContinuity(readState)",
"func (m *Monitor) unifiedStateViewWithStandaloneHostContinuity(view monitorUnifiedStateView) monitorUnifiedStateView {",
@@ -2241,7 +2242,8 @@ func TestHostAgentRemovalGuardUsesResolvedIdentifier(t *testing.T) {
}
source := string(data)
requiredSnippets := []string{
- "blockedID, removedAt, wasRemoved := m.lookupRemovedHostAgent(identifier, hostname, report.Host.MachineID, tokenID)",
+ "blocked, wasRemoved := m.lookupRemovedHostAgent(identifier, hostname, report.Host.MachineID, tokenID)",
+ "removedHostAgentAllowsFreshReenroll(blocked, identifier, report, tokenRecord)",
"func removedHostAgentMatchesReport(entry models.RemovedHostAgent, identifier, hostname, machineID, tokenID string) bool {",
"entryTokenID == \"\" || tokenID == \"\" || entryTokenID != tokenID",
`Str("hostID", identifier)`,
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 4de81e74a4..b1a8ba49d9 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -1096,6 +1096,7 @@ type Monitor struct {
dockerMetadataStore *config.DockerMetadataStore
hostMetadataStore *config.HostMetadataStore
hostContinuityStore *config.HostContinuityStore
+ hostAgentLifecycleMu sync.RWMutex
mu sync.RWMutex
startTime time.Time
rateTracker *RateTracker
@@ -1522,6 +1523,11 @@ func New(cfg *config.Config) (*Monitor, error) {
return nil, fmt.Errorf("config cannot be nil")
}
+ hostContinuityStore := config.NewHostContinuityStore(cfg.DataPath, nil)
+ if err := hostContinuityStore.LoadError(); err != nil {
+ return nil, fmt.Errorf("load host continuity lifecycle journal: %w", err)
+ }
+
// Initialize temperature collector with sensors SSH key
// Will use root user for now - can be made configurable later
homeDir := os.Getenv("HOME")
@@ -1670,7 +1676,7 @@ func New(cfg *config.Config) (*Monitor, error) {
guestMetadataStore: config.NewGuestMetadataStore(cfg.DataPath, nil),
dockerMetadataStore: config.NewDockerMetadataStore(cfg.DataPath, nil),
hostMetadataStore: config.NewHostMetadataStore(cfg.DataPath, nil),
- hostContinuityStore: config.NewHostContinuityStore(cfg.DataPath, nil),
+ hostContinuityStore: hostContinuityStore,
startTime: time.Now(),
rateTracker: NewRateTracker(),
metricsHistory: NewMetricsHistory(1000, 24*time.Hour), // Keep up to 1000 points (~8h @ 30s)
@@ -1740,6 +1746,7 @@ func New(cfg *config.Config) (*Monitor, error) {
}
m.executor = newRealExecutor(m)
+ m.hydrateRemovedHostAgents(time.Now().UTC())
m.alertManager.SetBackupIntentContextResolver(m.resolveBackupIntentContext)
m.registerBuiltInPollProviders()
m.buildInstanceInfoCache(cfg)
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index a5857748ed..44574ae8c4 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -268,17 +268,52 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
return models.Host{}, fmt.Errorf("host id is required")
}
+ m.hostAgentLifecycleMu.Lock()
+ defer m.hostAgentLifecycleMu.Unlock()
+
+ continuity, hasContinuity := config.HostContinuityEntry{}, false
+ if m.hostContinuityStore != nil {
+ continuity, hasContinuity = m.hostContinuityStore.Get(hostID)
+ }
+
host, removed := m.state.RemoveHost(hostID)
if !removed {
if logging.IsLevelEnabled(zerolog.DebugLevel) {
log.Debug().Str("hostID", hostID).Msg("host not present in state during removal")
}
- host = models.Host{
- ID: hostID,
- Hostname: hostID,
+ if hasContinuity {
+ host = hostFromContinuityEntry(continuity)
+ } else {
+ host = models.Host{
+ ID: hostID,
+ Hostname: hostID,
+ }
+ }
+ }
+
+ removedAt := time.Now().UTC()
+ if !continuity.RemovedAt.IsZero() {
+ removedAt = continuity.RemovedAt.UTC()
+ }
+ tombstone := removedHostContinuityEntry(hostID, host, continuity, removedAt)
+ if m.hostContinuityStore != nil {
+ if err := m.hostContinuityStore.Upsert(tombstone); err != nil {
+ if removed {
+ m.state.UpsertHost(host)
+ }
+ return models.Host{}, fmt.Errorf("persist host agent removal tombstone: %w", err)
}
}
+ removedEntry := removedHostAgentFromContinuity(tombstone)
+ m.mu.Lock()
+ if m.removedHostAgents == nil {
+ m.removedHostAgents = make(map[string]time.Time)
+ }
+ m.removedHostAgents[hostID] = removedAt
+ m.mu.Unlock()
+ m.state.AddRemovedHostAgent(removedEntry)
+
tokenID := strings.TrimSpace(host.TokenID)
hostname := strings.TrimSpace(host.Hostname)
@@ -369,26 +404,6 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
Msg("Unbound host agent token bindings after host removal")
}
- removedAt := time.Now()
- m.mu.Lock()
- if m.removedHostAgents == nil {
- m.removedHostAgents = make(map[string]time.Time)
- }
- m.removedHostAgents[hostID] = removedAt
- m.mu.Unlock()
-
- m.state.AddRemovedHostAgent(models.RemovedHostAgent{
- ID: hostID,
- Hostname: host.Hostname,
- DisplayName: host.DisplayName,
- Platform: firstNonEmpty(host.Platform, host.OSName),
- MachineID: host.MachineID,
- TokenID: host.TokenID,
- LinkedVMID: host.LinkedVMID,
- LinkedContainerID: host.LinkedContainerID,
- RemovedAt: removedAt,
- })
-
m.state.RemoveConnectionHealth(hostConnectionPrefix + hostID)
// Clear LinkedAgentID from any nodes that were linked to this host agent
@@ -409,7 +424,6 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
if m.alertManager != nil {
m.alertManager.HandleHostRemoved(host)
}
- m.removeHostContinuity(hostID)
m.hostReportOrderMu.Lock()
delete(m.hostReportOrders, hostID)
m.hostReportOrderMu.Unlock()
@@ -417,6 +431,49 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
return host, nil
}
+func removedHostContinuityEntry(
+ hostID string,
+ host models.Host,
+ continuity config.HostContinuityEntry,
+ removedAt time.Time,
+) config.HostContinuityEntry {
+ continuity.HostID = strings.TrimSpace(hostID)
+ continuity.Hostname = firstNonEmpty(continuity.Hostname, host.Hostname)
+ continuity.DisplayName = firstNonEmpty(continuity.DisplayName, host.DisplayName)
+ continuity.MachineID = firstNonEmpty(continuity.MachineID, host.MachineID)
+ continuity.TokenID = firstNonEmpty(continuity.TokenID, host.TokenID)
+ continuity.DeniedTokenIDs = uniqueNonEmptyStrings(
+ append(continuity.DeniedTokenIDs, continuity.TokenID, host.TokenID)...,
+ )
+ continuity.AgentVersion = firstNonEmpty(continuity.AgentVersion, host.AgentVersion)
+ continuity.Platform = firstNonEmpty(continuity.Platform, host.Platform, host.OSName)
+ continuity.LinkedNodeID = firstNonEmpty(continuity.LinkedNodeID, host.LinkedNodeID)
+ continuity.LinkedVMID = firstNonEmpty(continuity.LinkedVMID, host.LinkedVMID)
+ continuity.LinkedContainerID = firstNonEmpty(continuity.LinkedContainerID, host.LinkedContainerID)
+ continuity.IsLegacy = continuity.IsLegacy || host.IsLegacy
+ if continuity.LastSeen.IsZero() {
+ continuity.LastSeen = host.LastSeen.UTC()
+ }
+ continuity.RemovedAt = removedAt.UTC()
+ return continuity
+}
+
+func removedHostAgentFromContinuity(entry config.HostContinuityEntry) models.RemovedHostAgent {
+ return models.RemovedHostAgent{
+ ID: strings.TrimSpace(entry.HostID),
+ ReportHostID: strings.TrimSpace(entry.ReportHostID),
+ AgentReportedID: strings.TrimSpace(entry.AgentReportedID),
+ Hostname: strings.TrimSpace(entry.Hostname),
+ DisplayName: strings.TrimSpace(entry.DisplayName),
+ Platform: strings.TrimSpace(entry.Platform),
+ MachineID: strings.TrimSpace(entry.MachineID),
+ TokenID: strings.TrimSpace(entry.TokenID),
+ LinkedVMID: strings.TrimSpace(entry.LinkedVMID),
+ LinkedContainerID: strings.TrimSpace(entry.LinkedContainerID),
+ RemovedAt: entry.RemovedAt.UTC(),
+ }
+}
+
// AllowHostAgentReenroll removes a host agent ID from the removal blocklist so it can report again.
func (m *Monitor) AllowHostAgentReenroll(hostID string) error {
hostID = strings.TrimSpace(hostID)
@@ -424,6 +481,27 @@ func (m *Monitor) AllowHostAgentReenroll(hostID string) error {
return fmt.Errorf("host id is required")
}
+ m.hostAgentLifecycleMu.Lock()
+ defer m.hostAgentLifecycleMu.Unlock()
+ _, err := m.allowHostAgentReenrollLocked(hostID, "", true)
+ return err
+}
+
+func (m *Monitor) allowHostAgentReenrollLocked(
+ hostID string,
+ replacementTokenID string,
+ clearDeniedTokens bool,
+) (bool, error) {
+ hasDurableStore := m.hostContinuityStore != nil
+ existsOnDisk := false
+ if hasDurableStore {
+ cleared, err := m.hostContinuityStore.ClearRemoval(hostID, replacementTokenID, clearDeniedTokens)
+ if err != nil {
+ return false, fmt.Errorf("persist host agent re-enrollment allowance: %w", err)
+ }
+ existsOnDisk = cleared
+ }
+
m.mu.Lock()
if m.removedHostAgents == nil {
m.removedHostAgents = make(map[string]time.Time)
@@ -432,9 +510,6 @@ func (m *Monitor) AllowHostAgentReenroll(hostID string) error {
delete(m.removedHostAgents, hostID)
m.mu.Unlock()
- // The in-memory map resets on restart while the persisted entry keeps
- // blocking reports, so the persisted store must be checked and cleared
- // independently of memory presence (#1581).
existsInState := false
for _, entry := range m.state.GetRemovedHostAgents() {
if strings.TrimSpace(entry.ID) == hostID {
@@ -443,11 +518,15 @@ func (m *Monitor) AllowHostAgentReenroll(hostID string) error {
}
}
- if !existsInMemory && !existsInState {
+ transitioned := existsOnDisk
+ if !hasDurableStore {
+ transitioned = existsInMemory || existsInState
+ }
+ if !transitioned {
log.Info().
Str("hostID", hostID).
Msg("allow re-enroll requested but host agent was not blocked; ignoring")
- return nil
+ return false, nil
}
m.state.RemoveRemovedHostAgent(hostID)
@@ -456,33 +535,38 @@ func (m *Monitor) AllowHostAgentReenroll(hostID string) error {
Str("hostID", hostID).
Msg("Host agent removal block cleared; host may report again")
- return nil
+ return transitioned, nil
}
-func (m *Monitor) lookupRemovedHostAgent(identifier, hostname, machineID, tokenID string) (string, time.Time, bool) {
+func (m *Monitor) lookupRemovedHostAgent(identifier, hostname, machineID, tokenID string) (models.RemovedHostAgent, bool) {
identifier = strings.TrimSpace(identifier)
machineID = sanitizeDockerHostSuffix(machineID)
tokenID = strings.TrimSpace(tokenID)
+ for _, entry := range m.state.GetRemovedHostAgents() {
+ if removedHostAgentMatchesReport(entry, identifier, hostname, machineID, tokenID) {
+ return entry, true
+ }
+ }
+
m.mu.RLock()
removedAt, wasRemoved := m.removedHostAgents[identifier]
m.mu.RUnlock()
if wasRemoved {
- return identifier, removedAt, true
- }
-
- for _, entry := range m.state.GetRemovedHostAgents() {
- if removedHostAgentMatchesReport(entry, identifier, hostname, machineID, tokenID) {
- return strings.TrimSpace(entry.ID), entry.RemovedAt, true
- }
+ return models.RemovedHostAgent{
+ ID: identifier,
+ RemovedAt: removedAt,
+ }, true
}
- return "", time.Time{}, false
+ return models.RemovedHostAgent{}, false
}
func removedHostAgentMatchesReport(entry models.RemovedHostAgent, identifier, hostname, machineID, tokenID string) bool {
- if strings.TrimSpace(entry.ID) == strings.TrimSpace(identifier) {
- return true
+ for _, persistedID := range []string{entry.ID, entry.ReportHostID, entry.AgentReportedID} {
+ if hostAgentIdentifiersMatch(persistedID, identifier) {
+ return true
+ }
}
entryMachineID := sanitizeDockerHostSuffix(entry.MachineID)
@@ -506,6 +590,67 @@ func removedHostAgentMatchesReport(entry models.RemovedHostAgent, identifier, ho
hostAgentHostnamesMatch(entry.Hostname, hostname)
}
+func removedHostAgentAllowsFreshReenroll(
+ entry models.RemovedHostAgent,
+ identifier string,
+ report agentshost.Report,
+ tokenRecord *config.APITokenRecord,
+) bool {
+ if tokenRecord == nil ||
+ tokenRecord.CreatedAt.IsZero() ||
+ !tokenRecord.CreatedAt.After(entry.RemovedAt) {
+ return false
+ }
+
+ oldTokenID := strings.TrimSpace(entry.TokenID)
+ newTokenID := strings.TrimSpace(tokenRecord.ID)
+ if newTokenID == "" || (oldTokenID != "" && oldTokenID == newTokenID) {
+ return false
+ }
+
+ hostname := strings.TrimSpace(report.Host.Hostname)
+ if strings.TrimSpace(entry.Hostname) != "" &&
+ hostname != "" &&
+ !hostAgentHostnamesMatch(entry.Hostname, hostname) {
+ return false
+ }
+
+ entryMachineID := sanitizeDockerHostSuffix(entry.MachineID)
+ reportMachineID := sanitizeDockerHostSuffix(report.Host.MachineID)
+ if entryMachineID != "" && reportMachineID != "" && !hostAgentIdentifiersMatch(entryMachineID, reportMachineID) {
+ return false
+ }
+
+ persistedIDs := []string{
+ entry.ID,
+ entry.ReportHostID,
+ entry.AgentReportedID,
+ entry.MachineID,
+ }
+ reportedIDs := []string{
+ identifier,
+ report.Host.ID,
+ report.Host.MachineID,
+ report.Agent.ID,
+ }
+ for _, persistedID := range persistedIDs {
+ for _, reportedID := range reportedIDs {
+ if hostAgentIdentifiersMatch(persistedID, reportedID) {
+ return true
+ }
+ }
+ }
+ return entryMachineID != "" &&
+ reportMachineID != "" &&
+ hostAgentIdentifiersMatch(entryMachineID, reportMachineID)
+}
+
+func hostAgentIdentifiersMatch(left, right string) bool {
+ left = sanitizeDockerHostSuffix(left)
+ right = sanitizeDockerHostSuffix(right)
+ return left != "" && right != "" && strings.EqualFold(left, right)
+}
+
// LinkHostAgent manually links a host agent to a specific PVE node.
// This is used when auto-linking can't disambiguate (e.g., multiple nodes with hostname "pve").
// After linking, the host agent's temperature/sensor data will appear on the correct node.
@@ -1016,6 +1161,25 @@ func (m *Monitor) matchPersistedHostContinuity(
)
}
+func hostContinuityDeniesToken(
+ entry config.HostContinuityEntry,
+ tokenRecord *config.APITokenRecord,
+) bool {
+ if tokenRecord == nil {
+ return false
+ }
+ tokenID := strings.TrimSpace(tokenRecord.ID)
+ if tokenID == "" {
+ return false
+ }
+ for _, deniedTokenID := range entry.DeniedTokenIDs {
+ if strings.TrimSpace(deniedTokenID) == tokenID {
+ return true
+ }
+ }
+ return false
+}
+
// MatchHostConfigContinuity resolves a host identity for agent config fetches
// from the persisted continuity store. Live state loses agent-reported hosts
// across monitor reloads and restarts until the next report lands, and config
@@ -1036,7 +1200,10 @@ func (m *Monitor) MatchHostConfigContinuity(agentID, tokenID string) (models.Hos
continue
}
} else if agentID == "" ||
- (entry.HostID != agentID && entry.ReportHostID != agentID && entry.AgentReportedID != agentID) {
+ (!hostAgentIdentifiersMatch(entry.HostID, agentID) &&
+ !hostAgentIdentifiersMatch(entry.ReportHostID, agentID) &&
+ !hostAgentIdentifiersMatch(entry.AgentReportedID, agentID) &&
+ !hostAgentIdentifiersMatch(entry.MachineID, agentID)) {
continue
}
return models.Host{
@@ -1083,6 +1250,9 @@ func (m *Monitor) persistHostContinuity(host models.Host, report agentshost.Repo
order.RetiredStreamIDs...,
),
}
+ if previous, ok := m.hostContinuityStore.Get(entry.HostID); ok {
+ entry.DeniedTokenIDs = append([]string(nil), previous.DeniedTokenIDs...)
+ }
if err := m.hostContinuityStore.Upsert(entry); err != nil {
log.Warn().
Err(err).
@@ -1148,18 +1318,6 @@ func (m *Monitor) applyRejectedHostReportLiveness(
return host
}
-func (m *Monitor) removeHostContinuity(hostID string) {
- if m == nil || m.hostContinuityStore == nil {
- return
- }
- if err := m.hostContinuityStore.Delete(hostID); err != nil {
- log.Warn().
- Err(err).
- Str("hostID", hostID).
- Msg("failed to delete host continuity state")
- }
-}
-
// HostReportMatchesKnownIdentity returns true when a host report targets either
// the live host snapshot or a recent persisted standalone-host continuity
// record.
@@ -2016,6 +2174,9 @@ func normalizedSecurityStrings(values []string) []string {
// ApplyHostReport ingests a host agent report into the shared state.
func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.APITokenRecord) (models.Host, error) {
+ m.hostAgentLifecycleMu.RLock()
+ defer m.hostAgentLifecycleMu.RUnlock()
+
receivedAt := time.Now()
observedAt := receivedAt.UTC()
@@ -2057,6 +2218,13 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
baseIdentifier = fmt.Sprintf("agent-%s", hex.EncodeToString(sum[:6]))
}
if persisted, ok := m.matchPersistedHostContinuity(report, tokenRecord); ok {
+ if hostContinuityDeniesToken(persisted, tokenRecord) {
+ return models.Host{}, fmt.Errorf(
+ "API token %q was explicitly detached from host agent %q during removal and cannot report for that identity",
+ strings.TrimSpace(tokenRecord.ID),
+ strings.TrimSpace(persisted.HostID),
+ )
+ }
baseIdentifier = strings.TrimSpace(persisted.HostID)
}
@@ -2134,29 +2302,48 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
if tokenRecord != nil {
tokenID = strings.TrimSpace(tokenRecord.ID)
}
- blockedID, removedAt, wasRemoved := m.lookupRemovedHostAgent(identifier, hostname, report.Host.MachineID, tokenID)
- if wasRemoved && tokenRecord != nil && !tokenRecord.CreatedAt.IsZero() && tokenRecord.CreatedAt.After(removedAt) {
+ blocked, wasRemoved := m.lookupRemovedHostAgent(identifier, hostname, report.Host.MachineID, tokenID)
+ if wasRemoved && removedHostAgentAllowsFreshReenroll(blocked, identifier, report, tokenRecord) {
// A token minted after the host was removed means the user generated a
// fresh install command for this machine: that is explicit re-enroll
// intent, so clear the block instead of rejecting until the TTL
// expires. A still-running old agent keeps presenting its pre-removal
// token and stays blocked (#1581).
- if err := m.AllowHostAgentReenroll(blockedID); err == nil {
+ cleared, err := m.allowHostAgentReenrollLocked(blocked.ID, tokenID, false)
+ if err == nil && cleared {
+ identifier = strings.TrimSpace(blocked.ID)
+ if tokenID != "" {
+ m.mu.Lock()
+ if m.hostTokenBindings == nil {
+ m.hostTokenBindings = make(map[string]string)
+ }
+ m.hostTokenBindings[hostTokenBindingKey(tokenID, hostname)] = identifier
+ m.mu.Unlock()
+ }
log.Info().
Str("hostID", identifier).
- Str("blockedID", blockedID).
- Time("removedAt", removedAt).
+ Str("blockedID", blocked.ID).
+ Time("removedAt", blocked.RemovedAt).
Time("tokenCreatedAt", tokenRecord.CreatedAt).
Msg("Cleared host agent removal block: report presented a token created after removal")
wasRemoved = false
+ } else if err != nil {
+ log.Warn().
+ Err(err).
+ Str("blockedID", blocked.ID).
+ Msg("Failed to persist host agent re-enrollment allowance; report remains blocked")
+ } else {
+ log.Info().
+ Str("blockedID", blocked.ID).
+ Msg("Host agent re-enrollment transition was already consumed; report remains blocked")
}
}
if wasRemoved {
log.Info().
Str("hostID", identifier).
- Time("removedAt", removedAt).
+ Time("removedAt", blocked.RemovedAt).
Msg("Rejecting report from deliberately removed host agent")
- return models.Host{}, fmt.Errorf("host agent %q had monitoring stopped at %v and cannot report again. Re-enroll by reinstalling the agent with a newly generated API token, or wait for the block to clear 24 hours after removal", identifier, removedAt.Format(time.RFC3339))
+ return models.Host{}, fmt.Errorf("host agent %q had monitoring stopped at %v and cannot report again. Re-enroll by reinstalling the agent with a newly generated API token, or wait for the block to clear 24 hours after removal", identifier, blocked.RemovedAt.Format(time.RFC3339))
}
unlockHostReport := m.lockHostReportApplication(identifier)
@@ -3353,12 +3540,44 @@ func (m *Monitor) cleanupRemovedDockerHosts(now time.Time) {
}
}
-// cleanupRemovedHostAgents expires removed host-agent blocks older than 24 hours.
-// The persisted entries must be swept by their own RemovedAt, not via the
-// in-memory map: the map resets on restart while lookupRemovedHostAgent keeps
-// matching persisted entries, which made a deleted host's block immortal and
-// permanently rejected its agent's re-enrollment (#1581).
+// hydrateRemovedHostAgents restores durable removal tombstones before the
+// monitor accepts reports. Expired tombstones are deleted eagerly; if that
+// delete cannot be persisted, the block is retained in memory to fail closed.
+func (m *Monitor) hydrateRemovedHostAgents(now time.Time) {
+ if m == nil || m.hostContinuityStore == nil || m.state == nil {
+ return
+ }
+
+ for _, continuity := range m.hostContinuityStore.RemovedEntries() {
+ if now.Sub(continuity.RemovedAt) > removedHostAgentsTTL {
+ if err := m.hostContinuityStore.Delete(continuity.HostID); err == nil {
+ continue
+ } else {
+ log.Warn().
+ Err(err).
+ Str("hostID", continuity.HostID).
+ Msg("Failed to expire durable host-agent removal tombstone; retaining block")
+ }
+ }
+
+ entry := removedHostAgentFromContinuity(continuity)
+ m.state.AddRemovedHostAgent(entry)
+ m.mu.Lock()
+ if m.removedHostAgents == nil {
+ m.removedHostAgents = make(map[string]time.Time)
+ }
+ m.removedHostAgents[entry.ID] = entry.RemovedAt
+ m.mu.Unlock()
+ }
+}
+
+// cleanupRemovedHostAgents expires removal tombstones older than 24 hours.
+// Durable state is deleted before memory so a persistence failure retains the
+// deny boundary across this process and the next restart.
func (m *Monitor) cleanupRemovedHostAgents(now time.Time) {
+ m.hostAgentLifecycleMu.Lock()
+ defer m.hostAgentLifecycleMu.Unlock()
+
expired := make(map[string]time.Time)
for _, entry := range m.state.GetRemovedHostAgents() {
@@ -3376,6 +3595,18 @@ func (m *Monitor) cleanupRemovedHostAgents(now time.Time) {
m.mu.Unlock()
for hostID, removedAt := range expired {
+ if m.hostContinuityStore != nil {
+ if continuity, ok := m.hostContinuityStore.Get(hostID); ok && !continuity.RemovedAt.IsZero() {
+ if err := m.hostContinuityStore.Delete(hostID); err != nil {
+ log.Warn().
+ Err(err).
+ Str("hostID", hostID).
+ Msg("Failed to expire durable host-agent removal tombstone; retaining block")
+ continue
+ }
+ }
+ }
+
m.state.RemoveRemovedHostAgent(hostID)
m.mu.Lock()
diff --git a/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go b/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go
new file mode 100644
index 0000000000..c3fa53d718
--- /dev/null
+++ b/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go
@@ -0,0 +1,371 @@
+package monitoring
+
+import (
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "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 newHostRemovalLifecycleMonitor(t *testing.T, dataPath string) *Monitor {
+ t.Helper()
+ monitor := &Monitor{
+ state: models.NewState(),
+ alertManager: alerts.NewManager(),
+ hostTokenBindings: make(map[string]string),
+ removedHostAgents: make(map[string]time.Time),
+ rateTracker: NewRateTracker(),
+ config: &config.Config{DataPath: dataPath},
+ hostContinuityStore: config.NewHostContinuityStore(dataPath, nil),
+ }
+ t.Cleanup(func() { monitor.alertManager.Stop() })
+ return monitor
+}
+
+func hostRemovalLifecycleReport(hostID, machineID, agentID, hostname, platform string, at time.Time) agentshost.Report {
+ return agentshost.Report{
+ Host: agentshost.HostInfo{
+ ID: hostID,
+ MachineID: machineID,
+ Hostname: hostname,
+ Platform: platform,
+ },
+ Agent: agentshost.AgentInfo{
+ ID: agentID,
+ Version: "6.1.1",
+ Type: "unified",
+ },
+ Timestamp: at.UTC(),
+ }
+}
+
+func TestHostAgentRemovalLifecycleSameProcessAndPlatformAliases(t *testing.T) {
+ identities := []struct {
+ name string
+ hostID string
+ machineID string
+ agentID string
+ hostname string
+ platform string
+ }{
+ {
+ name: "linux systemd machine id",
+ hostID: "01234567-89ab-cdef-0123-456789abcdef",
+ machineID: "01234567-89ab-cdef-0123-456789abcdef",
+ agentID: "linux-agent-state-id",
+ hostname: "pve-node.local",
+ platform: "linux",
+ },
+ {
+ name: "docker unified identity",
+ hostID: "docker-machine-7",
+ machineID: "docker-machine-7",
+ agentID: "docker-agent-state-id",
+ hostname: "docker-node.local",
+ platform: "linux",
+ },
+ {
+ name: "windows machine guid",
+ hostID: "a12b34c5-d678-49ef-a012-3456789abcde",
+ machineID: "A12B34C5-D678-49EF-A012-3456789ABCDE",
+ agentID: "windows-agent-state-id",
+ hostname: "win-node.corp.local",
+ platform: "windows",
+ },
+ }
+
+ for _, identity := range identities {
+ t.Run(identity.name, func(t *testing.T) {
+ monitor := newHostRemovalLifecycleMonitor(t, t.TempDir())
+ now := time.Now().UTC()
+ oldToken := &config.APITokenRecord{
+ ID: "old-" + identity.agentID,
+ CreatedAt: now.Add(-time.Hour),
+ }
+ report := hostRemovalLifecycleReport(
+ identity.hostID,
+ identity.machineID,
+ identity.agentID,
+ identity.hostname,
+ identity.platform,
+ now,
+ )
+ host, err := monitor.ApplyHostReport(report, oldToken)
+ if err != nil {
+ t.Fatalf("initial ApplyHostReport: %v", err)
+ }
+ if _, err := monitor.RemoveHostAgent(host.ID); err != nil {
+ t.Fatalf("RemoveHostAgent: %v", err)
+ }
+ tombstones := monitor.hostContinuityStore.RemovedEntries()
+ if len(tombstones) != 1 ||
+ len(tombstones[0].DeniedTokenIDs) != 1 ||
+ tombstones[0].DeniedTokenIDs[0] != oldToken.ID {
+ t.Fatalf("removal tombstone token lineage = %+v", tombstones)
+ }
+ if _, err := monitor.ApplyHostReport(report, oldToken); err == nil {
+ t.Fatal("pre-removal token re-enrolled a deliberately removed host")
+ }
+ if _, ok := monitor.MatchHostConfigContinuity(host.ID, oldToken.ID); ok {
+ t.Fatal("removed host remained available through remote-config continuity")
+ }
+
+ aliasReport := report
+ aliasReport.Host.ID = identity.agentID
+ aliasReport.Timestamp = now.Add(2 * time.Minute)
+ freshToken := &config.APITokenRecord{
+ ID: "fresh-" + identity.agentID,
+ CreatedAt: now.Add(time.Minute),
+ }
+ reEnrolled, err := monitor.ApplyHostReport(aliasReport, freshToken)
+ if err != nil {
+ t.Fatalf("fresh-token alias re-enrollment: %v", err)
+ }
+ if reEnrolled.ID != host.ID {
+ t.Fatalf("re-enrolled host ID = %q, want canonical %q", reEnrolled.ID, host.ID)
+ }
+ if got := monitor.hostContinuityStore.RemovedEntries(); len(got) != 0 {
+ t.Fatalf("durable tombstone survived re-enrollment: %+v", got)
+ }
+ if continuity, ok := monitor.MatchHostConfigContinuity(host.ID, freshToken.ID); !ok || continuity.ID != host.ID {
+ t.Fatalf("fresh-token remote-config continuity = (%+v, %v)", continuity, ok)
+ }
+ })
+ }
+}
+
+func TestHostAgentRemovalLifecycleRevokesDedicatedCredentialAndRetainsDenial(t *testing.T) {
+ dataPath := t.TempDir()
+ monitor := newHostRemovalLifecycleMonitor(t, dataPath)
+ monitor.persistence = config.NewConfigPersistence(dataPath)
+
+ now := time.Now().UTC()
+ oldToken := config.APITokenRecord{
+ ID: "dedicated-old-token",
+ Name: "Dedicated host token",
+ CreatedAt: now.Add(-time.Hour),
+ }
+ monitor.config.APITokens = []config.APITokenRecord{oldToken}
+ if err := monitor.persistence.SaveAPITokens(monitor.config.APITokens); err != nil {
+ t.Fatalf("SaveAPITokens: %v", err)
+ }
+
+ report := hostRemovalLifecycleReport(
+ "dedicated-machine-id",
+ "dedicated-machine-id",
+ "dedicated-agent-id",
+ "dedicated.local",
+ "linux",
+ now,
+ )
+ host, err := monitor.ApplyHostReport(report, &oldToken)
+ if err != nil {
+ t.Fatalf("initial ApplyHostReport: %v", err)
+ }
+ if _, err := monitor.RemoveHostAgent(host.ID); err != nil {
+ t.Fatalf("RemoveHostAgent: %v", err)
+ }
+
+ if len(monitor.config.APITokens) != 0 {
+ t.Fatalf("dedicated credential remained in memory: %+v", monitor.config.APITokens)
+ }
+ reloadedTokens, err := monitor.persistence.LoadAPITokens()
+ if err != nil {
+ t.Fatalf("LoadAPITokens: %v", err)
+ }
+ if len(reloadedTokens) != 0 {
+ t.Fatalf("dedicated credential remained on disk: %+v", reloadedTokens)
+ }
+ if _, err := monitor.ApplyHostReport(report, &oldToken); err == nil {
+ t.Fatal("explicitly revoked credential bypassed the durable identity denial")
+ }
+}
+
+func TestHostAgentRemovalLifecycleSurvivesMonitorReconstruction(t *testing.T) {
+ dataPath := t.TempDir()
+ now := time.Now().UTC()
+ oldToken := &config.APITokenRecord{
+ ID: "shared-old-token",
+ CreatedAt: now.Add(-time.Hour),
+ }
+ report := hostRemovalLifecycleReport(
+ "systemd-machine-id",
+ "systemd-machine-id",
+ "persisted-agent-id",
+ "restart-node.local",
+ "linux",
+ now,
+ )
+
+ first := newHostRemovalLifecycleMonitor(t, dataPath)
+ host, err := first.ApplyHostReport(report, oldToken)
+ if err != nil {
+ t.Fatalf("initial ApplyHostReport: %v", err)
+ }
+ if _, err := first.RemoveHostAgent(host.ID); err != nil {
+ t.Fatalf("RemoveHostAgent: %v", err)
+ }
+
+ restarted, err := New(&config.Config{
+ DataPath: dataPath,
+ ConfigPath: dataPath,
+ MetricsDBPath: filepath.Join(
+ dataPath,
+ "restarted-metrics.db",
+ ),
+ })
+ if err != nil {
+ t.Fatalf("New restarted monitor: %v", err)
+ }
+ t.Cleanup(restarted.Stop)
+
+ aliasReport := report
+ aliasReport.Host.ID = report.Agent.ID
+ aliasReport.Timestamp = now.Add(2 * time.Minute)
+ if _, err := restarted.ApplyHostReport(aliasReport, oldToken); err == nil {
+ t.Fatal("restart lost the durable removal deny boundary")
+ }
+ if _, ok := restarted.MatchHostConfigContinuity(host.ID, oldToken.ID); ok {
+ t.Fatal("restart exposed removed host through remote-config continuity")
+ }
+
+ wrongIdentity := aliasReport
+ wrongIdentity.Host.MachineID = "cloned-machine-id"
+ wrongIdentity.Host.Hostname = "different-node.local"
+ wrongIdentity.Timestamp = now.Add(3 * time.Minute)
+ freshToken := &config.APITokenRecord{
+ ID: "fresh-after-restart",
+ CreatedAt: now.Add(time.Minute),
+ }
+ if _, err := restarted.ApplyHostReport(wrongIdentity, freshToken); err == nil {
+ t.Fatal("fresh token cleared a tombstone for a different machine identity")
+ }
+
+ reEnrolled, err := restarted.ApplyHostReport(aliasReport, freshToken)
+ if err != nil {
+ t.Fatalf("fresh-token re-enrollment after restart: %v", err)
+ }
+ if reEnrolled.ID != host.ID {
+ t.Fatalf("re-enrolled host ID = %q, want canonical %q", reEnrolled.ID, host.ID)
+ }
+ aliasReport.Timestamp = now.Add(4 * time.Minute)
+ if _, err := restarted.ApplyHostReport(aliasReport, oldToken); err == nil {
+ t.Fatal("detached old token created a duplicate after fresh-token re-enrollment")
+ }
+ if got := restarted.GetLiveHostsSnapshot(); len(got) != 1 || got[0].ID != host.ID {
+ t.Fatalf("detached old token changed active host inventory: %+v", got)
+ }
+}
+
+func TestHostAgentRemovalLifecycleDoesNotPoisonDuplicateActiveIdentity(t *testing.T) {
+ monitor := newHostRemovalLifecycleMonitor(t, t.TempDir())
+ now := time.Now().UTC()
+ firstReport := hostRemovalLifecycleReport("shared-machine", "shared-machine", "agent-one", "node-one.local", "linux", now)
+ secondReport := hostRemovalLifecycleReport("shared-machine", "shared-machine", "agent-two", "node-two.local", "linux", now)
+ firstToken := &config.APITokenRecord{ID: "token-one", CreatedAt: now.Add(-time.Hour)}
+ secondToken := &config.APITokenRecord{ID: "token-two", CreatedAt: now.Add(-time.Hour)}
+
+ first, err := monitor.ApplyHostReport(firstReport, firstToken)
+ if err != nil {
+ t.Fatalf("first ApplyHostReport: %v", err)
+ }
+ second, err := monitor.ApplyHostReport(secondReport, secondToken)
+ if err != nil {
+ t.Fatalf("second ApplyHostReport: %v", err)
+ }
+ if first.ID == second.ID {
+ t.Fatalf("duplicate active identities collapsed to %q", first.ID)
+ }
+
+ if _, err := monitor.RemoveHostAgent(first.ID); err != nil {
+ t.Fatalf("RemoveHostAgent(first): %v", err)
+ }
+ secondReport.Timestamp = now.Add(time.Minute)
+ updated, err := monitor.ApplyHostReport(secondReport, secondToken)
+ if err != nil {
+ t.Fatalf("unrelated duplicate host was poisoned by removal: %v", err)
+ }
+ if updated.ID != second.ID {
+ t.Fatalf("unrelated duplicate host changed ID from %q to %q", second.ID, updated.ID)
+ }
+}
+
+func TestHostAgentRemovalLifecycleFailsClosedWhenTombstoneCannotPersist(t *testing.T) {
+ dataPath := filepath.Join(t.TempDir(), "not-a-directory")
+ if err := os.WriteFile(dataPath, []byte("fixture"), 0o600); err != nil {
+ t.Fatalf("write non-directory fixture: %v", err)
+ }
+ monitor := newHostRemovalLifecycleMonitor(t, dataPath)
+ now := time.Now().UTC()
+ report := hostRemovalLifecycleReport("persist-failure-host", "persist-failure-host", "agent-id", "persist.local", "linux", now)
+ host, err := monitor.ApplyHostReport(report, &config.APITokenRecord{ID: "persist-token", CreatedAt: now.Add(-time.Hour)})
+ if err != nil {
+ t.Fatalf("ApplyHostReport: %v", err)
+ }
+
+ if _, err := monitor.RemoveHostAgent(host.ID); err == nil {
+ t.Fatal("RemoveHostAgent succeeded without a durable tombstone")
+ }
+ if got := monitor.state.GetHosts(); len(got) != 1 || got[0].ID != host.ID {
+ t.Fatalf("failed removal did not restore live host: %+v", got)
+ }
+}
+
+func TestHostAgentRemovalLifecycleFailsClosedWhenJournalCannotLoad(t *testing.T) {
+ dataPath := t.TempDir()
+ if err := os.WriteFile(
+ filepath.Join(dataPath, "host_continuity.json"),
+ []byte(`{"broken":`),
+ 0o600,
+ ); err != nil {
+ t.Fatalf("write corrupt journal: %v", err)
+ }
+ if monitor, err := New(&config.Config{DataPath: dataPath, ConfigPath: dataPath}); err == nil {
+ monitor.Stop()
+ t.Fatal("monitor started without a readable host lifecycle journal")
+ }
+}
+
+func TestHostAgentRemovalLifecycleOrdersConcurrentReportsBeforeDeletion(t *testing.T) {
+ monitor := newHostRemovalLifecycleMonitor(t, t.TempDir())
+ now := time.Now().UTC()
+ report := hostRemovalLifecycleReport("race-machine", "race-machine", "race-agent", "race.local", "linux", now)
+ token := &config.APITokenRecord{ID: "race-token", CreatedAt: now.Add(-time.Hour)}
+ host, err := monitor.ApplyHostReport(report, token)
+ if err != nil {
+ t.Fatalf("initial ApplyHostReport: %v", err)
+ }
+
+ const reporters = 32
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ wg.Add(reporters)
+ for i := 0; i < reporters; i++ {
+ go func(offset int) {
+ defer wg.Done()
+ <-start
+ concurrent := report
+ concurrent.Timestamp = now.Add(time.Duration(offset+1) * time.Millisecond)
+ _, _ = monitor.ApplyHostReport(concurrent, token)
+ }(i)
+ }
+ close(start)
+ if _, err := monitor.RemoveHostAgent(host.ID); err != nil {
+ t.Fatalf("RemoveHostAgent: %v", err)
+ }
+ wg.Wait()
+
+ if got := monitor.state.GetHosts(); len(got) != 0 {
+ t.Fatalf("concurrent report resurrected removed host: %+v", got)
+ }
+ report.Timestamp = now.Add(time.Minute)
+ if _, err := monitor.ApplyHostReport(report, token); err == nil {
+ t.Fatal("old token reported after concurrent deletion completed")
+ }
+}
diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.go
index a2a22ef2b6..767d8ab428 100644
--- a/internal/monitoring/monitor_host_agents_test.go
+++ b/internal/monitoring/monitor_host_agents_test.go
@@ -3463,14 +3463,14 @@ func TestApplyHostReport_FreshTokenClearsRemovalBlock(t *testing.T) {
}
if len(monitor.state.GetRemovedHostAgents()) != 0 {
- t.Fatal("expected persisted removal block to be cleared")
+ t.Fatal("expected state removal block to be cleared")
}
}
-// TestAllowHostAgentReenroll_ClearsPersistedBlockAfterRestart pins the #1581
-// restart hole: the in-memory map is empty after a restart, but the persisted
-// entry must still be found and cleared.
-func TestAllowHostAgentReenroll_ClearsPersistedBlockAfterRestart(t *testing.T) {
+// TestAllowHostAgentReenroll_ClearsStateMirrorWithoutMemoryEntry preserves
+// compatibility with callers that only populated the models.State mirror.
+// The production restart path is covered by TestHostAgentRemovalLifecycleSurvivesMonitorReconstruction.
+func TestAllowHostAgentReenroll_ClearsStateMirrorWithoutMemoryEntry(t *testing.T) {
monitor := &Monitor{
state: models.NewState(),
alertManager: alerts.NewManager(),
@@ -3492,14 +3492,13 @@ func TestAllowHostAgentReenroll_ClearsPersistedBlockAfterRestart(t *testing.T) {
t.Fatalf("allow host reenroll: %v", err)
}
if len(monitor.state.GetRemovedHostAgents()) != 0 {
- t.Fatal("expected persisted removal block to be cleared without an in-memory entry")
+ t.Fatal("expected state removal block to be cleared without an in-memory entry")
}
}
-// TestCleanupRemovedHostAgents_ExpiresPersistedEntries pins the #1581 TTL
-// hole: persisted blocks must expire by their own RemovedAt even when the
-// in-memory map lost them across a restart.
-func TestCleanupRemovedHostAgents_ExpiresPersistedEntries(t *testing.T) {
+// TestCleanupRemovedHostAgents_ExpiresStateMirrorEntries pins expiry for
+// models.State-only compatibility entries when the in-memory map lacks them.
+func TestCleanupRemovedHostAgents_ExpiresStateMirrorEntries(t *testing.T) {
monitor := &Monitor{
state: models.NewState(),
hostTokenBindings: make(map[string]string),