mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-03 18:43:38 +01:00
I added Schema v26 content-free Infrastructure Map topology read telemetry for external live GET /api/agent/topology requests (total read days, CLI days, MCP days, anonymized days, and an explicit availability flag) alongside hardened opt-out zero-write boundaries, credential-binding checks, and read-only SQLite/config guards. Key changes: - Added a dedicated root-scoped daily tally store (infrastructure_map_topology_tally.json) with strict schema validation, fail-closed degraded sidecar accounting, and strict zero-write guarantees when telemetry is disabled by settings or PULSE_TELEMETRY=false. - Added X-Pulse-Agent-Surface attribution for pulse-cli and MCP clients while filtering out first-party browser traffic, mock-mode snapshots, and unverified monitor states. - Updated Settings payload preview, localization copy, shipped PRIVACY.md disclosure, integration specs, and schema parity tooling for Schema v26. - Hardened host/agent token hash binding, self-uninstall live authority and durable hash-scoped tombstones, Patrol investigation replay-floor provenance, bounded non-blocking regular-file config reads, and cold read-only legacy SQLite history queries.
1914 lines
68 KiB
Go
1914 lines
68 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"crypto/ed25519"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"net/http"
|
|
"strings"
|
|
"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"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/remoteconfig"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/utils"
|
|
"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"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
const (
|
|
configSignatureTTL = 15 * time.Minute
|
|
agentRoutePrefix = "/api/agents/agent/"
|
|
legacyHostRoutePrefix = "/api/agents/host/"
|
|
)
|
|
|
|
var configSigningState struct {
|
|
once sync.Once
|
|
key ed25519.PrivateKey
|
|
err error
|
|
}
|
|
|
|
// UnifiedAgentHandlers manages ingest from the runtime-side Unified Agent module of pulse-agent.
|
|
type UnifiedAgentHandlers struct {
|
|
baseAgentHandlers
|
|
rootConfig *config.Config
|
|
|
|
// serverVersion is echoed on report acknowledgements so agents can spot a
|
|
// server upgrade on their next report instead of their next hourly update
|
|
// 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)
|
|
recordReportedIdentityForToken func(req *http.Request, monitor *monitoring.Monitor, organizationID string, admitted *config.APITokenRecord, presentedID, hostID, hostname string)
|
|
|
|
configFetchAudits *agentConfigFetchAuditTracker
|
|
}
|
|
|
|
// SetServerVersion supplies the running server version to include on report
|
|
// acknowledgements. Call once at wiring time; an empty version keeps acks
|
|
// version-free.
|
|
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 (h *UnifiedAgentHandlers) SetReportedIdentityTokenRecorder(record func(req *http.Request, monitor *monitoring.Monitor, organizationID string, admitted *config.APITokenRecord, presentedID, hostID, hostname string)) {
|
|
h.recordReportedIdentityForToken = record
|
|
}
|
|
|
|
func trimUnifiedAgentRoutePath(path string) string {
|
|
for _, prefix := range []string{agentRoutePrefix, legacyHostRoutePrefix} {
|
|
if strings.HasPrefix(path, prefix) {
|
|
return strings.TrimPrefix(path, prefix)
|
|
}
|
|
}
|
|
return path
|
|
}
|
|
|
|
// NewUnifiedAgentHandlers constructs a new handler set for Pulse Unified Agent ingest.
|
|
func (h *UnifiedAgentHandlers) SetRootConfig(cfg *config.Config) {
|
|
if h == nil {
|
|
return
|
|
}
|
|
h.rootConfig = cfg
|
|
}
|
|
|
|
func NewUnifiedAgentHandlers(mtm *monitoring.MultiTenantMonitor, m *monitoring.Monitor, hub *websocket.Hub) *UnifiedAgentHandlers {
|
|
return &UnifiedAgentHandlers{
|
|
baseAgentHandlers: newBaseAgentHandlers(mtm, m, hub),
|
|
configFetchAudits: newAgentConfigFetchAuditTracker(),
|
|
}
|
|
}
|
|
|
|
// HandleReport ingests Pulse Unified Agent reports.
|
|
func (h *UnifiedAgentHandlers) HandleReport(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only POST is allowed", nil)
|
|
return
|
|
}
|
|
|
|
var report agentshost.Report
|
|
// Support gzip-compressed reports from agents (backward compatible with
|
|
// uncompressed), with independent encoded and decoded size limits.
|
|
if !decodeCompressedAgentReport(w, r, 256*1024, 1536*1024, &report) {
|
|
return
|
|
}
|
|
|
|
if report.Timestamp.IsZero() {
|
|
report.Timestamp = time.Now().UTC()
|
|
}
|
|
|
|
monitor := h.requireMonitor(w, r)
|
|
if monitor == nil {
|
|
return
|
|
}
|
|
tokenRecord := getAPITokenRecordFromRequest(r)
|
|
host, reportAccepted, err := monitor.ApplyHostReportWithStatus(report, tokenRecord)
|
|
if err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_report", err.Error(), nil)
|
|
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 tokenRecord != nil && host.TokenID == tokenRecord.ID &&
|
|
agentbinding.EvaluateReportedIdentity(tokenRecord, report.Agent.ID, host.ID, reportedHostname) {
|
|
if h.recordReportedIdentityForToken != nil {
|
|
h.recordReportedIdentityForToken(r, monitor, GetOrgID(r.Context()), tokenRecord, report.Agent.ID, host.ID, reportedHostname)
|
|
} else if h.recordReportedIdentity != nil {
|
|
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
|
|
// survives remove/reinstall and immediately shuts down an agent launched
|
|
// with --enable-commands (#1728).
|
|
orgID := GetOrgID(r.Context())
|
|
var (
|
|
liveToken *config.APITokenRecord
|
|
withdrawn bool
|
|
reconcileErr error
|
|
)
|
|
// Medium #2 + R30 Medium #5: Only reconcile install-token command policy
|
|
// for an accepted, token-owned live host report (never for mock-mode
|
|
// discards or stale/duplicate rejected reports).
|
|
if reportAccepted && tokenRecord != nil && host.TokenID == tokenRecord.ID {
|
|
liveToken, withdrawn, reconcileErr = reconcileInstallTokenCommandPolicyForRequest(r, monitor, tokenRecord, host)
|
|
if reconcileErr != nil {
|
|
log.Error().Err(reconcileErr).
|
|
Str("agent_id", host.ID).
|
|
Str("token_id", tokenID(tokenRecord)).
|
|
Msg("Failed to reconcile install-token command policy")
|
|
}
|
|
} else if tokenRecord != nil {
|
|
liveToken, withdrawn = lookupLiveInstallTokenReadOnly(r, monitor, tokenRecord, orgID)
|
|
}
|
|
// High #3: Decide response command eligibility from the live token record
|
|
// (when token-authenticated) on every exit, never stale admission state.
|
|
effectiveToken := tokenRecord
|
|
if tokenRecord != nil {
|
|
effectiveToken = liveToken
|
|
}
|
|
withholdCommands := withdrawn || reconcileErr != nil ||
|
|
hasPendingCommandPolicyRevert(orgID, host.ID) ||
|
|
monitor.IsHostCommandsEnablePendingAuth(host.ID) ||
|
|
(tokenRecord != nil && liveToken == nil)
|
|
|
|
log.Debug().
|
|
Str("agentId", host.ID).
|
|
Str("hostname", host.Hostname).
|
|
Str("platform", host.Platform).
|
|
Msg("Agent report processed")
|
|
|
|
h.broadcastState(r.Context())
|
|
|
|
// Include any server-side config overrides in the response
|
|
serverConfig := monitor.GetHostAgentConfig(host.ID)
|
|
serverConfig = sanitizeHostAgentConfigForToken(serverConfig, effectiveToken, host)
|
|
if withholdCommands {
|
|
disabled := false
|
|
serverConfig.CommandsEnabled = &disabled
|
|
}
|
|
|
|
resp := map[string]any{
|
|
"success": true,
|
|
"agentId": host.ID,
|
|
"lastSeen": host.LastSeen,
|
|
"platform": host.Platform,
|
|
"osName": host.OSName,
|
|
"osVersion": host.OSVersion,
|
|
}
|
|
if h.serverVersion != "" {
|
|
resp["serverVersion"] = h.serverVersion
|
|
}
|
|
// Name the identity this agent's command channel must register under, for
|
|
// a host the monitor resolved and holds under this token, judged for the
|
|
// hostname this report presents, as its registration will. Mock mode's
|
|
// discard acknowledgement carries no token ID, so it names nothing.
|
|
if !withholdCommands && effectiveToken != nil && host.TokenID == effectiveToken.ID {
|
|
commandHost := host
|
|
commandHost.Hostname = reportedHostname
|
|
if commandAgentID := commandIdentityForToken(effectiveToken, commandHost); commandAgentID != "" {
|
|
resp["commandAgentId"] = commandAgentID
|
|
}
|
|
}
|
|
|
|
// Only include config if there are actual overrides
|
|
if serverConfig.CommandsEnabled != nil {
|
|
resp["config"] = map[string]any{
|
|
"commandsEnabled": serverConfig.CommandsEnabled,
|
|
}
|
|
}
|
|
|
|
if err := utils.WriteJSONResponse(w, resp); err != nil {
|
|
log.Error().Err(err).Msg("Failed to serialize agent response")
|
|
}
|
|
}
|
|
|
|
type pendingCommandPolicyRevert struct {
|
|
tokenID string
|
|
tokenHash string
|
|
}
|
|
|
|
type refCountedCommandPolicyMutex struct {
|
|
mu sync.Mutex
|
|
refs int
|
|
}
|
|
|
|
var (
|
|
pendingCommandPolicyRevertsMu sync.Mutex
|
|
pendingCommandPolicyReverts = make(map[string]pendingCommandPolicyRevert)
|
|
|
|
hostCommandPolicyLocksMu sync.Mutex
|
|
hostCommandPolicyLocks = make(map[string]*refCountedCommandPolicyMutex)
|
|
)
|
|
|
|
func commandPolicyRevertKey(orgID, hostID string) string {
|
|
orgID = strings.TrimSpace(orgID)
|
|
if orgID == "" {
|
|
orgID = "default"
|
|
}
|
|
return orgID + "\x00" + strings.TrimSpace(hostID)
|
|
}
|
|
|
|
// lockHostCommandPolicy acquires a per-(orgID, hostID) reconciliation lock
|
|
// using a reference-counted map entry so completed/removed hosts never leak
|
|
// mutexes for the lifetime of the process (Low #2).
|
|
func lockHostCommandPolicy(orgID, hostID string) func() {
|
|
key := commandPolicyRevertKey(orgID, hostID)
|
|
hostCommandPolicyLocksMu.Lock()
|
|
entry := hostCommandPolicyLocks[key]
|
|
if entry == nil {
|
|
entry = &refCountedCommandPolicyMutex{}
|
|
hostCommandPolicyLocks[key] = entry
|
|
}
|
|
entry.refs++
|
|
hostCommandPolicyLocksMu.Unlock()
|
|
|
|
entry.mu.Lock()
|
|
return func() {
|
|
entry.mu.Unlock()
|
|
hostCommandPolicyLocksMu.Lock()
|
|
entry.refs--
|
|
if entry.refs == 0 && hostCommandPolicyLocks[key] == entry {
|
|
delete(hostCommandPolicyLocks, key)
|
|
}
|
|
hostCommandPolicyLocksMu.Unlock()
|
|
}
|
|
}
|
|
|
|
func getPendingCommandPolicyRevert(orgID, hostID string) (pendingCommandPolicyRevert, bool) {
|
|
pendingCommandPolicyRevertsMu.Lock()
|
|
rev, ok := pendingCommandPolicyReverts[commandPolicyRevertKey(orgID, hostID)]
|
|
pendingCommandPolicyRevertsMu.Unlock()
|
|
return rev, ok
|
|
}
|
|
|
|
func setPendingCommandPolicyRevert(orgID, hostID, tokenID, tokenHash string) {
|
|
pendingCommandPolicyRevertsMu.Lock()
|
|
pendingCommandPolicyReverts[commandPolicyRevertKey(orgID, hostID)] = pendingCommandPolicyRevert{
|
|
tokenID: strings.TrimSpace(tokenID),
|
|
tokenHash: strings.TrimSpace(tokenHash),
|
|
}
|
|
pendingCommandPolicyRevertsMu.Unlock()
|
|
}
|
|
|
|
func clearPendingCommandPolicyRevert(orgID, hostID string, expected pendingCommandPolicyRevert) {
|
|
key := commandPolicyRevertKey(orgID, hostID)
|
|
pendingCommandPolicyRevertsMu.Lock()
|
|
if cur, ok := pendingCommandPolicyReverts[key]; ok &&
|
|
cur.tokenID == expected.tokenID &&
|
|
constantTimeStringEqual(cur.tokenHash, expected.tokenHash) {
|
|
delete(pendingCommandPolicyReverts, key)
|
|
}
|
|
pendingCommandPolicyRevertsMu.Unlock()
|
|
}
|
|
|
|
func hasPendingCommandPolicyRevert(orgID, hostID string) bool {
|
|
_, ok := getPendingCommandPolicyRevert(orgID, hostID)
|
|
return ok
|
|
}
|
|
|
|
func matchesAdmittedInstallToken(live, admitted *config.APITokenRecord) bool {
|
|
if live == nil || admitted == nil || live.ID != admitted.ID {
|
|
return false
|
|
}
|
|
if admitted.Hash != "" && !constantTimeStringEqual(live.Hash, admitted.Hash) {
|
|
return false
|
|
}
|
|
if apiTokenAuthenticatedUser(live) != apiTokenAuthenticatedUser(admitted) {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func reconcileInstallTokenCommandPolicy(monitor *monitoring.Monitor, requestRecord *config.APITokenRecord, host models.Host) error {
|
|
_, _, err := reconcileInstallTokenCommandPolicyForRequest(nil, monitor, requestRecord, host)
|
|
return err
|
|
}
|
|
|
|
func resolveAuthenticatingInventories(req *http.Request, monitor *monitoring.Monitor) []monitoring.APITokenInventory {
|
|
inventories := monitor.APITokenInventories()
|
|
if req == nil {
|
|
return inventories
|
|
}
|
|
if source, ok := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource); ok && source.orgID != "" && source.orgID != "default" {
|
|
config.Mu.RLock()
|
|
requiredTenantCfg := tenantTokenConfigForRequest(req)
|
|
config.Mu.RUnlock()
|
|
filtered := make([]monitoring.APITokenInventory, 0, 1)
|
|
for _, inv := range inventories {
|
|
if inv.Config != nil && inv.Config == requiredTenantCfg {
|
|
filtered = append(filtered, inv)
|
|
}
|
|
}
|
|
return filtered
|
|
}
|
|
if len(inventories) > 1 {
|
|
// Root-authenticated request serving a tenant org: pin strictly to instance inventory.
|
|
return inventories[len(inventories)-1:]
|
|
}
|
|
return inventories
|
|
}
|
|
|
|
func lookupLiveInstallTokenReadOnly(req *http.Request, monitor *monitoring.Monitor, requestRecord *config.APITokenRecord, orgID string) (*config.APITokenRecord, bool) {
|
|
if monitor == nil || requestRecord == nil || strings.TrimSpace(requestRecord.ID) == "" {
|
|
return requestRecord, false
|
|
}
|
|
inventories := resolveAuthenticatingInventories(req, monitor)
|
|
config.Mu.RLock()
|
|
defer config.Mu.RUnlock()
|
|
for _, inventory := range inventories {
|
|
if inventory.Config == nil {
|
|
continue
|
|
}
|
|
if config.HasPendingRootTokensImportForConfig(inventory.Config) {
|
|
return nil, true
|
|
}
|
|
live := findAuthoritativeInstallTokenReadOnly(inventory.Config.APITokens, inventory, requestRecord)
|
|
if live == nil {
|
|
continue
|
|
}
|
|
// High #5: Enforce the same live ScopeAgentReport and org authorization
|
|
// check on rejected/mock reports before granting command eligibility.
|
|
if !liveInstallTokenAuthorizedForOrgReport(live, requestRecord, orgID) {
|
|
return nil, true
|
|
}
|
|
clone := live.Clone()
|
|
return &clone, false
|
|
}
|
|
return nil, true
|
|
}
|
|
|
|
// findAuthoritativeInstallTokenInSlice mirrors authentication's first-matching-hash
|
|
// rule: stop at the first record whose hash matches admitted, and accept it only
|
|
// if its ID, inventory ownership, and admitted identity match.
|
|
// findAuthoritativeInstallTokenReadOnly evaluates first-matching-hash
|
|
// semantics against a sorted copy so RLock callers never mutate APITokens and
|
|
// never accept a shadowed record even if APITokens was mutated out of order.
|
|
func findAuthoritativeInstallTokenReadOnly(tokens []config.APITokenRecord, inventory monitoring.APITokenInventory, admitted *config.APITokenRecord) *config.APITokenRecord {
|
|
if admitted == nil || len(tokens) == 0 {
|
|
return nil
|
|
}
|
|
copied := make([]config.APITokenRecord, len(tokens))
|
|
copy(copied, tokens)
|
|
config.SortAPITokens(copied)
|
|
return findAuthoritativeInstallTokenInSlice(copied, inventory, admitted)
|
|
}
|
|
|
|
func findAuthoritativeInstallTokenInSlice(tokens []config.APITokenRecord, inventory monitoring.APITokenInventory, admitted *config.APITokenRecord) *config.APITokenRecord {
|
|
if admitted == nil {
|
|
return nil
|
|
}
|
|
for i := range tokens {
|
|
candidate := &tokens[i]
|
|
if !constantTimeStringEqual(candidate.Hash, admitted.Hash) {
|
|
continue
|
|
}
|
|
if candidate.ID != admitted.ID || !inventory.Owns(candidate) || !matchesAdmittedInstallToken(candidate, admitted) {
|
|
return nil
|
|
}
|
|
return candidate
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func isInstallTokenAuthorizedForPendingPromotion(live, admitted *config.APITokenRecord, orgID string, host models.Host) bool {
|
|
if live == nil || !liveInstallTokenAuthorizedForOrgReport(live, admitted, orgID) ||
|
|
!evaluateAgentExecBinding(live, host.ID, host.Hostname).admit {
|
|
return false
|
|
}
|
|
curIntent, curHasIntent := agenttokens.ParseCommandPolicyIntent(live)
|
|
if !curHasIntent || !curIntent || !live.HasScope(config.ScopeAgentExec) {
|
|
return false
|
|
}
|
|
return strings.TrimSpace(live.Metadata[agenttokens.CommandPolicyAppliedAgentIDMetadataKey]) == host.ID
|
|
}
|
|
|
|
func liveInstallTokenAuthorizedForOrgReport(live, admitted *config.APITokenRecord, orgID string) bool {
|
|
if live == nil || live.IsExpired() {
|
|
return false
|
|
}
|
|
if !live.HasScope(config.ScopeAgentReport) {
|
|
return false
|
|
}
|
|
normOrg := strings.TrimSpace(orgID)
|
|
if normOrg == "" {
|
|
normOrg = "default"
|
|
}
|
|
if len(live.GetBoundOrgs()) > 0 {
|
|
return live.CanAccessOrg(normOrg)
|
|
}
|
|
// Unbound single-tenant default-org install tokens are valid ONLY for the
|
|
// default organization and ONLY if the admitted credential was also unbound
|
|
// (so an import stripping an org-bound credential never preserves access).
|
|
return normOrg == "default" && (admitted == nil || len(admitted.GetBoundOrgs()) == 0)
|
|
}
|
|
|
|
func reconcileInstallTokenCommandPolicyForRequest(req *http.Request, monitor *monitoring.Monitor, requestRecord *config.APITokenRecord, host models.Host) (*config.APITokenRecord, bool, error) {
|
|
if monitor == nil || requestRecord == nil || strings.TrimSpace(requestRecord.ID) == "" || strings.TrimSpace(host.ID) == "" {
|
|
return requestRecord, false, nil
|
|
}
|
|
|
|
orgID := "default"
|
|
if req != nil {
|
|
orgID = GetOrgID(req.Context())
|
|
}
|
|
// Medium #1 + Medium #4: Fast read-only authority check under config.Mu.RLock()
|
|
// and short map lock ONLY so ordinary reports never acquire config.Mu.Lock(),
|
|
// persistence c.mu, or any cross-host lock.
|
|
if !hasPendingCommandPolicyRevert(orgID, host.ID) && !monitor.IsHostCommandsEnablePendingAuth(host.ID) {
|
|
inventories := resolveAuthenticatingInventories(req, monitor)
|
|
config.Mu.RLock()
|
|
needsWritePath := false
|
|
needsSupersededCheck := false
|
|
var fastLive *config.APITokenRecord
|
|
fastFound := false
|
|
fastWithdrawn := false
|
|
for _, inventory := range inventories {
|
|
if inventory.Config == nil {
|
|
continue
|
|
}
|
|
if config.HasPendingRootTokensImportForConfig(inventory.Config) {
|
|
needsWritePath = true
|
|
break
|
|
}
|
|
live := findAuthoritativeInstallTokenInSlice(inventory.Config.APITokens, inventory, requestRecord)
|
|
if live == nil {
|
|
continue
|
|
}
|
|
fastFound = true
|
|
if !liveInstallTokenAuthorizedForOrgReport(live, requestRecord, orgID) {
|
|
fastWithdrawn = true
|
|
break
|
|
}
|
|
clone := live.Clone()
|
|
fastLive = &clone
|
|
_, hasIntent := agenttokens.ParseCommandPolicyIntent(live)
|
|
appliedAgent := strings.TrimSpace(live.Metadata[agenttokens.CommandPolicyAppliedAgentIDMetadataKey])
|
|
if appliedAgent == "" && hasIntent && evaluateAgentExecBinding(live, host.ID, host.Hostname).admit {
|
|
needsSupersededCheck = true
|
|
}
|
|
break
|
|
}
|
|
config.Mu.RUnlock()
|
|
// Medium #6: Never access host_metadata.json while holding global config.Mu.RLock.
|
|
if !needsWritePath && needsSupersededCheck && fastLive != nil &&
|
|
!monitor.IsInstallTokenSupersededForHost(host.ID, fastLive.ID, fastLive.Hash) {
|
|
needsWritePath = true
|
|
}
|
|
if !needsWritePath {
|
|
if !fastFound || fastWithdrawn {
|
|
return nil, true, nil
|
|
}
|
|
return fastLive, false, nil
|
|
}
|
|
}
|
|
|
|
// Medium #4 + Low #2: Serialize per (orgID, hostID) with ref-counted lock cleanup.
|
|
unlockHost := lockHostCommandPolicy(orgID, host.ID)
|
|
defer unlockHost()
|
|
|
|
if pendingRev, ok := getPendingCommandPolicyRevert(orgID, host.ID); ok {
|
|
// Medium #1: Retry revert using the INITIATING credential stored with
|
|
// the retry entry via conditional FinalizeHostCommandsEnablePendingAuth
|
|
// so an intervening operator enable is never overwritten.
|
|
if _, err := monitor.FinalizeHostCommandsEnablePendingAuth(host.ID, pendingRev.tokenID, pendingRev.tokenHash, false); err != nil {
|
|
return nil, true, fmt.Errorf("retry pending host command-policy revert: %w", err)
|
|
}
|
|
clearPendingCommandPolicyRevert(orgID, host.ID, pendingRev)
|
|
}
|
|
|
|
inventories := resolveAuthenticatingInventories(req, monitor)
|
|
|
|
// Phase 1: Inspect live token under authoritative write lock and capture
|
|
// live snapshot for response eligibility on EVERY exit.
|
|
var (
|
|
matchedInventory monitoring.APITokenInventory
|
|
liveSnapshot *config.APITokenRecord
|
|
foundLive bool
|
|
withdrawn bool
|
|
shouldApply bool
|
|
effectiveEnabled bool
|
|
finishPendingOn bool
|
|
finishPendingOff bool
|
|
)
|
|
pendingHostAuth, pendingTokID, pendingTokHash := monitor.GetHostCommandsEnablePendingAuth(host.ID)
|
|
pendingUnboundLegacy := pendingHostAuth && (strings.TrimSpace(pendingTokID) == "" || strings.TrimSpace(pendingTokHash) == "")
|
|
// Medium #2: Positive non-empty match required on BOTH ID and Hash for promotion.
|
|
pendingMatchesReq := pendingHostAuth && !pendingUnboundLegacy &&
|
|
strings.TrimSpace(pendingTokID) == strings.TrimSpace(requestRecord.ID) &&
|
|
constantTimeStringEqual(strings.TrimSpace(pendingTokHash), strings.TrimSpace(requestRecord.Hash))
|
|
|
|
evaluatePhase1Live := func(inventory monitoring.APITokenInventory, live *config.APITokenRecord) {
|
|
foundLive = true
|
|
matchedInventory = inventory
|
|
// Revalidate org membership AND ScopeAgentReport under lock.
|
|
if !liveInstallTokenAuthorizedForOrgReport(live, requestRecord, orgID) {
|
|
withdrawn = true
|
|
return
|
|
}
|
|
clone := live.Clone()
|
|
liveSnapshot = &clone
|
|
requestedEnabled, hasIntent := agenttokens.ParseCommandPolicyIntent(live)
|
|
appliedAgent := strings.TrimSpace(live.Metadata[agenttokens.CommandPolicyAppliedAgentIDMetadataKey])
|
|
if pendingUnboundLegacy {
|
|
// Legacy unbound pending record resolves fail-closed.
|
|
finishPendingOff = true
|
|
return
|
|
}
|
|
if appliedAgent != "" {
|
|
if pendingMatchesReq && appliedAgent == host.ID {
|
|
if hasIntent && requestedEnabled && live.HasScope(config.ScopeAgentExec) && evaluateAgentExecBinding(live, host.ID, host.Hostname).admit {
|
|
finishPendingOn = true
|
|
} else {
|
|
finishPendingOff = true
|
|
}
|
|
}
|
|
return
|
|
}
|
|
// If an operator explicitly superseded this token after a crash
|
|
// between Phase 2 and Phase 3, never re-apply its intent.
|
|
if monitor.IsInstallTokenSupersededForHost(host.ID, live.ID, live.Hash) {
|
|
return
|
|
}
|
|
if !hasIntent || !evaluateAgentExecBinding(live, host.ID, host.Hostname).admit {
|
|
if pendingMatchesReq {
|
|
finishPendingOff = true
|
|
}
|
|
return
|
|
}
|
|
shouldApply = true
|
|
effectiveEnabled = requestedEnabled && live.HasScope(config.ScopeAgentExec)
|
|
}
|
|
|
|
// Phase 1 (Medium #2): Read authoritative on-disk inventory under the
|
|
// per-directory token lock WITHOUT holding global config.Mu.Lock() across
|
|
// disk I/O so stalled storage on one tenant never blocks auth or topology
|
|
// reads on other tenants.
|
|
for _, inventory := range inventories {
|
|
if inventory.Config == nil {
|
|
continue
|
|
}
|
|
if inventory.Persistence != nil {
|
|
err := inventory.Persistence.WithAPITokenWriteLock(func() error {
|
|
diskTokens, loadErr := inventory.Persistence.LoadAPITokensAlreadyLocked()
|
|
if loadErr != nil {
|
|
return loadErr
|
|
}
|
|
(&config.Config{APITokens: diskTokens}).SortAPITokens()
|
|
if candidate := findAuthoritativeInstallTokenInSlice(diskTokens, inventory, requestRecord); candidate != nil {
|
|
evaluatePhase1Live(inventory, candidate)
|
|
return nil
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, true, err
|
|
}
|
|
} else {
|
|
config.Mu.RLock()
|
|
live, _, found := monitoring.FindAPITokenLocked([]monitoring.APITokenInventory{inventory}, requestRecord.ID)
|
|
if found && matchesAdmittedInstallToken(live, requestRecord) {
|
|
evaluatePhase1Live(inventory, live)
|
|
}
|
|
config.Mu.RUnlock()
|
|
}
|
|
if foundLive {
|
|
break
|
|
}
|
|
}
|
|
|
|
if !foundLive || withdrawn {
|
|
if pendingMatchesReq || pendingUnboundLegacy {
|
|
if _, err := monitor.FinalizeHostCommandsEnablePendingAuth(host.ID, pendingTokID, pendingTokHash, false); err != nil {
|
|
setPendingCommandPolicyRevert(orgID, host.ID, pendingTokID, pendingTokHash)
|
|
}
|
|
}
|
|
return nil, true, nil
|
|
}
|
|
if finishPendingOn {
|
|
// Serialize pending-enable promotion with concurrent token revocation
|
|
// under the authenticating inventory's token lock (zero config.Mu held).
|
|
finalizePending := func() (*config.APITokenRecord, bool, error) {
|
|
if matchedInventory.Persistence != nil {
|
|
var (
|
|
finalSnap *config.APITokenRecord
|
|
stillAuthorized bool
|
|
finErr error
|
|
)
|
|
_ = matchedInventory.Persistence.WithAPITokenWriteLock(func() error {
|
|
if matchedInventory.Persistence.HasPendingRootTokensImport() {
|
|
return nil
|
|
}
|
|
diskTokens, loadErr := matchedInventory.Persistence.LoadAPITokensAlreadyLocked()
|
|
if loadErr != nil {
|
|
finErr = loadErr
|
|
return nil
|
|
}
|
|
(&config.Config{APITokens: diskTokens}).SortAPITokens()
|
|
live := findAuthoritativeInstallTokenInSlice(diskTokens, matchedInventory, requestRecord)
|
|
if !isInstallTokenAuthorizedForPendingPromotion(live, requestRecord, orgID, host) {
|
|
return nil
|
|
}
|
|
stillAuthorized = true
|
|
c := live.Clone()
|
|
finalSnap = &c
|
|
if _, err := monitor.FinalizeHostCommandsEnablePendingAuth(host.ID, requestRecord.ID, requestRecord.Hash, true); err != nil {
|
|
finErr = fmt.Errorf("finalize pending host command policy enable: %w", err)
|
|
}
|
|
return nil
|
|
})
|
|
if finErr != nil {
|
|
return finalSnap, true, finErr
|
|
}
|
|
if !stillAuthorized {
|
|
if _, revErr := monitor.FinalizeHostCommandsEnablePendingAuth(host.ID, requestRecord.ID, requestRecord.Hash, false); revErr != nil {
|
|
setPendingCommandPolicyRevert(orgID, host.ID, requestRecord.ID, requestRecord.Hash)
|
|
}
|
|
return nil, true, nil
|
|
}
|
|
return finalSnap, false, nil
|
|
}
|
|
if _, err := monitor.FinalizeHostCommandsEnablePendingAuth(host.ID, requestRecord.ID, requestRecord.Hash, true); err != nil {
|
|
return liveSnapshot, true, fmt.Errorf("finalize pending host command policy enable: %w", err)
|
|
}
|
|
return liveSnapshot, false, nil
|
|
}
|
|
return finalizePending()
|
|
}
|
|
if finishPendingOff {
|
|
if _, err := monitor.FinalizeHostCommandsEnablePendingAuth(host.ID, pendingTokID, pendingTokHash, false); err != nil {
|
|
setPendingCommandPolicyRevert(orgID, host.ID, pendingTokID, pendingTokHash)
|
|
return liveSnapshot, true, fmt.Errorf("clear unconfirmed pending host command policy enable: %w", err)
|
|
}
|
|
return liveSnapshot, false, nil
|
|
}
|
|
if !shouldApply {
|
|
return liveSnapshot, false, nil
|
|
}
|
|
|
|
// Phase 2: Atomically verify this credential has NOT been superseded by an
|
|
// intervening operator disable AND persist durable credential-bound
|
|
// CommandsEnablePendingAuth=true for enables in ONE host-metadata lock (High #4).
|
|
superseded, err := monitor.BeginInstallTokenCommandsEnablePendingAuth(host.ID, effectiveEnabled, requestRecord.ID, requestRecord.Hash)
|
|
if err != nil {
|
|
return liveSnapshot, true, fmt.Errorf("persist desired command policy: %w", err)
|
|
}
|
|
if superseded {
|
|
return liveSnapshot, false, nil
|
|
}
|
|
|
|
// Phase 3 (High #2 + High #3): Acquire the shared full-inventory writer
|
|
// ordering (config.Mu.Lock -> WithAPITokenWriteLock) AND read/mutate/save
|
|
// the authoritative on-disk slice while holding BOTH locks. That prevents
|
|
// BOTH a concurrent token create/revoke from erasing the one-shot marker
|
|
// AND a retired tenant monitor from restoring revoked tenant credentials!
|
|
var (
|
|
marked bool
|
|
tokenID string
|
|
revertToDisable bool
|
|
)
|
|
if matchedInventory.Persistence != nil {
|
|
config.Mu.Lock()
|
|
err = matchedInventory.Persistence.WithAPITokenWriteLock(func() error {
|
|
if matchedInventory.Config != nil {
|
|
if syncErr := matchedInventory.Persistence.SyncPendingRootImportTokensAlreadyLocked(matchedInventory.Config); syncErr != nil {
|
|
if effectiveEnabled {
|
|
revertToDisable = true
|
|
}
|
|
return syncErr
|
|
}
|
|
}
|
|
diskTokens, loadErr := matchedInventory.Persistence.LoadAPITokensAlreadyLocked()
|
|
if loadErr != nil {
|
|
if effectiveEnabled {
|
|
revertToDisable = true
|
|
}
|
|
return loadErr
|
|
}
|
|
(&config.Config{APITokens: diskTokens}).SortAPITokens()
|
|
live := findAuthoritativeInstallTokenInSlice(diskTokens, matchedInventory, requestRecord)
|
|
if live == nil || !liveInstallTokenAuthorizedForOrgReport(live, requestRecord, orgID) {
|
|
liveSnapshot = nil
|
|
withdrawn = true
|
|
if effectiveEnabled {
|
|
revertToDisable = true
|
|
}
|
|
return nil
|
|
}
|
|
clone := live.Clone()
|
|
liveSnapshot = &clone
|
|
if !evaluateAgentExecBinding(live, host.ID, host.Hostname).admit {
|
|
if effectiveEnabled {
|
|
revertToDisable = true
|
|
}
|
|
return nil
|
|
}
|
|
curIntent, curHasIntent := agenttokens.ParseCommandPolicyIntent(live)
|
|
if !curHasIntent || (effectiveEnabled && !(curIntent && live.HasScope(config.ScopeAgentExec))) {
|
|
if effectiveEnabled {
|
|
revertToDisable = true
|
|
}
|
|
return nil
|
|
}
|
|
if strings.TrimSpace(live.Metadata[agenttokens.CommandPolicyAppliedAgentIDMetadataKey]) != "" {
|
|
return nil
|
|
}
|
|
if live.Metadata == nil {
|
|
live.Metadata = make(map[string]string)
|
|
}
|
|
live.Metadata[agenttokens.CommandPolicyAppliedAgentIDMetadataKey] = host.ID
|
|
if saveErr := matchedInventory.Persistence.SaveAPITokensAlreadyLocked(diskTokens); saveErr != nil {
|
|
if config.IsDurablePublishSyncError(saveErr) {
|
|
if matchedInventory.Config != nil {
|
|
matchedInventory.Config.APITokens = diskTokens
|
|
matchedInventory.Config.SortAPITokens()
|
|
}
|
|
} else {
|
|
delete(live.Metadata, agenttokens.CommandPolicyAppliedAgentIDMetadataKey)
|
|
}
|
|
if effectiveEnabled {
|
|
revertToDisable = true
|
|
}
|
|
return fmt.Errorf("persist install-token command-policy marker: %w", saveErr)
|
|
}
|
|
cloneAfter := live.Clone()
|
|
liveSnapshot = &cloneAfter
|
|
marked = true
|
|
tokenID = live.ID
|
|
if matchedInventory.Config != nil {
|
|
matchedInventory.Config.APITokens = diskTokens
|
|
matchedInventory.Config.SortAPITokens()
|
|
}
|
|
return nil
|
|
})
|
|
config.Mu.Unlock()
|
|
} else {
|
|
config.Mu.Lock()
|
|
live, _, found := monitoring.FindAPITokenLocked([]monitoring.APITokenInventory{matchedInventory}, requestRecord.ID)
|
|
if !found || !matchesAdmittedInstallToken(live, requestRecord) || !liveInstallTokenAuthorizedForOrgReport(live, requestRecord, orgID) {
|
|
liveSnapshot = nil
|
|
withdrawn = true
|
|
if effectiveEnabled {
|
|
revertToDisable = true
|
|
}
|
|
} else {
|
|
clone := live.Clone()
|
|
liveSnapshot = &clone
|
|
curIntent, curHasIntent := agenttokens.ParseCommandPolicyIntent(live)
|
|
if !evaluateAgentExecBinding(live, host.ID, host.Hostname).admit || !curHasIntent || (effectiveEnabled && !(curIntent && live.HasScope(config.ScopeAgentExec))) {
|
|
if effectiveEnabled {
|
|
revertToDisable = true
|
|
}
|
|
} else if strings.TrimSpace(live.Metadata[agenttokens.CommandPolicyAppliedAgentIDMetadataKey]) == "" {
|
|
if live.Metadata == nil {
|
|
live.Metadata = make(map[string]string)
|
|
}
|
|
live.Metadata[agenttokens.CommandPolicyAppliedAgentIDMetadataKey] = host.ID
|
|
cloneAfter := live.Clone()
|
|
liveSnapshot = &cloneAfter
|
|
marked = true
|
|
tokenID = live.ID
|
|
}
|
|
}
|
|
config.Mu.Unlock()
|
|
}
|
|
|
|
if revertToDisable {
|
|
if _, compErr := monitor.FinalizeHostCommandsEnablePendingAuth(host.ID, requestRecord.ID, requestRecord.Hash, false); compErr != nil {
|
|
setPendingCommandPolicyRevert(orgID, host.ID, requestRecord.ID, requestRecord.Hash)
|
|
if err != nil {
|
|
return liveSnapshot, true, fmt.Errorf("%w (also failed to revert host commands: %v)", err, compErr)
|
|
}
|
|
return liveSnapshot, true, fmt.Errorf("revert host command policy after token authority withdrawal: %w", compErr)
|
|
}
|
|
clearPendingCommandPolicyRevert(orgID, host.ID, pendingCommandPolicyRevert{tokenID: requestRecord.ID, tokenHash: requestRecord.Hash})
|
|
return liveSnapshot, true, err
|
|
}
|
|
if err != nil {
|
|
return liveSnapshot, true, err
|
|
}
|
|
if marked && effectiveEnabled {
|
|
// Phase 4: Re-verify credential authority under the token write lock and
|
|
// conditionally finalize in the same lock so revocation cannot interleave
|
|
// before pending-auth promotion.
|
|
if matchedInventory.Persistence != nil {
|
|
var (
|
|
stillAuthorized bool
|
|
finErr error
|
|
)
|
|
_ = matchedInventory.Persistence.WithAPITokenWriteLock(func() error {
|
|
if matchedInventory.Persistence.HasPendingRootTokensImport() {
|
|
return nil
|
|
}
|
|
diskTokens, loadErr := matchedInventory.Persistence.LoadAPITokensAlreadyLocked()
|
|
if loadErr != nil {
|
|
finErr = loadErr
|
|
return nil
|
|
}
|
|
(&config.Config{APITokens: diskTokens}).SortAPITokens()
|
|
live := findAuthoritativeInstallTokenInSlice(diskTokens, matchedInventory, requestRecord)
|
|
if !isInstallTokenAuthorizedForPendingPromotion(live, requestRecord, orgID, host) {
|
|
return nil
|
|
}
|
|
stillAuthorized = true
|
|
if _, err := monitor.FinalizeHostCommandsEnablePendingAuth(host.ID, requestRecord.ID, requestRecord.Hash, true); err != nil {
|
|
finErr = fmt.Errorf("clear pending-auth gate on host command policy: %w", err)
|
|
}
|
|
return nil
|
|
})
|
|
if finErr != nil {
|
|
return liveSnapshot, true, finErr
|
|
}
|
|
if !stillAuthorized {
|
|
if _, revErr := monitor.FinalizeHostCommandsEnablePendingAuth(host.ID, requestRecord.ID, requestRecord.Hash, false); revErr != nil {
|
|
setPendingCommandPolicyRevert(orgID, host.ID, requestRecord.ID, requestRecord.Hash)
|
|
}
|
|
return nil, true, nil
|
|
}
|
|
} else {
|
|
if _, err := monitor.FinalizeHostCommandsEnablePendingAuth(host.ID, requestRecord.ID, requestRecord.Hash, true); err != nil {
|
|
return liveSnapshot, true, fmt.Errorf("clear pending-auth gate on host command policy: %w", err)
|
|
}
|
|
}
|
|
}
|
|
if marked {
|
|
log.Info().
|
|
Str("agent_id", host.ID).
|
|
Str("hostname", host.Hostname).
|
|
Str("token_id", tokenID).
|
|
Bool("commands_enabled", effectiveEnabled).
|
|
Msg("Applied install-token command policy to host")
|
|
}
|
|
return liveSnapshot, withdrawn, nil
|
|
}
|
|
|
|
// HandleLookup returns agent registration details for installer validation.
|
|
func (h *UnifiedAgentHandlers) HandleLookup(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only GET is allowed", nil)
|
|
return
|
|
}
|
|
|
|
lookupID := strings.TrimSpace(r.URL.Query().Get("id"))
|
|
hostname := strings.TrimSpace(r.URL.Query().Get("hostname"))
|
|
|
|
if lookupID == "" && hostname == "" {
|
|
writeErrorResponse(w, http.StatusBadRequest, "missing_lookup_param", "Provide either id or hostname to look up an agent", nil)
|
|
return
|
|
}
|
|
|
|
// Use the live host snapshot (not the global mock snapshot) so agent
|
|
// registrations can still be validated while Pulse is in mock/demo mode.
|
|
monitor := h.requireMonitor(w, r)
|
|
if monitor == nil {
|
|
return
|
|
}
|
|
hosts := monitor.GetLiveHostsSnapshot()
|
|
|
|
var (
|
|
host models.Host
|
|
found bool
|
|
)
|
|
|
|
if lookupID != "" {
|
|
for _, candidate := range hosts {
|
|
if candidate.ID == lookupID {
|
|
host = candidate
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if !found && hostname != "" {
|
|
// First pass: exact hostname match (case-insensitive) when unique.
|
|
var exactMatch *models.Host
|
|
for i := range hosts {
|
|
candidate := &hosts[i]
|
|
if strings.EqualFold(candidate.Hostname, hostname) {
|
|
if exactMatch != nil {
|
|
exactMatch = nil
|
|
break
|
|
}
|
|
exactMatch = candidate
|
|
}
|
|
}
|
|
if exactMatch != nil {
|
|
host = *exactMatch
|
|
found = true
|
|
}
|
|
|
|
// Second pass: display-name match, but only when unambiguous.
|
|
if !found {
|
|
var displayMatch *models.Host
|
|
for i := range hosts {
|
|
candidate := &hosts[i]
|
|
if strings.EqualFold(candidate.DisplayName, hostname) {
|
|
if displayMatch != nil {
|
|
displayMatch = nil
|
|
break
|
|
}
|
|
displayMatch = candidate
|
|
}
|
|
}
|
|
if displayMatch != nil {
|
|
host = *displayMatch
|
|
found = true
|
|
}
|
|
}
|
|
|
|
// Third pass: short hostname match, but only when unique.
|
|
if !found {
|
|
// Helper to get short hostname (before first dot)
|
|
getShortName := func(h string) string {
|
|
if idx := strings.Index(h, "."); idx != -1 {
|
|
return h[:idx]
|
|
}
|
|
return h
|
|
}
|
|
|
|
shortLookup := getShortName(hostname)
|
|
var shortMatch *models.Host
|
|
for i := range hosts {
|
|
candidate := &hosts[i]
|
|
if strings.EqualFold(getShortName(candidate.Hostname), shortLookup) {
|
|
if shortMatch != nil {
|
|
shortMatch = nil
|
|
break
|
|
}
|
|
shortMatch = candidate
|
|
}
|
|
}
|
|
if shortMatch != nil {
|
|
host = *shortMatch
|
|
found = true
|
|
}
|
|
}
|
|
}
|
|
|
|
if !found {
|
|
writeErrorResponse(w, http.StatusNotFound, "agent_not_found", "Agent has not registered with Pulse yet", nil)
|
|
return
|
|
}
|
|
|
|
// Ensure the querying token matches the agent (when applicable).
|
|
if record := getAPITokenRecordFromRequest(r); record != nil && host.TokenID != "" && host.TokenID != record.ID {
|
|
writeErrorResponse(w, http.StatusForbidden, "agent_lookup_forbidden", "Agent does not belong to this API token", nil)
|
|
return
|
|
}
|
|
|
|
connected := strings.EqualFold(host.Status, "online") ||
|
|
strings.EqualFold(host.Status, "running") ||
|
|
strings.EqualFold(host.Status, "healthy")
|
|
|
|
agentInfo := map[string]any{
|
|
"id": host.ID,
|
|
"hostname": host.Hostname,
|
|
"displayName": host.DisplayName,
|
|
"status": host.Status,
|
|
"connected": connected,
|
|
"lastSeen": host.LastSeen,
|
|
"agentVersion": host.AgentVersion,
|
|
}
|
|
|
|
resp := map[string]any{
|
|
"success": true,
|
|
"agent": agentInfo,
|
|
}
|
|
|
|
if err := utils.WriteJSONResponse(w, resp); err != nil {
|
|
log.Error().Err(err).Msg("Failed to serialize agent lookup response")
|
|
}
|
|
}
|
|
|
|
// HandleDeleteHost removes an agent from the shared state.
|
|
func (h *UnifiedAgentHandlers) HandleDeleteHost(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodDelete {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only DELETE is allowed", nil)
|
|
return
|
|
}
|
|
|
|
// Extract agent ID from URL path.
|
|
// Expected format: /api/agents/agent/{agentId} or legacy /api/agents/host/{agentId}
|
|
trimmedPath := trimUnifiedAgentRoutePath(r.URL.Path)
|
|
agentID := strings.TrimSpace(trimmedPath)
|
|
if agentID == "" {
|
|
writeErrorResponse(w, http.StatusBadRequest, "missing_agent_id", "agentId is required", nil)
|
|
return
|
|
}
|
|
|
|
// Remove the agent from state.
|
|
monitor := h.requireMonitor(w, r)
|
|
if monitor == nil {
|
|
return
|
|
}
|
|
host, err := monitor.RemoveHostAgent(agentID)
|
|
if err != nil {
|
|
writeErrorResponse(w, http.StatusInternalServerError, "agent_removal_failed", err.Error(), nil)
|
|
return
|
|
}
|
|
|
|
h.broadcastState(r.Context())
|
|
|
|
if err := utils.WriteJSONResponse(w, map[string]any{
|
|
"success": true,
|
|
"agentId": host.ID,
|
|
"message": "Agent removed",
|
|
}); err != nil {
|
|
log.Error().Err(err).Msg("Failed to serialize agent removal response")
|
|
}
|
|
}
|
|
|
|
// HandleAllowReenroll clears the removal block for a host agent to permit future reports.
|
|
func (h *UnifiedAgentHandlers) HandleAllowReenroll(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only POST is allowed", nil)
|
|
return
|
|
}
|
|
|
|
trimmedPath := trimUnifiedAgentRoutePath(r.URL.Path)
|
|
trimmedPath = strings.TrimSuffix(trimmedPath, "/allow-reenroll")
|
|
agentID := strings.TrimSpace(trimmedPath)
|
|
if agentID == "" {
|
|
writeErrorResponse(w, http.StatusBadRequest, "missing_agent_id", "agentId is required", nil)
|
|
return
|
|
}
|
|
|
|
monitor := h.requireMonitor(w, r)
|
|
if monitor == nil {
|
|
return
|
|
}
|
|
if err := monitor.AllowHostAgentReenroll(agentID); err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "agent_reenroll_failed", err.Error(), nil)
|
|
return
|
|
}
|
|
|
|
h.broadcastState(r.Context())
|
|
|
|
if err := utils.WriteJSONResponse(w, map[string]any{
|
|
"success": true,
|
|
"agentId": agentID,
|
|
}); err != nil {
|
|
log.Error().Err(err).Msg("Failed to serialize host-agent allow reenroll response")
|
|
}
|
|
}
|
|
|
|
// HandleConfig handles GET (fetch config) and PATCH (update config) for agents.
|
|
// GET /api/agents/agent/{agentId}/config - Agent fetches its server-side config.
|
|
// PATCH /api/agents/agent/{agentId}/config - UI updates agent config (e.g., commandsEnabled).
|
|
// Legacy clients may also use /api/agents/host/{agentId}/config.
|
|
func (h *UnifiedAgentHandlers) HandleConfig(w http.ResponseWriter, r *http.Request) {
|
|
// Extract agent ID from URL path.
|
|
// Expected format: /api/agents/agent/{agentId}/config or legacy /api/agents/host/{agentId}/config
|
|
trimmedPath := trimUnifiedAgentRoutePath(r.URL.Path)
|
|
trimmedPath = strings.TrimSuffix(trimmedPath, "/config")
|
|
agentID := strings.TrimSpace(trimmedPath)
|
|
if agentID == "" {
|
|
writeErrorResponse(w, http.StatusBadRequest, "missing_agent_id", "agentId is required", nil)
|
|
return
|
|
}
|
|
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
h.handleGetConfig(w, r, agentID)
|
|
case http.MethodPatch:
|
|
h.handlePatchConfig(w, r, agentID)
|
|
default:
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only GET and PATCH are allowed", nil)
|
|
}
|
|
}
|
|
|
|
func (h *UnifiedAgentHandlers) canReadConfig(record *config.APITokenRecord) bool {
|
|
if record == nil {
|
|
return true
|
|
}
|
|
return record.HasScope(config.ScopeAgentConfigRead) ||
|
|
// Older host/docker-agent tokens may only carry agent:report (legacy
|
|
// host-agent:report). Allow them to keep fetching their own config via
|
|
// token binding — resolveConfigAgent below restricts a report-only token
|
|
// to the host it is bound to.
|
|
record.HasScope(config.ScopeAgentReport) ||
|
|
record.HasScope(config.ScopeAgentManage) ||
|
|
record.HasScope(config.ScopeSettingsWrite)
|
|
}
|
|
|
|
// hasUniqueLiveAuthorizedTokenForConfig requires exactly one live, non-expired,
|
|
// unshadowed credential matching the admitted record's ID and hash in its
|
|
// authenticating inventory (and no duplicate ID across the monitor's token
|
|
// inventories) before ID-only host ownership or probe secrets are released.
|
|
// resolveLiveAuthorizedConfigToken revalidates the admitted token against its
|
|
// live authenticating inventory AND the admitting organization policy (including
|
|
// owner membership for owner-acting tokens), returning a detached copy of the
|
|
// live credential and whether its ID is unique across all monitor inventories.
|
|
func (h *UnifiedAgentHandlers) resolveLiveAuthorizedConfigToken(req *http.Request, monitor *monitoring.Monitor, record *config.APITokenRecord) (live *config.APITokenRecord, uniqueID bool, ok bool) {
|
|
if h == nil || monitor == nil || record == nil || strings.TrimSpace(record.ID) == "" || strings.TrimSpace(record.Hash) == "" {
|
|
return nil, false, false
|
|
}
|
|
allInventories := monitor.APITokenInventories()
|
|
authInventories := resolveAuthenticatingInventories(req, monitor)
|
|
if len(allInventories) == 0 && h.rootConfig != nil {
|
|
fallback := []monitoring.APITokenInventory{{Config: h.rootConfig}}
|
|
allInventories = fallback
|
|
authInventories = fallback
|
|
}
|
|
if len(authInventories) == 0 {
|
|
return nil, false, false
|
|
}
|
|
orgID := "default"
|
|
if req != nil {
|
|
if v := strings.TrimSpace(GetOrgID(req.Context())); v != "" {
|
|
orgID = v
|
|
}
|
|
}
|
|
|
|
config.Mu.RLock()
|
|
seenCfgs := make(map[*config.Config]struct{}, len(allInventories))
|
|
idMatches := 0
|
|
for _, inv := range allInventories {
|
|
if inv.Config == nil {
|
|
continue
|
|
}
|
|
if _, seen := seenCfgs[inv.Config]; seen {
|
|
continue
|
|
}
|
|
seenCfgs[inv.Config] = struct{}{}
|
|
for i := range inv.Config.APITokens {
|
|
if inv.Config.APITokens[i].ID == record.ID {
|
|
idMatches++
|
|
}
|
|
}
|
|
}
|
|
var liveCopy *config.APITokenRecord
|
|
for _, inv := range authInventories {
|
|
if inv.Config == nil {
|
|
continue
|
|
}
|
|
if config.HasPendingRootTokensImportForConfig(inv.Config) {
|
|
config.Mu.RUnlock()
|
|
return nil, false, false
|
|
}
|
|
for i := range inv.Config.APITokens {
|
|
cand := &inv.Config.APITokens[i]
|
|
if constantTimeStringEqual(cand.Hash, record.Hash) {
|
|
// Authentication chooses the first matching hash; an earlier
|
|
// shadowing record withdraws authority from the admitted token.
|
|
if cand.ID != record.ID || apiTokenAuthenticatedUser(cand) != apiTokenAuthenticatedUser(record) {
|
|
config.Mu.RUnlock()
|
|
return nil, false, false
|
|
}
|
|
if !inv.Owns(cand) || cand.IsExpired() || !h.canReadConfig(cand) {
|
|
config.Mu.RUnlock()
|
|
return nil, false, false
|
|
}
|
|
c := cand.Clone()
|
|
liveCopy = &c
|
|
break
|
|
}
|
|
}
|
|
}
|
|
config.Mu.RUnlock()
|
|
|
|
if liveCopy == nil {
|
|
return nil, false, false
|
|
}
|
|
// Recheck the admitting organization policy outside config.Mu so
|
|
// owner-acting tokens lose access immediately if owner membership is revoked.
|
|
var checker AuthorizationChecker = NewAuthorizationChecker(nil)
|
|
ctx := context.Background()
|
|
if req != nil {
|
|
ctx = req.Context()
|
|
if policy, hasPolicy := ctx.Value(orgAccessCheckerContextKey{}).(AuthorizationChecker); hasPolicy && policy != nil {
|
|
checker = policy
|
|
}
|
|
}
|
|
var authRes AuthorizationResult
|
|
if ctxChecker, ok := checker.(contextAuthorizationChecker); ok {
|
|
authRes = ctxChecker.CheckAccessContext(ctx, liveCopy, "", orgID)
|
|
} else {
|
|
authRes = checker.CheckAccess(liveCopy, "", orgID)
|
|
}
|
|
if !authRes.Allowed {
|
|
return nil, false, false
|
|
}
|
|
return liveCopy, idMatches == 1, true
|
|
}
|
|
|
|
func (h *UnifiedAgentHandlers) hasUniqueLiveAuthorizedTokenForConfig(req *http.Request, monitor *monitoring.Monitor, record *config.APITokenRecord) bool {
|
|
_, uniqueID, ok := h.resolveLiveAuthorizedConfigToken(req, monitor, record)
|
|
return ok && uniqueID
|
|
}
|
|
|
|
func (h *UnifiedAgentHandlers) resolveConfigAgent(r *http.Request, agentID string, record *config.APITokenRecord) (models.Host, bool) {
|
|
// Use the live host snapshot so agents can still fetch config while
|
|
// Pulse is running in mock/demo mode.
|
|
monitor := h.getMonitor(r.Context())
|
|
if monitor == nil {
|
|
return models.Host{}, false
|
|
}
|
|
hosts := monitor.GetLiveHostsSnapshot()
|
|
|
|
if record == nil {
|
|
for _, candidate := range hosts {
|
|
if candidate.ID == agentID {
|
|
return candidate, true
|
|
}
|
|
}
|
|
return monitor.MatchHostConfigContinuity(agentID, "")
|
|
}
|
|
|
|
liveRecord, uniqueID, liveOK := h.resolveLiveAuthorizedConfigToken(r, monitor, record)
|
|
if !liveOK || liveRecord == nil {
|
|
return models.Host{}, false
|
|
}
|
|
|
|
if liveRecord.HasScope(config.ScopeSettingsWrite) || liveRecord.HasScope(config.ScopeAgentManage) {
|
|
for _, candidate := range hosts {
|
|
if candidate.ID == agentID {
|
|
return candidate, true
|
|
}
|
|
}
|
|
// Live state loses agent-reported hosts across monitor reloads and
|
|
// restarts until the next report lands; fall back to the persisted
|
|
// continuity store so config fetches in that window do not 404 (#1570).
|
|
return monitor.MatchHostConfigContinuity(agentID, "")
|
|
}
|
|
|
|
if !uniqueID {
|
|
return models.Host{}, false
|
|
}
|
|
|
|
for _, candidate := range hosts {
|
|
if hostOwnedByToken(candidate, liveRecord) {
|
|
return candidate, true
|
|
}
|
|
}
|
|
|
|
continuityHost, ok := monitor.MatchHostConfigContinuity(agentID, liveRecord.ID)
|
|
if !ok || !hostOwnedByToken(continuityHost, liveRecord) {
|
|
return models.Host{}, false
|
|
}
|
|
return continuityHost, true
|
|
}
|
|
|
|
// hostOwnedByToken verifies that host belongs to record (matching TokenID and,
|
|
// whenever recorded, TokenHash) for non-secret config resolution.
|
|
func hostOwnedByToken(host models.Host, record *config.APITokenRecord) bool {
|
|
if record == nil || strings.TrimSpace(host.TokenID) == "" || host.TokenID != record.ID {
|
|
return false
|
|
}
|
|
hostHash := strings.TrimSpace(host.TokenHash)
|
|
if hostHash != "" {
|
|
recHash := strings.TrimSpace(record.Hash)
|
|
return recHash != "" && constantTimeStringEqual(hostHash, recHash)
|
|
}
|
|
return true
|
|
}
|
|
|
|
// hostOwnedByTokenPositive requires positive cryptographic proof that host was
|
|
// established by record's exact credential hash (never trusting an empty legacy
|
|
// TokenHash) before releasing probe secrets or authorizing self-uninstall.
|
|
func hostOwnedByTokenPositive(host models.Host, record *config.APITokenRecord) bool {
|
|
if record == nil || strings.TrimSpace(host.TokenID) == "" || host.TokenID != record.ID {
|
|
return false
|
|
}
|
|
hostHash := strings.TrimSpace(host.TokenHash)
|
|
recHash := strings.TrimSpace(record.Hash)
|
|
return hostHash != "" && recHash != "" && constantTimeStringEqual(hostHash, recHash)
|
|
}
|
|
|
|
func (h *UnifiedAgentHandlers) signAgentConfig(agentID string, cfg monitoring.HostAgentConfig) (monitoring.HostAgentConfig, error) {
|
|
var err error
|
|
cfg, err = ensureDesiredAgentConfigMetadata(cfg)
|
|
if err != nil {
|
|
return cfg, err
|
|
}
|
|
|
|
signatureRequired := isConfigSignatureRequired()
|
|
key, err := getConfigSigningKey()
|
|
if err != nil {
|
|
if signatureRequired {
|
|
return cfg, fmt.Errorf("failed to load config signing key: %w", err)
|
|
}
|
|
log.Warn().Err(err).Msg("Failed to load config signing key")
|
|
return cfg, nil
|
|
}
|
|
if len(key) == 0 {
|
|
if signatureRequired {
|
|
return cfg, fmt.Errorf("config signing required but PULSE_AGENT_CONFIG_SIGNING_KEY is not set")
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
issuedAt := time.Now().UTC()
|
|
expiresAt := issuedAt.Add(configSignatureTTL)
|
|
|
|
payload := remoteconfig.SignedConfigPayload{
|
|
AgentID: agentID,
|
|
IssuedAt: issuedAt,
|
|
ExpiresAt: expiresAt,
|
|
CommandsEnabled: cfg.CommandsEnabled,
|
|
Settings: cfg.Settings,
|
|
}
|
|
|
|
signature, err := remoteconfig.SignConfigPayload(payload, key)
|
|
if err != nil {
|
|
if signatureRequired {
|
|
return cfg, fmt.Errorf("failed to sign agent config payload: %w", err)
|
|
}
|
|
log.Warn().Err(err).Msg("Failed to sign agent config payload")
|
|
return cfg, nil
|
|
}
|
|
|
|
cfg.IssuedAt = &issuedAt
|
|
cfg.ExpiresAt = &expiresAt
|
|
cfg.Signature = signature
|
|
return cfg, nil
|
|
}
|
|
|
|
func ensureDesiredAgentConfigMetadata(cfg monitoring.HostAgentConfig) (monitoring.HostAgentConfig, error) {
|
|
metadata, err := remoteconfig.BuildDesiredConfigMetadata(cfg.CommandsEnabled, cfg.Settings)
|
|
if err != nil {
|
|
return cfg, fmt.Errorf("failed to build desired config metadata: %w", err)
|
|
}
|
|
cfg.DesiredConfig = &metadata
|
|
return cfg, nil
|
|
}
|
|
|
|
func getConfigSigningKey() (ed25519.PrivateKey, error) {
|
|
configSigningState.once.Do(func() {
|
|
raw := utils.GetenvTrim("PULSE_AGENT_CONFIG_SIGNING_KEY")
|
|
if raw == "" {
|
|
return
|
|
}
|
|
key, err := remoteconfig.DecodeEd25519PrivateKey(raw)
|
|
if err != nil {
|
|
configSigningState.err = err
|
|
return
|
|
}
|
|
configSigningState.key = key
|
|
})
|
|
|
|
return configSigningState.key, configSigningState.err
|
|
}
|
|
|
|
func isConfigSignatureRequired() bool {
|
|
return utils.ParseBool(utils.GetenvTrim("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED"))
|
|
}
|
|
|
|
// handleGetConfig returns the server-side config for an agent to apply.
|
|
func (h *UnifiedAgentHandlers) handleGetConfig(w http.ResponseWriter, r *http.Request, agentID string) {
|
|
record := getAPITokenRecordFromRequest(r)
|
|
if !h.canReadConfig(record) {
|
|
respondMissingScope(w, config.ScopeAgentConfigRead)
|
|
LogAuditEventForTenant(GetOrgID(r.Context()), "agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,
|
|
fmt.Sprintf("agent_id=%s token_id=%s", agentID, tokenID(record)))
|
|
return
|
|
}
|
|
|
|
monitor := h.requireMonitor(w, r)
|
|
if monitor == nil {
|
|
return
|
|
}
|
|
|
|
host, ok := h.resolveConfigAgent(r, agentID, record)
|
|
if !ok {
|
|
writeErrorResponse(w, http.StatusNotFound, "agent_not_found", "Agent has not registered with Pulse yet", nil)
|
|
LogAuditEventForTenant(GetOrgID(r.Context()), "agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,
|
|
fmt.Sprintf("agent_id=%s token_id=%s", agentID, tokenID(record)))
|
|
return
|
|
}
|
|
|
|
agentID = host.ID
|
|
|
|
fetchOrgID := GetOrgID(r.Context())
|
|
revertStillPending := false
|
|
if _, ok := getPendingCommandPolicyRevert(fetchOrgID, agentID); ok {
|
|
unlockHost := lockHostCommandPolicy(fetchOrgID, agentID)
|
|
if pendingRev, pending := getPendingCommandPolicyRevert(fetchOrgID, agentID); pending {
|
|
if _, err := monitor.FinalizeHostCommandsEnablePendingAuth(agentID, pendingRev.tokenID, pendingRev.tokenHash, false); err != nil {
|
|
revertStillPending = true
|
|
} else {
|
|
clearPendingCommandPolicyRevert(fetchOrgID, agentID, pendingRev)
|
|
}
|
|
}
|
|
unlockHost()
|
|
}
|
|
hostCfg, currentHost, hostOwnerStable := monitor.GetHostAgentConfigWithOwner(agentID)
|
|
if !hostOwnerStable {
|
|
writeErrorResponse(w, http.StatusConflict, "host_ownership_changed", "Host ownership changed during config fetch", nil)
|
|
LogAuditEventForTenant(GetOrgID(r.Context()), "agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,
|
|
fmt.Sprintf("agent_id=%s token_id=%s", agentID, tokenID(record)))
|
|
return
|
|
}
|
|
var (
|
|
effectiveRecord = record
|
|
uniqueLiveToken = false
|
|
)
|
|
if record != nil {
|
|
liveRec, uniqueID, liveOK := h.resolveLiveAuthorizedConfigToken(r, monitor, record)
|
|
if !liveOK || liveRec == nil {
|
|
writeErrorResponse(w, http.StatusForbidden, "token_authority_changed", "API token authority is no longer valid for agent config", nil)
|
|
LogAuditEventForTenant(GetOrgID(r.Context()), "agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,
|
|
fmt.Sprintf("agent_id=%s token_id=%s", agentID, tokenID(record)))
|
|
return
|
|
}
|
|
effectiveRecord = liveRec
|
|
uniqueLiveToken = uniqueID
|
|
// Bind host entitlement AND probe-secret redaction to the exact host
|
|
// revision returned alongside hostCfg.
|
|
if !effectiveRecord.HasScope(config.ScopeSettingsWrite) && !effectiveRecord.HasScope(config.ScopeAgentManage) {
|
|
if !uniqueLiveToken || !hostOwnedByToken(currentHost, effectiveRecord) {
|
|
writeErrorResponse(w, http.StatusForbidden, "token_authority_changed", "API token authority is no longer valid for this host", nil)
|
|
LogAuditEventForTenant(GetOrgID(r.Context()), "agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,
|
|
fmt.Sprintf("agent_id=%s token_id=%s", agentID, tokenID(record)))
|
|
return
|
|
}
|
|
}
|
|
}
|
|
hostCfg = sanitizeHostAgentConfigForToken(hostCfg, effectiveRecord, currentHost)
|
|
if revertStillPending {
|
|
disabled := false
|
|
hostCfg.CommandsEnabled = &disabled
|
|
}
|
|
hostCfg = withholdProbeSecretsFromOtherTokens(hostCfg, effectiveRecord, currentHost, uniqueLiveToken)
|
|
config := hostCfg
|
|
signedConfig, err := h.signAgentConfig(agentID, config)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("Failed to sign agent config payload")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "config_signing_failed", "Failed to sign agent config", nil)
|
|
LogAuditEventForTenant(GetOrgID(r.Context()), "agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,
|
|
fmt.Sprintf("agent_id=%s token_id=%s", agentID, tokenID(record)))
|
|
return
|
|
}
|
|
|
|
resp := map[string]any{
|
|
"success": true,
|
|
"agentId": agentID,
|
|
"config": signedConfig,
|
|
}
|
|
|
|
if err := utils.WriteJSONResponse(w, resp); err != nil {
|
|
log.Error().Err(err).Msg("Failed to serialize agent config response")
|
|
LogAuditEventForTenant(GetOrgID(r.Context()), "agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, false,
|
|
fmt.Sprintf("agent_id=%s token_id=%s", agentID, tokenID(record)))
|
|
return
|
|
}
|
|
|
|
configHash := ""
|
|
if signedConfig.DesiredConfig != nil {
|
|
configHash = signedConfig.DesiredConfig.Hash
|
|
}
|
|
orgID := GetOrgID(r.Context())
|
|
if reason, audit := h.configFetchAudits.observe(orgID, agentID, tokenID(record), configHash, time.Now()); audit {
|
|
details := fmt.Sprintf("agent_id=%s token_id=%s config=%s", agentID, tokenID(record), configHash)
|
|
if reason != "" {
|
|
details += " reason=" + reason
|
|
}
|
|
LogAuditEventForTenant(orgID, "agent_config_fetch", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, true, details)
|
|
}
|
|
}
|
|
|
|
func tokenID(record *config.APITokenRecord) string {
|
|
if record == nil {
|
|
return ""
|
|
}
|
|
return record.ID
|
|
}
|
|
|
|
func sanitizeHostAgentConfigForToken(cfg monitoring.HostAgentConfig, record *config.APITokenRecord, host models.Host) monitoring.HostAgentConfig {
|
|
if cfg.CommandsEnabled == nil || !*cfg.CommandsEnabled || commandConfigAllowedForToken(record, host) {
|
|
return cfg
|
|
}
|
|
|
|
disabled := false
|
|
cfg.CommandsEnabled = &disabled
|
|
return cfg
|
|
}
|
|
|
|
// withholdProbeSecretsFromOtherTokens keeps the request body, credentials, and
|
|
// header values of assigned HTTP checks in the answer to the token the host
|
|
// itself reports under: the agent that runs them. resolveConfigAgent lets an
|
|
// agent:manage or settings:write token read any host's config by ID, so such a
|
|
// token gets another host's targets as the availability API returns them,
|
|
// where those values are write-only. Session and proxy callers carry no token;
|
|
// the route admits them only with administrative authority.
|
|
func withholdProbeSecretsFromOtherTokens(cfg monitoring.HostAgentConfig, record *config.APITokenRecord, host models.Host, uniqueTokenID bool) monitoring.HostAgentConfig {
|
|
assigned, present := cfg.Settings["availabilityTargets"]
|
|
if !present || record == nil || (uniqueTokenID && hostOwnedByTokenPositive(host, record)) {
|
|
return cfg
|
|
}
|
|
|
|
// Anything that is not the payload GetHostAgentConfig builds is dropped
|
|
// rather than passed through unredacted.
|
|
targets, _ := assigned.([]map[string]interface{})
|
|
redacted := make([]map[string]interface{}, 0, len(targets))
|
|
for _, target := range targets {
|
|
target = maps.Clone(target)
|
|
if contract, ok := target["http"].(*config.AvailabilityHTTPConfig); ok {
|
|
target["http"] = availabilityTargetWithoutHTTPSecrets(config.AvailabilityTarget{HTTP: contract}).HTTP
|
|
} else {
|
|
delete(target, "http")
|
|
}
|
|
redacted = append(redacted, target)
|
|
}
|
|
cfg.Settings = maps.Clone(cfg.Settings)
|
|
cfg.Settings["availabilityTargets"] = redacted
|
|
return cfg
|
|
}
|
|
|
|
func commandConfigAllowedForToken(record *config.APITokenRecord, host models.Host) bool {
|
|
if record == nil {
|
|
return true
|
|
}
|
|
if !record.HasScope(config.ScopeAgentExec) {
|
|
log.Warn().
|
|
Str("token_id", record.ID).
|
|
Str("agent_id", host.ID).
|
|
Str("hostname", host.Hostname).
|
|
Msg("Suppressing enabled remote commands for agent: token missing required scope agent:exec")
|
|
return false
|
|
}
|
|
|
|
// Mirror the command-channel admission decision exactly. Telling an agent
|
|
// commands are enabled when its channel registration would be rejected
|
|
// strands the host on "Remote control blocked" (the agent reports
|
|
// CommandsEnabled=true forever while no channel can be admitted).
|
|
if commandIdentityForToken(record, host) == "" {
|
|
// This gate runs before the agent ever attempts command-channel
|
|
// registration, so without a log here a refused binding leaves no
|
|
// trace anywhere: the agent never learns commands were requested and
|
|
// the channel rejection warnings never fire (#1728).
|
|
log.Warn().
|
|
Str("token_id", record.ID).
|
|
Str("agent_id", host.ID).
|
|
Str("hostname", host.Hostname).
|
|
Str("bound_agent_id", strings.TrimSpace(record.Metadata["bound_agent_id"])).
|
|
Str("bound_hostname", strings.TrimSpace(record.Metadata["bound_hostname"])).
|
|
Str("install_type", strings.TrimSpace(record.Metadata["install_type"])).
|
|
Str("issued_via", strings.TrimSpace(record.Metadata["issued_via"])).
|
|
Msg("Suppressing enabled remote commands for agent: exec binding would reject this token and agent identity")
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// commandIdentityForToken names the identity a host agent's command channel
|
|
// must register under for its token to admit it: the host ID Pulse resolved
|
|
// for the agent's report, which the ack returns as agentId and the agent
|
|
// persists and presents after a restart. A token binds the first ID its
|
|
// channel presents, so an agent that registered a configured --agent-id, or
|
|
// an ID Pulse forked or kept from an earlier enrollment, was refused on every
|
|
// restart while the config gate judged the resolved ID.
|
|
//
|
|
// The ID is named only for a credential that command admission would take on
|
|
// its legacy path (agent:exec, at most one organization, no runner,
|
|
// collector, or unsupported runtime role), and only when the shared binding
|
|
// decision admits it: the token already holds it, or a registration
|
|
// presenting it would take the first bind, backfill, legacy migration,
|
|
// hostname rebind, or one-time deploy repair it would get anyway. Naming it
|
|
// grants nothing beyond that registration. An established binding to any
|
|
// other ID is never moved by report contents, which can be steered onto
|
|
// another host's continuity record; the result is empty and the agent keeps
|
|
// registering under the ID it presents. The config gate consumes the same
|
|
// decision, so commands are never reported enabled for an identity the
|
|
// channel would refuse.
|
|
func commandIdentityForToken(record *config.APITokenRecord, host models.Host) string {
|
|
hostID := strings.TrimSpace(host.ID)
|
|
if record == nil || hostID == "" || !record.HasScope(config.ScopeAgentExec) || len(record.GetBoundOrgs()) > 1 {
|
|
return ""
|
|
}
|
|
switch strings.TrimSpace(record.Metadata[agenttokens.RuntimeRoleMetadataKey]) {
|
|
case "", agenttokens.CredentialKindLegacyFullTrust:
|
|
default:
|
|
return ""
|
|
}
|
|
if !evaluateAgentExecBinding(record, hostID, host.Hostname).admit {
|
|
return ""
|
|
}
|
|
return hostID
|
|
}
|
|
|
|
func (h *UnifiedAgentHandlers) ensureAgentTokenMatch(w http.ResponseWriter, r *http.Request, agentID string) bool {
|
|
record := getAPITokenRecordFromRequest(r)
|
|
if record == nil {
|
|
return true
|
|
}
|
|
|
|
if record.HasScope(config.ScopeSettingsWrite) || record.HasScope(config.ScopeWildcard) {
|
|
return true
|
|
}
|
|
|
|
// Use the live host snapshot so mock/demo mode doesn't block agent auth checks.
|
|
monitor := h.requireMonitor(w, r)
|
|
if monitor == nil {
|
|
return false
|
|
}
|
|
hosts := monitor.GetLiveHostsSnapshot()
|
|
for _, host := range hosts {
|
|
if host.ID != agentID {
|
|
continue
|
|
}
|
|
if host.TokenID == record.ID {
|
|
return true
|
|
}
|
|
writeErrorResponse(w, http.StatusForbidden, "agent_lookup_forbidden", "Agent does not belong to this API token", nil)
|
|
return false
|
|
}
|
|
|
|
writeErrorResponse(w, http.StatusNotFound, "agent_not_found", "Agent has not registered with Pulse yet", nil)
|
|
return false
|
|
}
|
|
|
|
// handlePatchConfig updates the server-side config for an agent.
|
|
func (h *UnifiedAgentHandlers) handlePatchConfig(w http.ResponseWriter, r *http.Request, agentID string) {
|
|
if !h.ensureAgentTokenMatch(w, r, agentID) {
|
|
return
|
|
}
|
|
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
|
|
defer r.Body.Close()
|
|
|
|
var req struct {
|
|
CommandsEnabled *bool `json:"commandsEnabled"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
monitor := h.requireMonitor(w, r)
|
|
if monitor == nil {
|
|
return
|
|
}
|
|
if err := monitor.UpdateHostAgentConfig(agentID, req.CommandsEnabled); err != nil {
|
|
writeErrorResponse(w, http.StatusInternalServerError, "update_failed", err.Error(), nil)
|
|
return
|
|
}
|
|
|
|
h.broadcastState(r.Context())
|
|
|
|
log.Info().
|
|
Str("agentId", agentID).
|
|
Interface("commandsEnabled", req.CommandsEnabled).
|
|
Msg("Agent config updated")
|
|
|
|
resp := map[string]any{
|
|
"success": true,
|
|
"agentId": agentID,
|
|
"config": map[string]any{
|
|
"commandsEnabled": req.CommandsEnabled,
|
|
},
|
|
}
|
|
|
|
if err := utils.WriteJSONResponse(w, resp); err != nil {
|
|
log.Error().Err(err).Msg("Failed to serialize agent config update response")
|
|
}
|
|
}
|
|
|
|
// HandleUninstall allows an agent to unregister itself during uninstallation.
|
|
// Requires ScopeAgentReport and a valid agentId in the request body.
|
|
func (h *UnifiedAgentHandlers) HandleUninstall(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only POST is allowed", nil)
|
|
return
|
|
}
|
|
|
|
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
|
|
defer r.Body.Close()
|
|
|
|
var req struct {
|
|
AgentID string `json:"agentId"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
agentID := strings.TrimSpace(req.AgentID)
|
|
if agentID == "" {
|
|
writeErrorResponse(w, http.StatusBadRequest, "missing_agent_id", "agentId is required", nil)
|
|
return
|
|
}
|
|
|
|
log.Info().Str("agentId", agentID).Msg("Received unregistration request from agent uninstaller")
|
|
|
|
monitor := h.requireMonitor(w, r)
|
|
if monitor == nil {
|
|
return
|
|
}
|
|
record := getAPITokenRecordFromRequest(r)
|
|
var err error
|
|
if record != nil {
|
|
orgID := strings.TrimSpace(GetOrgID(r.Context()))
|
|
if orgID == "" {
|
|
orgID = "default"
|
|
}
|
|
authInventories := resolveAuthenticatingInventories(r, monitor)
|
|
if len(authInventories) == 0 {
|
|
writeErrorResponse(w, http.StatusForbidden, "agent_lookup_forbidden", "Agent does not belong to this API token", nil)
|
|
return
|
|
}
|
|
// High #3: Revalidate the LIVE credential principal (not only the admitted
|
|
// snapshot) against the admitting organization policy and bind the result
|
|
// to the inventory generation used for revocation.
|
|
var checker AuthorizationChecker = NewAuthorizationChecker(nil)
|
|
if policy, hasPolicy := r.Context().Value(orgAccessCheckerContextKey{}).(AuthorizationChecker); hasPolicy && policy != nil {
|
|
checker = policy
|
|
}
|
|
expectedOwnerUserID := ""
|
|
if len(record.Metadata) > 0 {
|
|
expectedOwnerUserID = strings.TrimSpace(record.Metadata[agenttokens.OwnerUserIDMetadataKey])
|
|
}
|
|
_, err = monitor.UninstallHostAgentForCredential(agentID, record.ID, monitoring.UninstallCredentialCheck{
|
|
ExpectedHash: record.Hash,
|
|
ExpectedOwnerUserID: expectedOwnerUserID,
|
|
OrgID: orgID,
|
|
RequiredScope: config.ScopeAgentReport,
|
|
AuthInventories: authInventories,
|
|
RequireStrictInventories: true,
|
|
AuthorizeLiveRecord: func(live *config.APITokenRecord) bool {
|
|
if live == nil {
|
|
return false
|
|
}
|
|
if ctxChecker, ok := checker.(contextAuthorizationChecker); ok {
|
|
return ctxChecker.CheckAccessContext(r.Context(), live, "", orgID).Allowed
|
|
}
|
|
return checker.CheckAccess(live, "", orgID).Allowed
|
|
},
|
|
})
|
|
} else {
|
|
// Preserve the existing administrative/session removal surface. Collector
|
|
// self-uninstall always takes the exact-token durable path above.
|
|
_, err = monitor.RemoveHostAgent(agentID)
|
|
}
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, monitoring.ErrHostAgentTokenMismatch):
|
|
writeErrorResponse(w, http.StatusForbidden, "agent_lookup_forbidden", "Agent does not belong to this API token", nil)
|
|
case errors.Is(err, monitoring.ErrHostAgentNotFound):
|
|
writeErrorResponse(w, http.StatusNotFound, "agent_not_found", "Agent has not registered with Pulse yet", nil)
|
|
default:
|
|
log.Error().Err(err).Str("agentId", agentID).Msg("Collector uninstall transaction failed")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "agent_uninstall_failed", "Pulse could not durably remove the agent", nil)
|
|
}
|
|
return
|
|
}
|
|
|
|
h.broadcastState(r.Context())
|
|
|
|
if err := utils.WriteJSONResponse(w, map[string]any{
|
|
"success": true,
|
|
"agentId": agentID,
|
|
"message": "Agent unregistered successfully",
|
|
}); err != nil {
|
|
log.Error().Err(err).Msg("Failed to serialize agent unregistration response")
|
|
}
|
|
}
|
|
|
|
// HandleLink manually links an agent to a specific PVE node.
|
|
// This is used when auto-linking can't disambiguate (e.g., multiple nodes with hostname "pve").
|
|
func (h *UnifiedAgentHandlers) HandleLink(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only POST is allowed", nil)
|
|
return
|
|
}
|
|
|
|
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
|
|
defer r.Body.Close()
|
|
|
|
var req struct {
|
|
AgentID string `json:"agentId"`
|
|
NodeID string `json:"nodeId"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
agentID := strings.TrimSpace(req.AgentID)
|
|
if agentID == "" {
|
|
writeErrorResponse(w, http.StatusBadRequest, "missing_agent_id", "agentId is required", nil)
|
|
return
|
|
}
|
|
|
|
nodeID := strings.TrimSpace(req.NodeID)
|
|
if nodeID == "" {
|
|
writeErrorResponse(w, http.StatusBadRequest, "missing_node_id", "Node ID is required", nil)
|
|
return
|
|
}
|
|
|
|
monitor := h.requireMonitor(w, r)
|
|
if monitor == nil {
|
|
return
|
|
}
|
|
if err := monitor.LinkHostAgent(agentID, nodeID); err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "link_failed", err.Error(), nil)
|
|
return
|
|
}
|
|
|
|
h.broadcastState(r.Context())
|
|
|
|
if err := utils.WriteJSONResponse(w, map[string]any{
|
|
"success": true,
|
|
"agentId": agentID,
|
|
"nodeId": nodeID,
|
|
"message": "Agent linked to PVE node",
|
|
}); err != nil {
|
|
log.Error().Err(err).Msg("Failed to serialize agent link response")
|
|
}
|
|
}
|
|
|
|
// HandleUnlink removes the link between an agent and its PVE node.
|
|
// The agent continues to report but appears in the Managed Agents table.
|
|
func (h *UnifiedAgentHandlers) HandleUnlink(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only POST is allowed", nil)
|
|
return
|
|
}
|
|
|
|
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
|
|
defer r.Body.Close()
|
|
|
|
var req struct {
|
|
AgentID string `json:"agentId"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
agentID := strings.TrimSpace(req.AgentID)
|
|
if agentID == "" {
|
|
writeErrorResponse(w, http.StatusBadRequest, "missing_agent_id", "agentId is required", nil)
|
|
return
|
|
}
|
|
|
|
monitor := h.requireMonitor(w, r)
|
|
if monitor == nil {
|
|
return
|
|
}
|
|
if err := monitor.UnlinkHostAgent(agentID); err != nil {
|
|
writeErrorResponse(w, http.StatusNotFound, "unlink_failed", err.Error(), nil)
|
|
return
|
|
}
|
|
|
|
h.broadcastState(r.Context())
|
|
|
|
if err := utils.WriteJSONResponse(w, map[string]any{
|
|
"success": true,
|
|
"agentId": agentID,
|
|
"message": "Agent unlinked from PVE node",
|
|
}); err != nil {
|
|
log.Error().Err(err).Msg("Failed to serialize agent unlink response")
|
|
}
|
|
}
|