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.

Let agents without a command channel reduce their authority

rcourtman4742159bb32e
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index dec04753a8..625a5b24f4 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -8248,6 +8248,33 @@ in `internal/api/deploy_handlers_test.go` replays that sequence: the identity
enrollment handed out, or the agent's own, then the acknowledged identity after
a restart.
+### Reports name the agent on a hostname-bound token
+
+Deploy enrollment, Proxmox auto-registration, and pre-v6.1.1 installs leave a
+token bound to the node's hostname and to no agent ID until a command
+registration names the agent. An agent whose token lacks `agent:exec`, or that
+never connects the command channel, never names itself that way, and the
+safe-profile authority reduction refuses it, because it matches the agent ID
+on the token. Every applied report therefore offers its identity: when the
+agent presented the same ID Pulse resolved and acknowledges in `agentId`
+(which the agent persists and the installer sends to the reduction), that ID
+is recorded on a token that has none, under the reporting-side rule in the
+security-privacy contract. The report grants no command authority, and when
+the presented and resolved IDs differ the token is left to the command
+channel's first registration. The first identity recorded is final, as it is
+for a command registration, so an agent later restarted under a different
+configured `--agent-id` is refused under that ID on the same token.
+`TestContractDeployEnrolledCollectorReducesItsAuthorityAfterItsFirstReport`
+in `internal/api/contract_test.go` replays enrollment without commands, the
+first report, and the reduction, which was refused before it;
+`TestReportedIdentityIsFinalForALaterReconfiguredAgent` in
+`internal/api/security_regression_test.go` pins the final-identity trade-off;
+and `TestApplyHostReportStampsTheTokenOnlyOnHostsItHolds` in
+`internal/monitoring/monitor_host_agents_test.go` pins the host properties the
+report path relies on: an applied report carries its token's ID, a report the
+ordering watermark rejects returns the stored host and hostname, and mock
+mode's discard acknowledgement carries no token.
+
### Alert push routing does not create an agent lifecycle channel
The shared API router may classify an external-probe outage for specialized
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 8026e32a35..767a622371 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -483,6 +483,14 @@ collector baseline, removes every scope outside the exact collector allowlist
from that token, persists before success, restores the full token inventory on
persistence failure, and invalidates only the exact matching collector session
after persistence.
+A token bound only to a hostname carries no agent ID for that match until
+something names the agent. `POST /api/agents/agent/report` names it: when the
+reporting agent presented the same ID the response acknowledges in `agentId`,
+that ID is recorded on a hostname-bound token that has none, so a collector
+that never connected the command channel can still reduce its authority. The
+report request and response shapes are unchanged.
+`TestContractDeployEnrolledCollectorReducesItsAuthorityAfterItsFirstReport`
+in `internal/api/contract_test.go` pins report, then reduction.
## Canonical Files
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 7ee7c0afba..e9c82794b3 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1475,6 +1475,40 @@ the agent config gate consumes the same decision.
`TestVersionlessDeployPlaceholderCannotBeMovedTwice`, and
`TestCurrentDeployTokenNeverMovesOnceBound` in
`internal/api/security_regression_test.go` pin that boundary.
+Authenticated reports also name the agent on a token bound only to its
+hostname, so a token without `agent:exec`, or whose agent never connects the
+command channel, still carries the identity the safe-profile authority
+reduction matches. After `/api/agents/agent/report` applies a report,
+`recordReportedAgentIdentity` in `internal/api/agent_exec_token_binding.go`
+writes the server-resolved host ID as `bound_agent_id`, with `bound_at` and the
+current binding version, only when the token has a `bound_hostname` and no
+`bound_agent_id`, the report presented exactly the ID Pulse resolved for it
+(in the same run, the ID the agent's command registration presents), and
+`agentbinding.EvaluateReportedIdentity` finds that the shared `Evaluate`
+decision would first-bind, legacy-migrate, or backfill that ID for the
+reported hostname. The token must also run command sessions in the request's
+organization, be bound to at most one organization, and carry a collector,
+legacy full-trust, or no runtime role, and the host must be one the monitor
+resolved and holds under that token, so mock mode's discarded, unresolved
+acknowledgements never qualify. The path never changes scopes, runtime role,
+command policy, or `bound_hostname`, and never moves a recorded ID or repairs
+a deploy placeholder. The binding version makes the recorded ID immutable to
+every later registration, and a recorded identity grants no execution
+authority: command admission still requires `agent:exec` and the same ID.
+As with a command registration, the first identity recorded is final: an
+agent later restarted under a different configured `--agent-id`, or replaying
+a report buffered by an earlier run, meets a token already bound to its first
+reported identity and is refused under the new one. When the presented and
+resolved IDs differ (a configured agent ID, a continuity fork), nothing is
+recorded and the command channel's first registration decides as before;
+reconciling that disagreement belongs to command-channel identity
+convergence. A token bound to no hostname is left to command-channel first
+use. The write runs against the live record under the token lock command
+admission holds, and a failed save restores the previous metadata.
+`TestEvaluateReportedIdentityRecordsOnlyWhatCommandRegistrationWouldBind` in
+`internal/api/agentbinding/policy_test.go`, and the `TestReportedIdentity*`
+tests and `TestReportHandlerOffersOnlyQualifyingLiveReportsToTheRecorder` in
+`internal/api/security_regression_test.go`, pin that boundary.
Pulse-minted install tokens now carry a server-authored command-policy intent
in addition to first-use binding metadata. That intent grants no independent
authority: first-report convergence requires the same shared binding decision
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 929e8c1c85..7909a2bab7 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -6486,6 +6486,17 @@ write never leaves a half-moved token. This adds no backup, restore, retention,
recovery authority. `internal/api/security_regression_test.go` pins the
persisted binding.
+### Reported agent identity is one persisted token transition
+
+Recording a report's agent identity on a hostname-bound token writes
+`bound_agent_id`, `bound_at`, and the binding version through the existing
+API-token persistence, under the token lock, in one save. When that save
+fails, the previous metadata is restored, the report itself is still
+acknowledged, and the next report retries, so a failed write never leaves a
+half-bound token. This adds no backup, restore, retention, snapshot, or
+recovery authority. `TestReportedIdentityRestoresTheTokenWhenTheSaveFails` in
+`internal/api/security_regression_test.go` pins the restore and the retry.
+
### Destination severity policy preserves notification recovery identity
Email, webhook, Apprise, and Relay minimum-severity floors persist through
diff --git a/internal/api/agent_exec_token_binding.go b/internal/api/agent_exec_token_binding.go
index 765525a805..b81045ed07 100644
--- a/internal/api/agent_exec_token_binding.go
+++ b/internal/api/agent_exec_token_binding.go
@@ -347,6 +347,88 @@ func (r *Router) admitAgentExecToken(token string, agentID string, hostname stri
return agentexec.AgentAdmission{}, false
}
+// recordReportedAgentIdentity is the reporting-side identity binding. After an
+// authenticated report is applied, a token bound to the report's hostname but
+// to no agent ID records the server-resolved host ID when the agent presented
+// that same ID (agentbinding.EvaluateReportedIdentity). Without it, a token
+// that lacks agent:exec, or whose agent never connects the command channel,
+// never names its agent, and the collector-authority reduction, which needs
+// that name, can never run for it.
+//
+// Only bound_agent_id, bound_at and the binding version are written, the
+// binding version so the recorded ID is immutable to every later
+// registration. Scopes, runtime role and command policy are left alone: a
+// recorded identity grants no execution authority, and a command registration
+// still needs agent:exec and the same identity. It runs under the token lock
+// that command admission holds, against the live record, so the two paths
+// cannot race each other into different identities. A failed save restores
+// the previous metadata and the next report retries.
+func (r *Router) recordReportedAgentIdentity(organizationID, tokenID, presentedID, hostID, hostname string) {
+ if r == nil || r.config == nil {
+ return
+ }
+ organizationID = strings.TrimSpace(organizationID)
+ if organizationID == "" {
+ organizationID = "default"
+ }
+ tokenID = strings.TrimSpace(tokenID)
+ hostID = strings.TrimSpace(hostID)
+ if tokenID == "" || hostID == "" {
+ return
+ }
+
+ config.Mu.Lock()
+ defer config.Mu.Unlock()
+ for index := range r.config.APITokens {
+ record := &r.config.APITokens[index]
+ if record.ID != tokenID {
+ continue
+ }
+ if record.IsExpired() {
+ return
+ }
+ // The host ID was resolved in the request's organization. Record it only
+ // on a token whose command sessions would run in that same organization,
+ // derived exactly as command admission derives it.
+ tokenOrganizationID := "default"
+ if orgs := record.GetBoundOrgs(); len(orgs) == 1 && strings.TrimSpace(orgs[0]) != "" {
+ tokenOrganizationID = strings.TrimSpace(orgs[0])
+ }
+ if tokenOrganizationID != organizationID {
+ return
+ }
+ if !agentbinding.EvaluateReportedIdentity(record, presentedID, hostID, hostname) {
+ return
+ }
+ previousMetadata := snapshotAgentExecMetadata(
+ record.Metadata,
+ "bound_agent_id",
+ "bound_at",
+ agentExecBindingVersionKey,
+ )
+ record.Metadata["bound_agent_id"] = hostID
+ record.Metadata["bound_at"] = time.Now().UTC().Format(time.RFC3339)
+ record.Metadata[agentExecBindingVersionKey] = agentExecBindingVersion
+ if r.persistence != nil {
+ if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil {
+ restoreAgentExecMetadata(record.Metadata, previousMetadata)
+ log.Warn().
+ Err(err).
+ Str("token_id", tokenID).
+ Str("agent_id", hostID).
+ Msg("Failed to persist reported agent identity on its token; the next report retries")
+ return
+ }
+ }
+ log.Info().
+ Str("token_id", tokenID).
+ Str("agent_id", hostID).
+ Str("hostname", strings.TrimSpace(record.Metadata["bound_hostname"])).
+ Msg("Bound hostname-bound agent token to the agent identity its reports resolve to")
+ return
+ }
+}
+
func (r *Router) validateAgentExecSession(admission agentexec.AgentAdmission) bool {
if r == nil || r.config == nil {
return false
diff --git a/internal/api/agent_ingest.go b/internal/api/agent_ingest.go
index 5d43fa882c..b3b13a0d6b 100644
--- a/internal/api/agent_ingest.go
+++ b/internal/api/agent_ingest.go
@@ -11,6 +11,7 @@ import (
"sync"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/api/agentbinding"
"github.com/rcourtman/pulse-go-rewrite/internal/api/agenttokens"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
@@ -44,6 +45,10 @@ type UnifiedAgentHandlers struct {
// check. Empty (the default) omits it from acks.
serverVersion string
+ // recordReportedIdentity records a report's server-resolved identity on
+ // its hostname-bound token. Nil (the default) records nothing.
+ recordReportedIdentity func(organizationID, tokenID, presentedID, hostID, hostname string)
+
configFetchAudits *agentConfigFetchAuditTracker
}
@@ -54,6 +59,12 @@ func (h *UnifiedAgentHandlers) SetServerVersion(version string) {
h.serverVersion = strings.TrimSpace(version)
}
+// SetReportedIdentityRecorder supplies the canonical token-store binding that
+// records the agent identity a report resolves to. Call once at wiring time.
+func (h *UnifiedAgentHandlers) SetReportedIdentityRecorder(record func(organizationID, tokenID, presentedID, hostID, hostname string)) {
+ h.recordReportedIdentity = record
+}
+
func trimUnifiedAgentRoutePath(path string) string {
for _, prefix := range []string{agentRoutePrefix, legacyHostRoutePrefix} {
if strings.HasPrefix(path, prefix) {
@@ -96,6 +107,23 @@ func (h *UnifiedAgentHandlers) HandleReport(w http.ResponseWriter, r *http.Reque
return
}
+ // Name the agent on a token bound only to its hostname, so the token
+ // carries an identity even if this agent never registers a command channel.
+ // Only a host the monitor resolved and holds under this token carries its
+ // token ID; mock mode's discard acknowledgement echoes the presented ID
+ // unresolved and carries none, whenever mock mode flips. The hostname is
+ // the report's own, which is what the agent's command registration
+ // presents: a report the ordering watermark rejects returns the stored
+ // host, whose hostname may come from a different report. The request's
+ // token snapshot screens out tokens that are already bound or do not
+ // qualify without taking the exclusive token lock on every report; the
+ // recorder decides again on the live record.
+ reportedHostname := strings.TrimSpace(report.Host.Hostname)
+ if h.recordReportedIdentity != nil && tokenRecord != nil && host.TokenID == tokenRecord.ID &&
+ agentbinding.EvaluateReportedIdentity(tokenRecord, report.Agent.ID, host.ID, reportedHostname) {
+ h.recordReportedIdentity(GetOrgID(r.Context()), tokenRecord.ID, report.Agent.ID, host.ID, reportedHostname)
+ }
+
// A freshly generated install token is the server's durable record of the
// operator's command-policy choice. Project that choice onto the stable host
// identity before returning remote config, otherwise an old false override
diff --git a/internal/api/agentbinding/policy.go b/internal/api/agentbinding/policy.go
index 4e85dc44b3..eb940183de 100644
--- a/internal/api/agentbinding/policy.go
+++ b/internal/api/agentbinding/policy.go
@@ -108,6 +108,53 @@ func Evaluate(record *config.APITokenRecord, requestedID, requestedHost string)
}
}
+// EvaluateReportedIdentity reports whether an authenticated agent report may
+// record the reporting agent's identity on its token. It covers only a token
+// bound to a hostname but not yet to an agent ID, which is how deploy
+// enrollment, Proxmox auto-registration and pre-v6.1.1 installs leave it until
+// a command registration, so a token without agent:exec, or whose agent never
+// connects the command channel, would otherwise never name its agent.
+//
+// The identity the agent presented in the report must equal the identity the
+// server resolved for it. In the same run that is the ID the agent's command
+// registration presents, so recording it binds what the command channel would
+// bind, and a disagreement (a configured agent ID, a continuity fork) records
+// nothing. The token must also take a first bind, legacy migration, or
+// backfill under Evaluate, the command channel's own decision, so a token
+// command registration would refuse records nothing either. As with a command
+// registration, the first identity recorded is final: an agent later restarted
+// under a different configured ID, or replaying a report buffered by an
+// earlier run, meets a bound token. Bound IDs never move, deploy placeholders
+// are never repaired, hostnames never change, and only credentials that report
+// under a single organization qualify.
+func EvaluateReportedIdentity(record *config.APITokenRecord, presentedID, resolvedID, reportedHost string) bool {
+ if record == nil {
+ return false
+ }
+ presentedID = strings.TrimSpace(presentedID)
+ resolvedID = strings.TrimSpace(resolvedID)
+ if resolvedID == "" || presentedID != resolvedID {
+ return false
+ }
+ if strings.TrimSpace(record.Metadata["bound_agent_id"]) != "" ||
+ strings.TrimSpace(record.Metadata["bound_hostname"]) == "" {
+ return false
+ }
+ if len(record.GetBoundOrgs()) > 1 {
+ return false
+ }
+ switch strings.TrimSpace(record.Metadata[agenttokens.RuntimeRoleMetadataKey]) {
+ case "", agenttokens.CredentialKindLegacyFullTrust, agenttokens.CredentialKindMonitoringCollector:
+ default:
+ return false
+ }
+ // With no bound ID and a bound hostname, Evaluate admits only through a
+ // first bind, a legacy migration or an ID backfill, never a rebind or a
+ // placeholder repair; the explicit check keeps that true if Evaluate grows.
+ decision := Evaluate(record, resolvedID, reportedHost)
+ return decision.Admit && (decision.FirstBind || decision.LegacyMigrate || decision.BackfillID)
+}
+
// historicalDeployPlaceholder reports a runtime token that deploy enrollment
// bound to the agent-<hostname> identity it used to invent. No agent keeps
// that identity past its first acknowledged report, so such a token may move
diff --git a/internal/api/agentbinding/policy_test.go b/internal/api/agentbinding/policy_test.go
index d7500c2ee4..55d8d6bae4 100644
--- a/internal/api/agentbinding/policy_test.go
+++ b/internal/api/agentbinding/policy_test.go
@@ -160,3 +160,97 @@ func TestEvaluateCurrentDeployTokenBackfillsTheAgentIdentity(t *testing.T) {
t.Fatalf("current deploy token admitted another host: %+v", decision)
}
}
+
+// A report may name the agent on a token bound only to its hostname, but only
+// with the identity the command channel would bind for that same agent, and
+// never by moving, repairing, or rehosting a binding.
+func TestEvaluateReportedIdentityRecordsOnlyWhatCommandRegistrationWouldBind(t *testing.T) {
+ deployToken := func() *config.APITokenRecord {
+ return &config.APITokenRecord{OrgID: "default", Metadata: map[string]string{
+ "bound_hostname": "delly2",
+ "deploy_job_id": "dep_1",
+ VersionKey: Version,
+ DeployIdentityKey: DeployIdentityAgent,
+ }}
+ }
+ autoRegistered := func() *config.APITokenRecord {
+ return &config.APITokenRecord{OrgID: "default", Metadata: map[string]string{
+ "install_type": "pve",
+ "issued_via": IssuedViaConfig,
+ "bound_hostname": "pve1",
+ agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindMonitoringCollector,
+ }}
+ }
+ legacyHostnameOnly := func() *config.APITokenRecord {
+ return &config.APITokenRecord{Metadata: map[string]string{"bound_hostname": "node.example"}}
+ }
+
+ for _, test := range []struct {
+ name string
+ record *config.APITokenRecord
+ host string
+ }{
+ {name: "deploy runtime token", record: deployToken(), host: "delly2"},
+ {name: "deploy runtime token on an equivalent hostname", record: deployToken(), host: "delly2.lan"},
+ {name: "Proxmox auto-registered collector", record: autoRegistered(), host: "pve1"},
+ {name: "pre-v6.1.1 hostname-only token", record: legacyHostnameOnly(), host: "NODE.example"},
+ } {
+ if !EvaluateReportedIdentity(test.record, "machine-id", "machine-id", test.host) {
+ t.Fatalf("%s: report identity not recorded", test.name)
+ }
+ if EvaluateReportedIdentity(test.record, "configured-id", "machine-id", test.host) {
+ t.Fatalf("%s: recorded the resolved identity although the agent presented another", test.name)
+ }
+ if EvaluateReportedIdentity(test.record, "", "", test.host) {
+ t.Fatalf("%s: recorded an empty identity", test.name)
+ }
+ }
+
+ with := func(record *config.APITokenRecord, mutate func(*config.APITokenRecord)) *config.APITokenRecord {
+ mutate(record)
+ return record
+ }
+ for _, test := range []struct {
+ name string
+ record *config.APITokenRecord
+ host string
+ }{
+ {name: "another hostname", record: deployToken(), host: "other-node"},
+ {name: "an already bound ID", host: "delly2", record: with(deployToken(), func(r *config.APITokenRecord) {
+ r.Metadata["bound_agent_id"] = "other-machine"
+ })},
+ {name: "an ID already recorded", host: "delly2", record: with(deployToken(), func(r *config.APITokenRecord) {
+ r.Metadata["bound_agent_id"] = "machine-id"
+ })},
+ // Evaluate would legacy-migrate this one on command registration; the
+ // report path never moves an ID.
+ {name: "a versionless token already bound to an ID", host: "node.example", record: with(legacyHostnameOnly(), func(r *config.APITokenRecord) {
+ r.Metadata["bound_agent_id"] = "other-machine"
+ })},
+ {name: "a historical deploy placeholder", host: "delly2", record: with(deployToken(), func(r *config.APITokenRecord) {
+ r.Metadata["bound_agent_id"] = "agent-delly2"
+ delete(r.Metadata, DeployIdentityKey)
+ })},
+ {name: "a token bound to no hostname", host: "node.example", record: &config.APITokenRecord{OrgID: "default", Metadata: map[string]string{
+ "install_type": "host",
+ "issued_via": IssuedViaConfig,
+ }}},
+ {name: "a token bound to several organizations", host: "delly2", record: with(deployToken(), func(r *config.APITokenRecord) {
+ r.OrgID = ""
+ r.OrgIDs = []string{"org-a", "org-b"}
+ })},
+ {name: "an action-runner credential", host: "delly2", record: with(deployToken(), func(r *config.APITokenRecord) {
+ r.Metadata[agenttokens.RuntimeRoleMetadataKey] = agenttokens.CredentialKindActionRunner
+ })},
+ {name: "an unsupported runtime role", host: "delly2", record: with(deployToken(), func(r *config.APITokenRecord) {
+ r.Metadata[agenttokens.RuntimeRoleMetadataKey] = "future-role"
+ })},
+ } {
+ if EvaluateReportedIdentity(test.record, "machine-id", "machine-id", test.host) {
+ t.Fatalf("%s: report identity recorded", test.name)
+ }
+ }
+ if EvaluateReportedIdentity(nil, "machine-id", "machine-id", "delly2") {
+ t.Fatal("nil token recorded an identity")
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 82360b0096..c7dea26e53 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -17,6 +17,7 @@ import (
"path/filepath"
"reflect"
"regexp"
+ "slices"
"sort"
"strings"
"sync/atomic"
@@ -37,6 +38,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/unified"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rcourtman/pulse-go-rewrite/internal/api/agentbinding"
"github.com/rcourtman/pulse-go-rewrite/internal/api/agenttokens"
"github.com/rcourtman/pulse-go-rewrite/internal/api/alerting"
"github.com/rcourtman/pulse-go-rewrite/internal/api/chartapi"
@@ -25390,3 +25392,80 @@ func TestRouterPlatformConnectionAlertsFollowRuntime(t *testing.T) {
}
t.Log("real TrueNAS inventory recovery reaches the ledger and clears only after monitor confirmations")
}
+
+func TestContractDeployEnrolledCollectorReducesItsAuthorityAfterItsFirstReport(t *testing.T) {
+ h, store := newEnrollTestHandlers(t)
+ jobID, targetID := seedEnrollJobAndTarget(t, store, deploy.TargetEnrolling)
+ bootstrap := mintTestBootstrapToken(t, h.config, jobID, targetID, "pve-node2")
+ h.persistence = config.NewConfigPersistence(h.config.DataPath)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/enroll", enrollJSON(t, "pve-node2"))
+ attachAPITokenRecord(req, bootstrap)
+ rr := httptest.NewRecorder()
+ h.HandleEnroll(rr, req)
+ if rr.Code != http.StatusOK {
+ t.Fatalf("enroll status = %d: %s", rr.Code, rr.Body.String())
+ }
+ var enrolledResp map[string]any
+ if err := json.Unmarshal(rr.Body.Bytes(), &enrolledResp); err != nil {
+ t.Fatalf("decode enroll: %v", err)
+ }
+ runtimeToken, _ := enrolledResp["runtimeToken"].(string)
+ runtimeTokenID, _ := enrolledResp["runtimeTokenId"].(string)
+ if runtimeToken == "" || runtimeTokenID == "" {
+ t.Fatalf("enrollment returned no runtime token: %v", enrolledResp)
+ }
+ enrolled := reportIdentityToken(t, h.config, runtimeTokenID)
+ if enrolled.HasScope(config.ScopeAgentExec) || enrolled.Metadata["bound_agent_id"] != "" {
+ t.Fatalf("precondition: enrolled token = %+v, want hostname-bound without agent:exec", enrolled)
+ }
+
+ router := newReportIdentityRouter(t, h.config)
+ if code := postCollectorReduction(t, router, runtimeToken, reportIdentityMachineID, "pve-node2"); code != http.StatusForbidden {
+ t.Fatalf("reduction before any report = %d, want 403: the token names no agent yet", code)
+ }
+
+ ack := postReportIdentityReport(t, router, runtimeToken,
+ reportIdentityReport(reportIdentityMachineID, reportIdentityMachineID, "pve-node2"))
+ if ack != reportIdentityMachineID {
+ t.Fatalf("acknowledged agentId = %q, want %q", ack, reportIdentityMachineID)
+ }
+
+ bound := reportIdentityToken(t, h.config, runtimeTokenID)
+ if got := bound.Metadata["bound_agent_id"]; got != ack {
+ t.Fatalf("bound_agent_id after the first report = %q, want the acknowledged %q", got, ack)
+ }
+ if got := bound.Metadata["bound_hostname"]; got != "pve-node2" {
+ t.Fatalf("bound_hostname = %q, want it untouched", got)
+ }
+ if got := bound.Metadata[agentExecBindingVersionKey]; got != agentExecBindingVersion {
+ t.Fatalf("binding version = %q, want %q", got, agentExecBindingVersion)
+ }
+ if got := bound.Metadata[agentbinding.DeployIdentityKey]; got != agentbinding.DeployIdentityAgent {
+ t.Fatalf("deploy identity marker = %q, want it untouched", got)
+ }
+ if !slices.Equal(bound.Scopes, enrolled.Scopes) {
+ t.Fatalf("scopes after the report = %v, want unchanged %v", bound.Scopes, enrolled.Scopes)
+ }
+ if got := bound.Metadata[agenttokens.RuntimeRoleMetadataKey]; got != enrolled.Metadata[agenttokens.RuntimeRoleMetadataKey] {
+ t.Fatalf("runtime role after the report = %q, want unchanged %q", got, enrolled.Metadata[agenttokens.RuntimeRoleMetadataKey])
+ }
+ persisted, err := config.NewConfigPersistence(h.config.DataPath).LoadAPITokens()
+ if err != nil {
+ t.Fatalf("load persisted tokens: %v", err)
+ }
+ if len(persisted) != 1 || persisted[0].Metadata["bound_agent_id"] != ack {
+ t.Fatalf("persisted tokens = %+v, want the runtime token bound to %s", persisted, ack)
+ }
+ if _, ok := router.admitAgentExecToken(runtimeToken, ack, "pve-node2"); ok {
+ t.Fatal("recording the agent identity granted command execution to a token without agent:exec")
+ }
+
+ if code := postCollectorReduction(t, router, runtimeToken, ack, "pve-node2"); code != http.StatusNoContent {
+ t.Fatalf("reduction with the acknowledged identity = %d, want 204", code)
+ }
+ reduced := reportIdentityToken(t, h.config, runtimeTokenID)
+ if got := reduced.Metadata[agenttokens.RuntimeRoleMetadataKey]; got != agenttokens.CredentialKindMonitoringCollector {
+ t.Fatalf("runtime role after reduction = %q, want %q", got, agenttokens.CredentialKindMonitoringCollector)
+ }
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 082251c472..ceec1ce918 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -503,6 +503,7 @@ func (r *Router) setupRoutes() {
r.kubernetesAgentHandlers = NewKubernetesAgentHandlers(r.mtMonitor, r.monitor, r.wsHub)
r.unifiedAgentHandlers = NewUnifiedAgentHandlers(r.mtMonitor, r.monitor, r.wsHub)
r.unifiedAgentHandlers.SetServerVersion(r.serverVersion)
+ r.unifiedAgentHandlers.SetReportedIdentityRecorder(r.recordReportedAgentIdentity)
r.kubernetesAgentHandlers.SetRecoveryIngestor(r.recoveryHandlers)
r.resourceHandlers = NewResourceHandlers(r.config)
r.resourceHandlers.SetOperatorStateChanged(func(_ string, resourceID string) {
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 67f979cf5b..53794d9fb7 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -22,10 +22,12 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/api/agentbinding"
"github.com/rcourtman/pulse-go-rewrite/internal/api/agenttokens"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/rcourtman/pulse-go-rewrite/internal/servicediscovery"
pulsews "github.com/rcourtman/pulse-go-rewrite/internal/websocket"
+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
@@ -5633,3 +5635,414 @@ func TestCurrentDeployTokenNeverMovesOnceBound(t *testing.T) {
t.Fatal("a current deploy token moved after its first binding")
}
}
+
+const reportIdentityMachineID = "49a2dbb3-3cc8-43b7-ad57-eb1711142454"
+
+// reportIdentityReport is a report as pulse-agent sends it: the host carries
+
+// the machine-derived ID and the agent block the ID it presents everywhere,
+
+// including on command registration.
+
+func reportIdentityReport(presentedID, machineID, hostname string) agentshost.Report {
+ return agentshost.Report{
+ Agent: agentshost.AgentInfo{
+ ID: presentedID,
+ Version: "6.5.0",
+ Type: "unified",
+ IntervalSeconds: 30,
+ Hostname: hostname,
+ },
+ Host: agentshost.HostInfo{
+ ID: machineID,
+ Hostname: hostname,
+ MachineID: machineID,
+ Platform: "linux",
+ OSName: "debian",
+ },
+ Timestamp: time.Now().UTC(),
+ }
+}
+
+func newReportIdentityRouter(t *testing.T, cfg *config.Config) *Router {
+ t.Helper()
+ monitor, err := monitoring.New(cfg)
+ if err != nil {
+ t.Fatalf("new monitor: %v", err)
+ }
+ t.Cleanup(monitor.Stop)
+ return NewRouter(cfg, monitor, nil, nil, func() error { return nil }, "6.5.0")
+}
+
+func reportIdentityToken(t *testing.T, cfg *config.Config, tokenID string) config.APITokenRecord {
+ t.Helper()
+ config.Mu.Lock()
+ defer config.Mu.Unlock()
+ for index := range cfg.APITokens {
+ if cfg.APITokens[index].ID == tokenID {
+ return cfg.APITokens[index].Clone()
+ }
+ }
+ t.Fatalf("token %s not found", tokenID)
+ return config.APITokenRecord{}
+}
+
+func postReportIdentityReport(t *testing.T, router *Router, token string, report agentshost.Report) string {
+ t.Helper()
+ code, payload := issue1753PostReport(t, router, token, report)
+ if code != http.StatusOK {
+ t.Fatalf("report rejected with %d (%v)", code, payload)
+ }
+ ack, _ := payload["agentId"].(string)
+ return ack
+}
+
+func postCollectorReduction(t *testing.T, router *Router, token, agentID, hostname string) int {
+ t.Helper()
+ body, err := json.Marshal(collectorAuthorityReductionRequest{AgentID: agentID, Hostname: hostname})
+ if err != nil {
+ t.Fatalf("marshal reduction: %v", err)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/api/agents/collector/reduce-authority", bytes.NewReader(body))
+ req.Header.Set("X-API-Token", token)
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ return rec.Code
+}
+
+// A deployed agent enrolled without commands never registers a command
+
+// channel. Its runtime token stayed bound to the node's hostname alone, so the
+
+// safe-profile migration's authority reduction, which needs the agent's ID on
+
+// the token, was refused with "Collector credential binding mismatch" for as
+
+// long as the agent ran. The first acknowledged report now names the agent.
+
+func autoRegisteredInstallToken(t *testing.T, raw, hostname string, enableCommands bool) config.APITokenRecord {
+ t.Helper()
+ role := agenttokens.CredentialKindMonitoringCollector
+ if enableCommands {
+ role = agenttokens.CredentialKindLegacyFullTrust
+ }
+ record := newTokenRecord(t, raw, agenttokens.ProxmoxScopes(enableCommands), map[string]string{
+ "install_type": "pve",
+ "issued_via": agentbinding.IssuedViaConfig,
+ "bound_hostname": hostname,
+ "bound_at": time.Now().UTC().Format(time.RFC3339),
+ agenttokens.RuntimeRoleMetadataKey: role,
+ })
+ record.OrgID = "default"
+ return record
+}
+
+// The report path and the command channel bind the same identity, and once
+
+// either has named the agent the token never takes another identity, whatever
+
+// later reports resolve.
+
+func TestReportedIdentityMatchesCommandRegistrationAndNeverMoves(t *testing.T) {
+ const raw = "report-identity-pve1-token.12345678"
+ record := autoRegisteredInstallToken(t, raw, "pve1", true)
+ cfg := newTestConfigWithTokens(t, record)
+ router := newReportIdentityRouter(t, cfg)
+
+ postReportIdentityReport(t, router, raw, reportIdentityReport("machine-a", "machine-a", "pve1"))
+ bound := reportIdentityToken(t, cfg, record.ID)
+ if got := bound.Metadata["bound_agent_id"]; got != "machine-a" {
+ t.Fatalf("bound_agent_id = %q, want machine-a", got)
+ }
+ if got := bound.Metadata[agenttokens.RuntimeRoleMetadataKey]; got != agenttokens.CredentialKindLegacyFullTrust {
+ t.Fatalf("runtime role = %q, want it untouched", got)
+ }
+ // Without the binding version a versionless token would still accept any
+ // identity on its hostname through the legacy migration.
+ if got := bound.Metadata[agentExecBindingVersionKey]; got != agentExecBindingVersion {
+ t.Fatalf("binding version = %q, want %q so the recorded ID is immutable", got, agentExecBindingVersion)
+ }
+ if _, ok := router.admitAgentExecToken(raw, "machine-b", "pve1"); ok {
+ t.Fatal("another identity's command registration moved the identity the report recorded")
+ }
+ if _, ok := router.admitAgentExecToken(raw, "machine-a", "pve1"); !ok {
+ t.Fatal("the reporting agent's own command registration was refused")
+ }
+
+ // Another machine presenting this token under the same hostname reports
+ // under its own identity, but the token stays with the agent it named.
+ issue1753PostReport(t, router, raw, reportIdentityReport("machine-b", "machine-b", "pve1"))
+ if got := reportIdentityToken(t, cfg, record.ID).Metadata["bound_agent_id"]; got != "machine-a" {
+ t.Fatalf("bound_agent_id after another machine reported = %q, want machine-a", got)
+ }
+ if _, ok := router.admitAgentExecToken(raw, "machine-b", "pve1"); ok {
+ t.Fatal("a second identity was admitted on a token the report path had already bound")
+ }
+
+ // A token the command channel bound first keeps that identity even when the
+ // server resolves this agent's reports to another one.
+ const deployRaw = "report-identity-deploy-token.12345678"
+ deployRecord := newTokenRecord(t, deployRaw, agenttokens.HostScopes(true), map[string]string{
+ "bound_hostname": "pve-node3",
+ "deploy_job_id": "dep_1",
+ agentExecBindingVersionKey: agentExecBindingVersion,
+ agentbinding.DeployIdentityKey: agentbinding.DeployIdentityAgent,
+ })
+ deployRecord.OrgID = "default"
+ config.Mu.Lock()
+ cfg.UpsertAPIToken(deployRecord)
+ config.Mu.Unlock()
+ if _, ok := router.admitAgentExecToken(deployRaw, "configured-id", "pve-node3"); !ok {
+ t.Fatal("first command registration refused")
+ }
+ ack := postReportIdentityReport(t, router, deployRaw, reportIdentityReport("configured-id", reportIdentityMachineID, "pve-node3"))
+ if ack == "configured-id" {
+ t.Fatalf("precondition: the server resolved the presented ID %q", ack)
+ }
+ if got := reportIdentityToken(t, cfg, deployRecord.ID).Metadata["bound_agent_id"]; got != "configured-id" {
+ t.Fatalf("bound_agent_id = %q, want the command channel's configured-id", got)
+ }
+}
+
+// As with a command registration, the first identity a token records is
+
+// final. An agent that reported under its machine ID with commands off, then
+
+// restarts under a configured --agent-id with commands on, meets a token
+
+// already bound to the machine ID, exactly as it would had its first run
+
+// registered a command channel.
+
+func TestReportedIdentityIsFinalForALaterReconfiguredAgent(t *testing.T) {
+ const raw = "report-identity-reconfigured-token.12345678"
+ record := autoRegisteredInstallToken(t, raw, "pve9", true)
+ cfg := newTestConfigWithTokens(t, record)
+ router := newReportIdentityRouter(t, cfg)
+
+ postReportIdentityReport(t, router, raw, reportIdentityReport(reportIdentityMachineID, reportIdentityMachineID, "pve9"))
+ ack := postReportIdentityReport(t, router, raw, reportIdentityReport("configured-id", reportIdentityMachineID, "pve9"))
+ if ack != reportIdentityMachineID {
+ t.Fatalf("precondition: acknowledged agentId = %q, want the machine ID", ack)
+ }
+ if got := reportIdentityToken(t, cfg, record.ID).Metadata["bound_agent_id"]; got != reportIdentityMachineID {
+ t.Fatalf("bound_agent_id = %q, want the first reported identity", got)
+ }
+ if _, ok := router.admitAgentExecToken(raw, "configured-id", "pve9"); ok {
+ t.Fatal("a reconfigured identity moved a token the report path had bound")
+ }
+ if _, ok := router.admitAgentExecToken(raw, reportIdentityMachineID, "pve9"); !ok {
+ t.Fatal("the recorded identity's command registration was refused")
+ }
+}
+
+// An agent started with a configured --agent-id presents that ID on its
+
+// command channel, while Pulse resolves its reports to the machine ID. The
+
+// report path cannot tell which identity the token should carry, so it records
+
+// nothing and leaves the command channel's first registration unchanged.
+
+func TestReportedIdentityRecordsNothingWhenTheResolvedIdentityIsNotThePresentedOne(t *testing.T) {
+ const raw = "report-identity-configured-token.12345678"
+ record := newTokenRecord(t, raw, agenttokens.HostScopes(true), map[string]string{
+ "bound_hostname": "pve-node4",
+ "deploy_job_id": "dep_1",
+ agentExecBindingVersionKey: agentExecBindingVersion,
+ agentbinding.DeployIdentityKey: agentbinding.DeployIdentityAgent,
+ })
+ record.OrgID = "default"
+ cfg := newTestConfigWithTokens(t, record)
+ router := newReportIdentityRouter(t, cfg)
+
+ ack := postReportIdentityReport(t, router, raw, reportIdentityReport("configured-id", reportIdentityMachineID, "pve-node4"))
+ if ack != reportIdentityMachineID {
+ t.Fatalf("precondition: acknowledged agentId = %q, want the machine ID", ack)
+ }
+ if got := reportIdentityToken(t, cfg, record.ID).Metadata["bound_agent_id"]; got != "" {
+ t.Fatalf("bound_agent_id = %q, want nothing recorded while the identities disagree", got)
+ }
+ if _, ok := router.admitAgentExecToken(raw, "configured-id", "pve-node4"); !ok {
+ t.Fatal("the agent's command registration under its configured ID was refused")
+ }
+}
+
+// A report the ordering watermark rejects is answered with the stored host,
+
+// whose hostname came from another report. The binding must be judged on the
+
+// rejected report's own hostname, the one its agent's command registration
+
+// presents, never on the stored one.
+
+func TestReportedIdentityJudgesAReplayedReportByItsOwnHostname(t *testing.T) {
+ const raw = "report-identity-replay-token.12345678"
+ record := newTokenRecord(t, raw, agenttokens.HostScopes(false), map[string]string{
+ "bound_hostname": "node.site-a",
+ "deploy_job_id": "dep_1",
+ agentExecBindingVersionKey: agentExecBindingVersion,
+ agentbinding.DeployIdentityKey: agentbinding.DeployIdentityAgent,
+ })
+ record.OrgID = "default"
+ cfg := newTestConfigWithTokens(t, record)
+ router := newReportIdentityRouter(t, cfg)
+
+ start := time.Now().UTC().Add(-time.Minute)
+ retired := reportIdentityReport(reportIdentityMachineID, reportIdentityMachineID, "node.site-b")
+ retired.Timestamp = start
+ postReportIdentityReport(t, router, raw, retired)
+ newer := reportIdentityReport("configured-id", reportIdentityMachineID, "node")
+ newer.Timestamp = start.Add(30 * time.Second)
+ postReportIdentityReport(t, router, raw, newer)
+ if got := reportIdentityToken(t, cfg, record.ID).Metadata["bound_agent_id"]; got != "" {
+ t.Fatalf("precondition: bound_agent_id = %q before the replay", got)
+ }
+
+ postReportIdentityReport(t, router, raw, retired)
+ if got := reportIdentityToken(t, cfg, record.ID).Metadata["bound_agent_id"]; got != "" {
+ t.Fatalf("bound_agent_id = %q from a replayed report whose own hostname the token refuses", got)
+ }
+}
+
+// A failed save leaves the token exactly as it was and the next report
+
+// records the identity.
+
+func TestReportedIdentityRestoresTheTokenWhenTheSaveFails(t *testing.T) {
+ const raw = "report-identity-save-token.12345678"
+ record := autoRegisteredInstallToken(t, raw, "pve5", false)
+ cfg := newTestConfigWithTokens(t, record)
+ router := newReportIdentityRouter(t, cfg)
+
+ blocked := filepath.Join(t.TempDir(), "blocked-state")
+ failing := config.NewConfigPersistence(blocked)
+ if err := os.RemoveAll(blocked); err != nil {
+ t.Fatalf("remove persistence directory: %v", err)
+ }
+ if err := os.WriteFile(blocked, []byte("not a directory"), 0o600); err != nil {
+ t.Fatalf("create persistence blocker: %v", err)
+ }
+ working := router.persistence
+ router.persistence = failing
+
+ report := reportIdentityReport("machine-e", "machine-e", "pve5")
+ postReportIdentityReport(t, router, raw, report)
+ unchanged := reportIdentityToken(t, cfg, record.ID)
+ for _, key := range []string{"bound_agent_id", agentExecBindingVersionKey} {
+ if _, present := unchanged.Metadata[key]; present {
+ t.Fatalf("%s = %q after a failed save, want it absent", key, unchanged.Metadata[key])
+ }
+ }
+ if got := unchanged.Metadata["bound_at"]; got != record.Metadata["bound_at"] {
+ t.Fatalf("bound_at = %q after a failed save, want %q", got, record.Metadata["bound_at"])
+ }
+
+ router.persistence = working
+ postReportIdentityReport(t, router, raw, report)
+ retried := reportIdentityToken(t, cfg, record.ID)
+ if got := retried.Metadata["bound_agent_id"]; got != "machine-e" {
+ t.Fatalf("bound_agent_id after the retry = %q, want machine-e", got)
+ }
+ if got := retried.Metadata[agentExecBindingVersionKey]; got != agentExecBindingVersion {
+ t.Fatalf("binding version after the retry = %q, want %q", got, agentExecBindingVersion)
+ }
+}
+
+// The ID is resolved in the request's organization, so only a token whose
+
+// command sessions run in that organization records it.
+
+func TestReportedIdentityRequiresTheTokensOwnOrganization(t *testing.T) {
+ const raw = "report-identity-org-token.12345678"
+ record := autoRegisteredInstallToken(t, raw, "pve6", false)
+ record.OrgID = "org-a"
+ cfg := newTestConfigWithTokens(t, record)
+ router := &Router{config: cfg, persistence: config.NewConfigPersistence(cfg.DataPath)}
+
+ router.recordReportedAgentIdentity("default", record.ID, "machine-f", "machine-f", "pve6")
+ if got := reportIdentityToken(t, cfg, record.ID).Metadata["bound_agent_id"]; got != "" {
+ t.Fatalf("bound_agent_id = %q from another organization's report", got)
+ }
+ router.recordReportedAgentIdentity("org-a", record.ID, "machine-f", "machine-f", "pve6")
+ if got := reportIdentityToken(t, cfg, record.ID).Metadata["bound_agent_id"]; got != "machine-f" {
+ t.Fatalf("bound_agent_id = %q, want machine-f from the token's own organization", got)
+ }
+}
+
+// A token that expired after it authenticated the report records nothing.
+
+func TestReportedIdentityIgnoresAnExpiredToken(t *testing.T) {
+ record := autoRegisteredInstallToken(t, "report-identity-expired-token.12345678", "pve8", false)
+ expired := time.Now().Add(-time.Minute)
+ record.ExpiresAt = &expired
+ cfg := newTestConfigWithTokens(t, record)
+ router := &Router{config: cfg, persistence: config.NewConfigPersistence(cfg.DataPath)}
+
+ router.recordReportedAgentIdentity("default", record.ID, "machine-h", "machine-h", "pve8")
+ if got := reportIdentityToken(t, cfg, record.ID).Metadata["bound_agent_id"]; got != "" {
+ t.Fatalf("bound_agent_id = %q on an expired token", got)
+ }
+}
+
+// The handler offers the recorder only reports the monitor applied under the
+
+// token, and only when the token snapshot qualifies, so a token that never will
+
+// (here, an agent presenting a configured ID) does not take the exclusive token
+
+// lock on every report. Mock mode discards reports and acknowledges the
+
+// presented ID unresolved, so it must not record anything on a real token.
+
+func TestReportHandlerOffersOnlyQualifyingLiveReportsToTheRecorder(t *testing.T) {
+ const raw = "report-identity-mock-token.12345678"
+ record := autoRegisteredInstallToken(t, raw, "pve7", false)
+ cfg := newTestConfigWithTokens(t, record)
+ monitor, err := monitoring.New(cfg)
+ if err != nil {
+ t.Fatalf("new monitor: %v", err)
+ }
+ defer monitor.Stop()
+ handler := NewUnifiedAgentHandlers(nil, monitor, nil)
+ type recorded struct{ organizationID, tokenID, presentedID, hostID, hostname string }
+ var calls []recorded
+ handler.SetReportedIdentityRecorder(func(organizationID, tokenID, presentedID, hostID, hostname string) {
+ calls = append(calls, recorded{organizationID, tokenID, presentedID, hostID, hostname})
+ })
+ post := func(presentedID string) {
+ t.Helper()
+ body, err := json.Marshal(reportIdentityReport(presentedID, "machine-g", "pve7"))
+ if err != nil {
+ t.Fatalf("marshal report: %v", err)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/report", bytes.NewReader(body))
+ attachAPITokenRecord(req, &record)
+ rec := httptest.NewRecorder()
+ handler.HandleReport(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("report status = %d: %s", rec.Code, rec.Body.String())
+ }
+ }
+
+ post("configured-id")
+ if len(calls) != 0 {
+ t.Fatalf("recorder offered a report whose presented ID was not resolved: %+v", calls)
+ }
+ post("machine-g")
+ want := recorded{"default", record.ID, "machine-g", "machine-g", "pve7"}
+ if len(calls) != 1 || calls[0] != want {
+ t.Fatalf("recorder calls = %+v, want one call %+v", calls, want)
+ }
+
+ previous := mock.IsMockEnabled()
+ if err := mock.SetEnabled(true); err != nil {
+ t.Fatalf("enable mock mode: %v", err)
+ }
+ t.Cleanup(func() { _ = mock.SetEnabled(previous) })
+ post("machine-g")
+ if len(calls) != 1 {
+ t.Fatalf("recorder calls in mock mode = %+v, want none beyond the live report", calls[1:])
+ }
+}
diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.go
index b7d3708922..f14c2d1d55 100644
--- a/internal/monitoring/monitor_host_agents_test.go
+++ b/internal/monitoring/monitor_host_agents_test.go
@@ -5641,6 +5641,66 @@ func TestMockModeDiscardsRealHostReports(t *testing.T) {
})
}
+// Report ingest records an agent's identity on its token only for a host the
+// monitor resolved and holds under that token, judged on the report's own
+// hostname. That rests on three properties of the returned host, pinned here:
+// an applied report carries the token's ID, a report the ordering watermark
+// rejects returns the stored host with the stored hostname rather than its
+// own, and mock mode's discard acknowledgement carries no token at all.
+func TestApplyHostReportStampsTheTokenOnlyOnHostsItHolds(t *testing.T) {
+ token := &config.APITokenRecord{ID: "token-a", Name: "agent token"}
+ newMonitor := func(t *testing.T) *Monitor {
+ t.Helper()
+ return &Monitor{
+ state: models.NewState(),
+ resourceStore: unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil)),
+ hostContinuityStore: config.NewHostContinuityStore(t.TempDir(), nil),
+ rateTracker: NewRateTracker(),
+ }
+ }
+ report := func(hostname string, at time.Time) agentshost.Report {
+ return agentshost.Report{
+ Agent: agentshost.AgentInfo{ID: "machine-a", Version: "6.5.0", IntervalSeconds: 30},
+ Host: agentshost.HostInfo{ID: "machine-a", MachineID: "machine-a", Hostname: hostname, Platform: "linux"},
+ Timestamp: at,
+ }
+ }
+
+ previous := mock.IsMockEnabled()
+ mustSetMockEnabled(t, false)
+ t.Cleanup(func() { _ = mock.SetEnabled(previous) })
+
+ m := newMonitor(t)
+ start := time.Now().UTC().Add(-time.Minute)
+ first := report("node.site-b", start)
+ applied, err := m.ApplyHostReport(first, token)
+ if err != nil {
+ t.Fatalf("ApplyHostReport: %v", err)
+ }
+ if applied.ID != "machine-a" || applied.TokenID != token.ID || applied.Hostname != "node.site-b" {
+ t.Fatalf("applied host = %q token %q hostname %q, want machine-a under %q as node.site-b", applied.ID, applied.TokenID, applied.Hostname, token.ID)
+ }
+ if _, err := m.ApplyHostReport(report("node", start.Add(30*time.Second)), token); err != nil {
+ t.Fatalf("ApplyHostReport newer: %v", err)
+ }
+ replayed, err := m.ApplyHostReport(first, token)
+ if err != nil {
+ t.Fatalf("ApplyHostReport replay: %v", err)
+ }
+ if replayed.TokenID != token.ID || replayed.Hostname != "node" {
+ t.Fatalf("replayed report returned token %q hostname %q, want the stored host under %q as node", replayed.TokenID, replayed.Hostname, token.ID)
+ }
+
+ mustSetMockEnabled(t, true)
+ discarded, err := newMonitor(t).ApplyHostReport(report("node", time.Now().UTC()), token)
+ if err != nil {
+ t.Fatalf("mock mode ApplyHostReport: %v", err)
+ }
+ if discarded.ID != "machine-a" || discarded.TokenID != "" {
+ t.Fatalf("mock acknowledgement = %q token %q, want the echoed ID with no token", discarded.ID, discarded.TokenID)
+ }
+}
+
// The agent-authored privilege profile must survive ingest into model state
// exactly, and a report without one must not invent a profile.
func TestApplyHostReportCarriesAgentPrivilegeProfile(t *testing.T) {