package api import ( "net/http" "strings" "time" "github.com/rcourtman/pulse-go-rewrite/internal/agentexec" "github.com/rcourtman/pulse-go-rewrite/internal/api/agentbinding" "github.com/rcourtman/pulse-go-rewrite/internal/api/agenttokens" "github.com/rcourtman/pulse-go-rewrite/internal/config" "github.com/rcourtman/pulse-go-rewrite/internal/monitoring" "github.com/rs/zerolog/log" ) const ( agentInstallIssuedViaConfig = "config_agent_install_command" agentInstallIssuedViaHosted = "hosted_agent_install_command" agentExecBindingVersionKey = "agent_exec_binding_version" agentExecBindingVersion = "2" ) type agentExecMetadataValue struct { value string present bool } func snapshotAgentExecMetadata(metadata map[string]string, keys ...string) map[string]agentExecMetadataValue { snapshot := make(map[string]agentExecMetadataValue, len(keys)) for _, key := range keys { value, present := metadata[key] snapshot[key] = agentExecMetadataValue{value: value, present: present} } return snapshot } func restoreAgentExecMetadata(metadata map[string]string, snapshot map[string]agentExecMetadataValue) { for key, previous := range snapshot { if previous.present { metadata[key] = previous.value } else { delete(metadata, key) } } } func (r *Router) validateAgentExecToken(token string, agentID string, hostname string) bool { _, ok := r.admitAgentExecToken(token, agentID, hostname) return ok } // agentExecHostnamesMatch compares a bound hostname against the hostname an // agent reports. Short-name vs fully-qualified variants of the same host must // compare equal here the same way they do everywhere else in the system // (unifiedresources.HostnamesEquivalent); the case-insensitive exact branch // keeps IP-literal hostnames comparable, which HostnamesEquivalent rejects. func agentExecHostnamesMatch(bound, requested string) bool { return agentbinding.HostnamesMatch(bound, requested) } // agentExecBindingDecision is the single source of truth for whether an // already-issued agent exec token accepts a registering agent identity, and // which metadata repair the admission path must persist when it does. type agentExecBindingDecision struct { admit bool firstBind bool legacyMigrate bool rebindHostname bool backfillID bool backfillHost bool repairDeployIdentity bool } // evaluateAgentExecBinding computes the admission decision for a token record // and a requesting agent identity without mutating the record. Both the // command-channel admission (admitAgentExecToken) and the agent config gate // (commandConfigAllowedForToken) consume this decision: v6.1.2 shipped them as // two divergent policies, so an agent could be told commands were enabled // while its command channel was rejected, leaving the host permanently on // "Remote control blocked" with reinstall as the only recourse. func evaluateAgentExecBinding(record *config.APITokenRecord, requestedID, requestedHost string) agentExecBindingDecision { decision := agentbinding.Evaluate(record, requestedID, requestedHost) return agentExecBindingDecision{ admit: decision.Admit, firstBind: decision.FirstBind, legacyMigrate: decision.LegacyMigrate, rebindHostname: decision.RebindHostname, backfillID: decision.BackfillID, backfillHost: decision.BackfillHost, repairDeployIdentity: decision.RepairDeployIdentity, } } func (r *Router) admitAgentExecToken(token string, agentID string, hostname string) (agentexec.AgentAdmission, bool) { if r == nil || r.config == nil { return agentexec.AgentAdmission{}, false } requestedID := strings.TrimSpace(agentID) requestedHost := strings.TrimSpace(hostname) config.Mu.Lock() var ( outAdmission agentexec.AgentAdmission outOK bool ) _ = r.persistence.WithAPITokenWriteLock(func() error { if r.persistence != nil { if err := r.persistence.SyncPendingRootImportTokensAlreadyLocked(r.config); err != nil { return nil } } outAdmission, outOK = r.admitAgentExecTokenAlreadyLocked(token, requestedID, requestedHost) return nil }) config.Mu.Unlock() return outAdmission, outOK } func (r *Router) admitAgentExecTokenAlreadyLocked(token string, requestedID string, requestedHost string) (agentexec.AgentAdmission, bool) { record, ok := r.config.ValidateAPIToken(token) if !ok { // This is the branch a stale-enrollment agent hits: it holds a token // from a prior install that this server no longer recognises. It was // previously the only rejection path with no log, which made a looping // "Invalid token" agent impossible to diagnose without reading source. log.Warn(). Str("agent_id", requestedID). Str("hostname", requestedHost). Msg("Agent exec token not recognized by this server: re-run the agent installer to re-enroll this agent") return agentexec.AgentAdmission{}, false } tokenID := record.ID if !record.HasScope(config.ScopeAgentExec) { log.Warn(). Str("token_id", tokenID). Msg("Agent exec token missing required scope: agent:exec") return agentexec.AgentAdmission{}, false } orgs := record.GetBoundOrgs() if len(orgs) > 1 { log.Warn(). Str("token_id", tokenID). Strs("organization_ids", orgs). Msg("Agent exec token rejected because command sessions require one organization binding") return agentexec.AgentAdmission{}, false } organizationID := "default" if len(orgs) == 1 && strings.TrimSpace(orgs[0]) != "" { organizationID = strings.TrimSpace(orgs[0]) } runtimeRole := strings.TrimSpace(record.Metadata[agenttokens.RuntimeRoleMetadataKey]) if runtimeRole == agenttokens.CredentialKindMonitoringCollector { log.Warn().Str("token_id", tokenID).Msg("Monitoring collector credential rejected by action listener") return agentexec.AgentAdmission{}, false } if runtimeRole == agenttokens.CredentialKindActionRunner { if len(orgs) != 1 { log.Warn().Str("token_id", tokenID).Msg("Action runner credential requires one explicit organization binding") return agentexec.AgentAdmission{}, false } idCount := 0 for index := range r.config.APITokens { if r.config.APITokens[index].ID == tokenID { idCount++ if idCount > 1 { log.Warn().Str("token_id", tokenID).Msg("Action runner credential refused: ambiguous duplicate token ID") return agentexec.AgentAdmission{}, false } } } decision := agentbinding.EvaluateActionRunner(record, requestedID, requestedHost) if !decision.Admit { log.Warn().Str("token_id", tokenID).Msg("Action runner credential binding or capability mismatch") return agentexec.AgentAdmission{}, false } capability := strings.TrimSpace(record.Metadata[agenttokens.ActionCapabilityMetadataKey]) canonicalHostname := strings.TrimSpace(record.Metadata["bound_hostname"]) activationPending := strings.TrimSpace(record.Metadata[agenttokens.ActionRunnerActivationPendingMetadataKey]) == "true" if !activationPending { // Medium #2: Enforce the same active-runner exclusivity check at // admission as at dispatch so a second active runner cannot replace // or evict the existing transport. for otherIdx := range r.config.APITokens { other := &r.config.APITokens[otherIdx] if other == record || other.IsExpired() { continue } if strings.TrimSpace(other.Metadata[agenttokens.RuntimeRoleMetadataKey]) != agenttokens.CredentialKindActionRunner || strings.TrimSpace(other.Metadata[agenttokens.ActionRunnerActivationPendingMetadataKey]) == "true" { continue } if strings.TrimSpace(other.Metadata["bound_agent_id"]) != requestedID { continue } otherOrgs := other.GetBoundOrgs() if len(otherOrgs) == 1 && strings.TrimSpace(otherOrgs[0]) == organizationID { log.Warn().Str("token_id", tokenID).Str("requested_id", requestedID).Msg("Action runner credential refused: another active runner owns this agent") return agentexec.AgentAdmission{}, false } } } return agentexec.AgentAdmission{ OrganizationID: organizationID, TokenID: tokenID, TokenHash: record.Hash, AgentID: requestedID, Hostname: canonicalHostname, RuntimeRole: agentexec.RuntimeRoleActionRunner, ActionCapability: capability, ActivationPending: activationPending, }, true } if runtimeRole != "" && runtimeRole != agenttokens.CredentialKindLegacyFullTrust { log.Warn().Str("token_id", tokenID).Str("runtime_role", runtimeRole).Msg("Agent exec token has unsupported runtime role") return agentexec.AgentAdmission{}, false } boundID := strings.TrimSpace(record.Metadata["bound_agent_id"]) boundHost := strings.TrimSpace(record.Metadata["bound_hostname"]) decision := evaluateAgentExecBinding(record, requestedID, requestedHost) // A first bind, a legacy migration and an ID backfill each put on this // token an agent ID that only the registration names. The token's own // record cannot say whose ID that is, so the binding decision alone let an // unused install token take the ID of a host enrolled under another token, // and with it that host's command session. Refuse before anything is // persisted, so the refused token stays free to bind its own identity. // Enforce exclusive ownership across BOTH new bindings (first bind, // migration, backfill) AND already-bound admission so two distinct // credentials sharing a token ID or bound_agent_id can never share a // command-agent identity. if (decision.admit || decision.firstBind || decision.legacyMigrate || decision.backfillID) && r.agentExecIdentityHeldByAnotherToken(organizationID, record, requestedID) { log.Warn(). Str("token_id", tokenID). Str("organization_id", organizationID). Str("requested_id", requestedID). Str("requested_hostname", requestedHost). Msg("Agent exec token refused: the registering agent identity belongs to another token or ambiguous token ID") return agentexec.AgentAdmission{}, false } switch { case decision.firstBind: issuedVia := strings.TrimSpace(record.Metadata["issued_via"]) installType := strings.TrimSpace(record.Metadata["install_type"]) if record.Metadata == nil { record.Metadata = make(map[string]string) } previousMetadata := snapshotAgentExecMetadata( record.Metadata, "bound_agent_id", "bound_hostname", "bound_at", agentExecBindingVersionKey, agenttokens.RuntimeRoleMetadataKey, ) record.Metadata["bound_agent_id"] = requestedID // A bound_hostname already written by the Proxmox auto-register // bootstrap is authoritative: it is what the still-unconsumed install // grant compares against, so an equivalent-but-different spelling // reported by the agent must not overwrite it. if strings.TrimSpace(record.Metadata["bound_hostname"]) == "" { record.Metadata["bound_hostname"] = requestedHost } record.Metadata["bound_at"] = time.Now().UTC().Format(time.RFC3339) record.Metadata[agentExecBindingVersionKey] = agentExecBindingVersion record.Metadata[agenttokens.RuntimeRoleMetadataKey] = agenttokens.CredentialKindLegacyFullTrust if r.persistence != nil { if err := r.persistence.SaveAPITokensAlreadyLocked(r.config.APITokens); err != nil { if !config.IsDurablePublishSyncError(err) { restoreAgentExecMetadata(record.Metadata, previousMetadata) } log.Error(). Err(err). Str("token_id", tokenID). Str("hostname", requestedHost). Msg("Failed to persist first-use agent exec token binding, command registration denied") return agentexec.AgentAdmission{}, false } } log.Info(). Str("token_id", tokenID). Str("hostname", requestedHost). Str("issued_via", issuedVia). Str("install_type", installType). Msg("Bound agent install token to first command agent registration") return agentexec.AgentAdmission{ OrganizationID: organizationID, TokenID: tokenID, TokenHash: record.Hash, AgentID: requestedID, Hostname: requestedHost, RuntimeRole: agentexec.RuntimeRoleLegacyFullTrust, }, true case decision.legacyMigrate: previousID := boundID previousMetadata := snapshotAgentExecMetadata( record.Metadata, "bound_agent_id", "bound_at", agentExecBindingVersionKey, agenttokens.RuntimeRoleMetadataKey, agentbinding.DeployIdentityKey, ) record.Metadata["bound_agent_id"] = requestedID record.Metadata["bound_at"] = time.Now().UTC().Format(time.RFC3339) record.Metadata[agentExecBindingVersionKey] = agentExecBindingVersion record.Metadata[agenttokens.RuntimeRoleMetadataKey] = agenttokens.CredentialKindLegacyFullTrust if decision.repairDeployIdentity { record.Metadata[agentbinding.DeployIdentityKey] = agentbinding.DeployIdentityRepaired } if r.persistence != nil { if err := r.persistence.SaveAPITokensAlreadyLocked(r.config.APITokens); err != nil { if !config.IsDurablePublishSyncError(err) { restoreAgentExecMetadata(record.Metadata, previousMetadata) } log.Error(). Err(err). Str("token_id", tokenID). Msg("Failed to persist legacy agent exec identity migration, command registration denied") return agentexec.AgentAdmission{}, false } } log.Info(). Str("token_id", tokenID). Str("previous_agent_id", previousID). Str("agent_id", requestedID). Str("hostname", requestedHost). Msg("Migrated legacy hostname-bound agent exec token to immutable runtime identity") return agentexec.AgentAdmission{ OrganizationID: organizationID, TokenID: tokenID, TokenHash: record.Hash, AgentID: requestedID, Hostname: requestedHost, RuntimeRole: agentexec.RuntimeRoleLegacyFullTrust, }, true case decision.admit: previousHost := boundHost previousMetadata := snapshotAgentExecMetadata( record.Metadata, "bound_agent_id", "bound_hostname", "bound_at", agentExecBindingVersionKey, agenttokens.RuntimeRoleMetadataKey, ) metadataChanged := runtimeRole == "" if runtimeRole == "" { record.Metadata[agenttokens.RuntimeRoleMetadataKey] = agenttokens.CredentialKindLegacyFullTrust } if decision.backfillID { record.Metadata["bound_agent_id"] = requestedID boundID = requestedID metadataChanged = true } if decision.backfillHost || decision.rebindHostname { record.Metadata["bound_hostname"] = requestedHost boundHost = requestedHost metadataChanged = true } if metadataChanged { record.Metadata["bound_at"] = time.Now().UTC().Format(time.RFC3339) record.Metadata[agentExecBindingVersionKey] = agentExecBindingVersion } if metadataChanged && r.persistence != nil { if err := r.persistence.SaveAPITokensAlreadyLocked(r.config.APITokens); err != nil { if !config.IsDurablePublishSyncError(err) { restoreAgentExecMetadata(record.Metadata, previousMetadata) } log.Error(). Err(err). Str("token_id", tokenID). Msg("Failed to persist migrated agent exec token binding, command registration denied") return agentexec.AgentAdmission{}, false } } if decision.rebindHostname { log.Info(). Str("token_id", tokenID). Str("agent_id", requestedID). Str("previous_hostname", previousHost). Str("hostname", requestedHost). Msg("Re-bound agent exec token hostname for matching immutable agent identity") } return agentexec.AgentAdmission{ OrganizationID: organizationID, TokenID: tokenID, TokenHash: record.Hash, AgentID: requestedID, Hostname: requestedHost, RuntimeRole: agentexec.RuntimeRoleLegacyFullTrust, }, true } if boundID == "" && boundHost == "" { log.Warn(). Str("token_id", tokenID). Msg("Agent exec token missing binding metadata") return agentexec.AgentAdmission{}, false } log.Warn(). Str("token_id", tokenID). Str("bound_id", boundID). Str("bound_hostname", boundHost). Str("requested_id", requestedID). Str("requested_hostname", requestedHost). Msg("Agent token mismatch: token is not bound to the registering agent") return agentexec.AgentAdmission{}, false } // agentExecIdentityHeldByAnotherToken reports whether an agent ID that a // command registration would newly bind to a token already belongs to another // credential of the same organization. The caller holds config.Mu. // // The report path is the authority on which token holds a host ID: it forks a // colliding report onto its own ID and hands an existing ID to a fresh token // only as a re-enrollment, and the acknowledgement names a command identity // only for a host the monitor holds under the reporting token. So a host the // monitor holds decides: its own token may bind it (a reinstall that took the // host over, whatever the superseded token is still bound to), and no other // token may. Live state loses agent-reported hosts across a restart until the // next report lands, and an agent whose host is not in state has no holder, so // an ID the monitor does not hold falls back to the durable record: an // unexpired token of this organization that is already bound to it. An ID // neither knows is free, which is what first-use binding exists for. // // The config gate needs no matching check: it judges a token only against the // host the monitor holds under that token. func (r *Router) agentExecIdentityHeldByAnotherToken(organizationID string, record *config.APITokenRecord, agentID string) bool { if record == nil { return true } tokenID := record.ID // Reject ambiguous token IDs shared by distinct credentials before persisting // a first bind, migration, or ID backfill: live hosts and command sessions // identify their holder by token ID, so two credentials sharing an ID cannot // safely claim command-agent ownership. matchingIDCount := 0 for index := range r.config.APITokens { if r.config.APITokens[index].ID == tokenID { matchingIDCount++ if matchingIDCount > 1 { return true } } } if r.agentExecServer != nil { if liveTokenID, ok := r.agentExecServer.ConnectedAgentTokenIDForOrganization(organizationID, agentID); ok && liveTokenID != tokenID { for index := range r.config.APITokens { other := &r.config.APITokens[index] if other.ID != liveTokenID || other.IsExpired() { continue } otherOrganizationID := "default" if orgs := other.GetBoundOrgs(); len(orgs) == 1 && strings.TrimSpace(orgs[0]) != "" { otherOrganizationID = strings.TrimSpace(orgs[0]) } if otherOrganizationID == organizationID { return true } } } } var monitor *monitoring.Monitor r.monitorMu.RLock() defaultMonitor := r.monitor mtMonitor := r.mtMonitor r.monitorMu.RUnlock() if organizationID == "default" { monitor = defaultMonitor } else if mtMonitor != nil { // Peek only. A registration must not start a tenant runtime, and a // runtime that is not loaded holds no live hosts to ask about. monitor, _ = mtMonitor.PeekMonitor(organizationID) } if monitor != nil { for _, host := range monitor.GetLiveHostsSnapshot() { if host.ID != agentID { continue } if holder := strings.TrimSpace(host.TokenID); holder != "" { if holder != tokenID { return true } if holderHash := strings.TrimSpace(host.TokenHash); holderHash != "" && strings.TrimSpace(record.Hash) != "" && !constantTimeStringEqual(holderHash, record.Hash) { return true } if strings.TrimSpace(record.Metadata["bound_agent_id"]) == "" { return false } } if holderHash := strings.TrimSpace(host.TokenHash); holderHash != "" && strings.TrimSpace(record.Hash) != "" && !constantTimeStringEqual(holderHash, record.Hash) { return true } break } } for index := range r.config.APITokens { other := &r.config.APITokens[index] if other == record || other.IsExpired() || strings.TrimSpace(other.Metadata["bound_agent_id"]) != agentID { continue } // Medium #3: A pending (unactivated) action-runner credential prepared // during legacy-to-typed migration does not yet own the host and must // not evict the active legacy command session before activation. if strings.TrimSpace(other.Metadata[agenttokens.RuntimeRoleMetadataKey]) == agenttokens.CredentialKindActionRunner && strings.TrimSpace(other.Metadata[agenttokens.ActionRunnerActivationPendingMetadataKey]) == "true" { continue } otherOrganizationID := "default" if orgs := other.GetBoundOrgs(); len(orgs) == 1 && strings.TrimSpace(orgs[0]) != "" { otherOrganizationID = strings.TrimSpace(orgs[0]) } if otherOrganizationID == organizationID { return true } } return 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) { r.recordReportedAgentIdentityWithCredential(organizationID, tokenID, "", "", false, presentedID, hostID, hostname) } func (r *Router) recordReportedAgentIdentityForToken(req *http.Request, monitor *monitoring.Monitor, organizationID string, admitted *config.APITokenRecord, presentedID, hostID, hostname string) { if admitted == nil { return } var targetCfg *config.Config var targetPersistence *config.ConfigPersistence if monitor != nil && req != nil { if invs := resolveAuthenticatingInventories(req, monitor); len(invs) > 0 { targetCfg = invs[0].Config targetPersistence = invs[0].Persistence if r != nil && targetCfg == r.config && r.persistence != nil { targetPersistence = r.persistence } } else { return } } else if r != nil { targetCfg = r.config targetPersistence = r.persistence } r.recordReportedAgentIdentityInInventory(targetCfg, targetPersistence, organizationID, admitted.ID, admitted.Hash, apiTokenAuthenticatedUser(admitted), true, presentedID, hostID, hostname) } func (r *Router) recordReportedAgentIdentityWithCredential(organizationID, tokenID, expectedHash, expectedOwner string, matchCredential bool, presentedID, hostID, hostname string) { if r == nil { return } r.recordReportedAgentIdentityInInventory(r.config, r.persistence, organizationID, tokenID, expectedHash, expectedOwner, matchCredential, presentedID, hostID, hostname) } func (r *Router) recordReportedAgentIdentityInInventory(targetCfg *config.Config, targetPersistence *config.ConfigPersistence, organizationID, tokenID, expectedHash, expectedOwner string, matchCredential bool, presentedID, hostID, hostname string) { if targetCfg == 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() _ = targetPersistence.WithAPITokenWriteLock(func() error { var tokens []config.APITokenRecord usingDiskAuthoritative := false if targetPersistence != nil { if err := targetPersistence.SyncPendingRootImportTokensAlreadyLocked(targetCfg); err != nil { return nil } // High #2: Load authoritative on-disk inventory under the directory // write lock so a retired tenant monitor's stale Config pointer can // NEVER overwrite a freshly imported tenant api_tokens.json or // restore revoked credentials before ReloadTenant finishes. diskTokens, diskExists, loadErr := targetPersistence.LoadAPITokensWithExistsAlreadyLocked() if loadErr != nil { return nil } if diskExists { config.SortAPITokens(diskTokens) tokens = diskTokens usingDiskAuthoritative = true } else { targetCfg.SortAPITokens() tokens = targetCfg.APITokens } } else { targetCfg.SortAPITokens() tokens = targetCfg.APITokens } for index := range tokens { record := &tokens[index] if matchCredential { if !constantTimeStringEqual(record.Hash, expectedHash) { continue } // Mirror authentication's first-matching-hash rule: if a newer or // different record now shadows expectedHash, refuse to bind. if record.ID != tokenID || apiTokenAuthenticatedUser(record) != expectedOwner { return nil } } else if record.ID != tokenID { continue } // High #5: Revalidate live ScopeAgentReport and organization grant // before persisting an immutable bound_agent_id. if record.IsExpired() || !record.HasScope(config.ScopeAgentReport) { return nil } if len(record.GetBoundOrgs()) > 0 { if !record.CanAccessOrg(organizationID) { return nil } } else if organizationID != "default" { return nil } if !agentbinding.EvaluateReportedIdentity(record, presentedID, hostID, hostname) { return nil } // Refuse report-driven bound_agent_id persistence if duplicate token IDs // exist or another live/durable token already owns hostID in this org. idMatches := 0 for otherIdx := range tokens { other := &tokens[otherIdx] if other.ID == record.ID { idMatches++ if idMatches > 1 { return nil } } if other == record || other.IsExpired() || strings.TrimSpace(other.Metadata["bound_agent_id"]) != hostID { continue } otherOrg := "default" if orgs := other.GetBoundOrgs(); len(orgs) == 1 && strings.TrimSpace(orgs[0]) != "" { otherOrg = strings.TrimSpace(orgs[0]) } if otherOrg == organizationID { return nil } } if r != nil && targetCfg == r.config && r.agentExecIdentityHeldByAnotherToken(organizationID, record, hostID) { return nil } previousMetadata := snapshotAgentExecMetadata( record.Metadata, "bound_agent_id", "bound_at", agentExecBindingVersionKey, ) if record.Metadata == nil { record.Metadata = make(map[string]string) } record.Metadata["bound_agent_id"] = hostID record.Metadata["bound_at"] = time.Now().UTC().Format(time.RFC3339) record.Metadata[agentExecBindingVersionKey] = agentExecBindingVersion if targetPersistence != nil { if err := targetPersistence.SaveAPITokensAlreadyLocked(tokens); err != nil { if config.IsDurablePublishSyncError(err) { if usingDiskAuthoritative { targetCfg.APITokens = tokens targetCfg.SortAPITokens() } } else { 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 will retry") return nil } boundHostname := strings.TrimSpace(record.Metadata["bound_hostname"]) if usingDiskAuthoritative { targetCfg.APITokens = tokens targetCfg.SortAPITokens() } log.Info(). Str("token_id", tokenID). Str("agent_id", hostID). Str("hostname", boundHostname). Msg("Bound hostname-bound agent token to the agent identity its reports resolve to") return nil } 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 nil } return nil }) } func (r *Router) validateAgentExecSession(admission agentexec.AgentAdmission) bool { if r == nil || r.config == nil { return false } tokenID := strings.TrimSpace(admission.TokenID) tokenHash := strings.TrimSpace(admission.TokenHash) requestedID := strings.TrimSpace(admission.AgentID) requestedHost := strings.TrimSpace(admission.Hostname) if tokenID == "" || tokenHash == "" || requestedID == "" || requestedHost == "" { return false } config.Mu.Lock() defer config.Mu.Unlock() if config.HasPendingRootTokensImportForConfig(r.config) { return false } for index := range r.config.APITokens { record := &r.config.APITokens[index] if !constantTimeStringEqual(record.Hash, tokenHash) { continue } // Authentication stops at the first matching credential hash (including // expired or shadowing records). Never fall through to a later record. if record.ID != tokenID || record.IsExpired() || !record.HasScope(config.ScopeAgentExec) { return false } orgs := record.GetBoundOrgs() organizationID := "default" if len(orgs) > 1 { return false } if len(orgs) == 1 && strings.TrimSpace(orgs[0]) != "" { organizationID = strings.TrimSpace(orgs[0]) } runtimeRole := strings.TrimSpace(record.Metadata[agenttokens.RuntimeRoleMetadataKey]) // Enforce unique token ID across the live inventory on dispatch just as // on admission so an imported duplicate ID revokes an active socket. idMatches := 0 for otherIdx := range r.config.APITokens { if r.config.APITokens[otherIdx].ID == record.ID { idMatches++ if idMatches > 1 { return false } } } if runtimeRole == agenttokens.CredentialKindActionRunner { if !admission.ActivationPending && strings.TrimSpace(record.Metadata[agenttokens.ActionRunnerActivationPendingMetadataKey]) == "true" { return false } // Refuse dispatch if another active (non-pending, non-expired) action // runner credential also claims the same agent identity in this org. for otherIdx := range r.config.APITokens { other := &r.config.APITokens[otherIdx] if other == record || other.IsExpired() { continue } if strings.TrimSpace(other.Metadata[agenttokens.RuntimeRoleMetadataKey]) != agenttokens.CredentialKindActionRunner || strings.TrimSpace(other.Metadata[agenttokens.ActionRunnerActivationPendingMetadataKey]) == "true" { continue } if strings.TrimSpace(other.Metadata["bound_agent_id"]) != requestedID { continue } otherOrgs := other.GetBoundOrgs() if len(otherOrgs) == 1 && strings.TrimSpace(otherOrgs[0]) == organizationID { return false } } return len(orgs) == 1 && strings.TrimSpace(admission.RuntimeRole) == agentexec.RuntimeRoleActionRunner && strings.TrimSpace(admission.ActionCapability) == agentexec.ActionCapabilityTypedV1 && organizationID == strings.TrimSpace(admission.OrganizationID) && agentbinding.EvaluateActionRunner(record, requestedID, requestedHost).Admit } if runtimeRole != agenttokens.CredentialKindLegacyFullTrust { return false } if r.agentExecIdentityHeldByAnotherToken(organizationID, record, requestedID) { return false } return strings.TrimSpace(admission.RuntimeRole) == agentexec.RuntimeRoleLegacyFullTrust && organizationID == strings.TrimSpace(admission.OrganizationID) && strings.TrimSpace(record.Metadata["bound_agent_id"]) == requestedID && agentExecHostnamesMatch(strings.TrimSpace(record.Metadata["bound_hostname"]), requestedHost) } return false } // agentCommandSessionConnected reports whether a live command channel exists // for a telemetry host. host.TokenID is sticky across token revocation and // rotation (monitoring keeps the last-seen token on the host record), so a // token-scoped miss must not be authoritative: fall through to the agent-ID // lookup before declaring the channel disconnected. The token-first order still // lets the canonical enrollment token win when its session is live. A hostname // cannot answer: while this machine is offline, another machine with its name // would read as this one's channel (#2681). func (r *Router) agentCommandSessionConnected(organizationID, tokenID, agentID string) bool { if r == nil || r.agentExecServer == nil { return false } if strings.TrimSpace(tokenID) != "" { if _, connected := r.agentExecServer.GetAgentForTokenForOrganization(organizationID, tokenID); connected { return true } } return strings.TrimSpace(agentID) != "" && r.agentExecServer.IsAgentConnectedForOrganization(organizationID, agentID) } func canBindAgentInstallExecToken(record *config.APITokenRecord, agentID string, hostname string) bool { return agentbinding.CanBindInstallToken(record, agentID, hostname) } // canBindAutoRegisteredAgentInstallExecToken reports whether an install token // whose bound_hostname was populated by the Proxmox auto-register bootstrap may // take the clean first-use exec bind. The registration path writes // bound_hostname without bound_agent_id or a binding version, so the record // looks identical to a pre-v6.1.1 deploy token; without this the first command // enrollment of a freshly installed Proxmox host is admitted by the // legacy-migration branch, which exists to repair old records and is not the // contract this flow should depend on. Hostname equivalence is still required. func canBindAutoRegisteredAgentInstallExecToken(record *config.APITokenRecord, agentID string, hostname string) bool { return agentbinding.CanBindAutoRegisteredInstallToken(record, agentID, hostname) }