Files
Pulse/internal/monitoring/api_token_lifecycle.go
rcourtman c5b6d05107 feat(telemetry): add schema v26 map topology API/CLI/MCP telemetry
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.
2026-12-02 01:41:25 +00:00

589 lines
19 KiB
Go

package monitoring
import (
"crypto/subtle"
"errors"
"fmt"
"sort"
"strings"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rs/zerolog/log"
)
// APITokenInventory is one token store a monitor's agents authenticate
// with, together with the persistence that commits changes to it.
type APITokenInventory struct {
Config *config.Config
Persistence *config.ConfigPersistence
// OrgID, when set, limits the inventory to records bound only to that
// organization: the instance inventory is shared by every org.
OrgID string
}
// Owns reports whether record belongs to this inventory's monitor.
func (inv APITokenInventory) Owns(record *config.APITokenRecord) bool {
return record != nil && (inv.OrgID == "" || record.BoundOnlyToOrg(inv.OrgID))
}
func (inv APITokenInventory) findLocked(tokenID string) *config.APITokenRecord {
if inv.Config == nil {
return nil
}
for i := range inv.Config.APITokens {
if record := &inv.Config.APITokens[i]; record.ID == tokenID && inv.Owns(record) {
return record
}
}
return nil
}
// FindAPITokenLocked returns the live record for tokenID and the inventory
// holding it, so a change can be persisted where the record lives. The
// caller holds config.Mu.
func FindAPITokenLocked(inventories []APITokenInventory, tokenID string) (*config.APITokenRecord, APITokenInventory, bool) {
for _, inventory := range inventories {
if record := inventory.findLocked(tokenID); record != nil {
return record, inventory, true
}
}
return nil, APITokenInventory{}, false
}
// SetInstanceAPITokenInventory gives a tenant monitor the instance token
// inventory. Agent install tokens for a tenant org live there, bound to the
// org, because agents never name an organization and authentication finds
// header-less tokens only in the instance inventory. Call it before Start.
// findUniqueOwnedTokenIndex locates the exact token index matching tokenID
// owned by inventory, rejecting ambiguous inventories where duplicate IDs exist
// (either across organizations or within the same inventory) before mutating.
func findUniqueOwnedTokenIndex(tokens []config.APITokenRecord, inventory APITokenInventory, tokenID string) (int, error) {
ownedIdx := -1
matchCount := 0
unownedMatch := false
for i := range tokens {
if tokens[i].ID != tokenID {
continue
}
matchCount++
if inventory.Owns(&tokens[i]) {
if ownedIdx < 0 {
ownedIdx = i
}
} else {
unownedMatch = true
}
}
if ownedIdx < 0 {
return -1, nil
}
if matchCount > 1 || unownedMatch {
return -1, fmt.Errorf("ambiguous API token ID %q across inventory records", tokenID)
}
return ownedIdx, nil
}
func (m *Monitor) SetInstanceAPITokenInventory(cfg *config.Config, persistence *config.ConfigPersistence) {
if m == nil || cfg == nil || cfg == m.config {
return
}
orgID := m.GetOrgID()
if orgID == "" || orgID == "default" {
return
}
m.instanceTokens = APITokenInventory{Config: cfg, Persistence: persistence, OrgID: orgID}
}
// APITokenInventories returns the inventories holding this monitor's agent
// credentials: the org's own config, then for a tenant org the instance
// records bound to it. Read and change a credential in the inventory that
// holds it. Own config comes first so a duplicate persisted there by an
// earlier version keeps the grant state it was given, and so a revocation
// that cannot commit leaves the instance credential, which agents
// authenticate with, still live.
func (m *Monitor) APITokenInventories() []APITokenInventory {
if m == nil || m.config == nil {
return nil
}
own := APITokenInventory{Config: m.config, Persistence: m.persistence}
if m.instanceTokens.Config == nil {
return []APITokenInventory{own}
}
return []APITokenInventory{own, m.instanceTokens}
}
// APITokenSnapshot copies the records of every inventory this monitor's
// agents authenticate with, once per token ID. It takes config.Mu itself:
// callers must not hold it.
func (m *Monitor) APITokenSnapshot() []config.APITokenRecord {
config.Mu.RLock()
defer config.Mu.RUnlock()
var records []config.APITokenRecord
seen := make(map[string]struct{})
for _, inventory := range m.APITokenInventories() {
for i := range inventory.Config.APITokens {
record := &inventory.Config.APITokens[i]
if !inventory.Owns(record) {
continue
}
if id := record.ID; id != "" {
if _, duplicate := seen[id]; duplicate {
continue
}
seen[id] = struct{}{}
}
records = append(records, record.Clone())
}
}
return records
}
// revokeAPIToken removes one credential from both live and restart-time state.
// Agent removal itself remains authoritative when persistence is unavailable,
// but the credential must remain live if its reduced inventory cannot commit;
// otherwise a restart would silently reactivate a token Pulse reported revoked.
// UninstallCredentialCheck carries the admitted credential authority that must
// still be valid in the positively resolved authenticating inventory before a
// collector self-uninstall commits any durable side effect.
type UninstallCredentialCheck struct {
ExpectedHash string
ExpectedOwnerUserID string
OrgID string
RequiredScope string
AuthInventories []APITokenInventory
RequireStrictInventories bool
AuthorizeLiveRecord func(live *config.APITokenRecord) bool
}
func (m *Monitor) revokeAPIToken(tokenID string) (*config.APITokenRecord, error) {
return m.revokeAPITokenWithCheck(tokenID, UninstallCredentialCheck{})
}
func tokenOwnerUserID(record *config.APITokenRecord) string {
if record == nil || len(record.Metadata) == 0 {
return ""
}
return strings.TrimSpace(record.Metadata["owner_user_id"])
}
func uninstallTokenRecordAuthorized(cand *config.APITokenRecord, inv APITokenInventory, tokenID string, check UninstallCredentialCheck) bool {
if cand == nil || cand.ID != tokenID || !inv.Owns(cand) || cand.IsExpired() {
return false
}
if check.RequiredScope != "" && !cand.HasScope(check.RequiredScope) {
return false
}
if check.OrgID != "" && !cand.CanAccessOrg(check.OrgID) {
return false
}
if check.RequireStrictInventories && tokenOwnerUserID(cand) != strings.TrimSpace(check.ExpectedOwnerUserID) {
return false
}
return true
}
func (m *Monitor) verifyUninstallCredentialLive(tokenID string, check UninstallCredentialCheck) (*config.APITokenRecord, uint64, error) {
expectedHash := strings.TrimSpace(check.ExpectedHash)
if expectedHash == "" && !check.RequireStrictInventories {
return nil, 0, nil
}
if check.RequireStrictInventories && len(check.AuthInventories) == 0 {
return nil, 0, ErrHostAgentTokenMismatch
}
allInventories := m.APITokenInventories()
inventories := check.AuthInventories
if len(inventories) == 0 {
inventories = allInventories
}
config.Mu.RLock()
tokGen := config.APITokensGeneration()
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 == tokenID {
idMatches++
if idMatches > 1 {
config.Mu.RUnlock()
return nil, 0, ErrHostAgentTokenMismatch
}
}
}
}
if idMatches != 1 {
config.Mu.RUnlock()
return nil, 0, ErrHostAgentTokenMismatch
}
var matched *config.APITokenRecord
for _, inv := range inventories {
if inv.Config == nil {
continue
}
if config.HasPendingRootTokensImportForConfig(inv.Config) {
config.Mu.RUnlock()
return nil, 0, ErrHostAgentTokenMismatch
}
for i := range inv.Config.APITokens {
cand := &inv.Config.APITokens[i]
candHash := strings.TrimSpace(cand.Hash)
if candHash != "" && subtle.ConstantTimeCompare([]byte(candHash), []byte(expectedHash)) == 1 {
if uninstallTokenRecordAuthorized(cand, inv, tokenID, check) {
c := cand.Clone()
matched = &c
break
}
config.Mu.RUnlock()
return nil, 0, ErrHostAgentTokenMismatch
}
}
}
config.Mu.RUnlock()
if matched == nil {
return nil, 0, ErrHostAgentTokenMismatch
}
if check.AuthorizeLiveRecord != nil && !check.AuthorizeLiveRecord(matched) {
return nil, 0, ErrHostAgentTokenMismatch
}
return matched, tokGen, nil
}
func (m *Monitor) revokeAPITokenWithCheck(tokenID string, check UninstallCredentialCheck) (*config.APITokenRecord, error) {
return m.revokeAPITokenWithCheckAtGen(tokenID, check, 0, false)
}
func (m *Monitor) revokeAPITokenWithCheckAtGen(tokenID string, check UninstallCredentialCheck, expectedGen uint64, enforceGen bool) (*config.APITokenRecord, error) {
tokenID = strings.TrimSpace(tokenID)
expectedHash := strings.TrimSpace(check.ExpectedHash)
if tokenID == "" {
return nil, nil
}
if m == nil || m.config == nil {
return nil, fmt.Errorf("configuration unavailable")
}
if check.RequireStrictInventories && len(check.AuthInventories) == 0 {
return nil, ErrHostAgentTokenMismatch
}
config.Mu.Lock()
defer config.Mu.Unlock()
// A credential can sit in more than one inventory (a duplicate an earlier
// version persisted in the org's own config). Hold every affected inventory's
// persistence lock in deterministic ConfigDir order across the entire
// transaction and condition rollback on the post-save directory revision so
// no concurrent tenant or root import can interleave or have its removal
// undone by a partial-failure rollback.
inventories := m.APITokenInventories()
authConfigs := make(map[*config.Config]struct{}, len(check.AuthInventories))
for _, inv := range check.AuthInventories {
if inv.Config != nil {
authConfigs[inv.Config] = struct{}{}
}
}
if check.RequireStrictInventories && len(authConfigs) == 0 {
return nil, ErrHostAgentTokenMismatch
}
if enforceGen && config.APITokensGeneration() != expectedGen {
return nil, ErrHostAgentTokenMismatch
}
var persistences []*config.ConfigPersistence
seenPersistence := make(map[*config.ConfigPersistence]struct{}, len(inventories))
seenLockKeys := make(map[string]struct{}, len(inventories))
for _, inv := range inventories {
if inv.Config == nil || inv.Persistence == nil {
continue
}
if _, dup := seenPersistence[inv.Persistence]; dup {
continue
}
lockKey := inv.Persistence.LockKey()
if lockKey != "" {
if _, dup := seenLockKeys[lockKey]; dup {
continue
}
seenLockKeys[lockKey] = struct{}{}
}
seenPersistence[inv.Persistence] = struct{}{}
persistences = append(persistences, inv.Persistence)
}
sort.Slice(persistences, func(i, j int) bool {
return persistences[i].LockKey() < persistences[j].LockKey()
})
var withAllLocks func(idx int, fn func() error) error
withAllLocks = func(idx int, fn func() error) error {
if idx >= len(persistences) {
return fn()
}
return persistences[idx].WithAPITokenWriteLock(func() error {
return withAllLocks(idx+1, fn)
})
}
type revokedFrom struct {
inventory APITokenInventory
previousTokens []config.APITokenRecord
removedRecord config.APITokenRecord
postSaveRevision uint64
}
var (
committed []revokedFrom
removed *config.APITokenRecord
)
restoreLocked := func() {
for i := len(committed) - 1; i >= 0; i-- {
entry := committed[i]
cfg := entry.inventory.Config
if persistence := entry.inventory.Persistence; persistence != nil {
if persistence.APITokensDirRevision() != entry.postSaveRevision {
// Another handle replaced this directory's token inventory
// after our write; never restore a credential over a newer import.
continue
}
diskTokens, loadErr := persistence.LoadAPITokensAlreadyLocked()
if loadErr != nil {
log.Error().Err(loadErr).Str("tokenID", tokenID).Msg("Failed to reload API tokens while restoring partial revocation")
continue
}
exists := false
for _, rec := range diskTokens {
if rec.ID == entry.removedRecord.ID {
exists = true
break
}
}
if !exists {
diskTokens = append(diskTokens, entry.removedRecord.Clone())
if err := persistence.SaveAPITokensAlreadyLocked(diskTokens); err != nil {
log.Error().Err(err).Str("tokenID", tokenID).Msg("Failed to restore API token after a partial revocation")
if !config.IsDurablePublishSyncError(err) {
continue
}
}
}
cfg.APITokens = diskTokens
cfg.SortAPITokens()
} else {
cfg.APITokens = entry.previousTokens
cfg.SortAPITokens()
}
}
}
txErr := withAllLocks(0, func() error {
type revokePlan struct {
inventory APITokenInventory
sourceTokens []config.APITokenRecord
tenantDisk bool
idx int
}
plans := make([]revokePlan, 0, len(inventories))
selectedHash := ""
for _, inventory := range inventories {
cfg := inventory.Config
if cfg == nil {
continue
}
plan := revokePlan{inventory: inventory, idx: -1}
if inventory.Persistence != nil {
if err := inventory.Persistence.SyncPendingRootImportTokensAlreadyLocked(cfg); err != nil {
return err
}
if inventory.Persistence.IsTenantScoped() {
diskTokens, diskExists, loadErr := inventory.Persistence.LoadAPITokensWithExistsAlreadyLocked()
if loadErr != nil {
return loadErr
}
if !diskExists {
diskTokens = append([]config.APITokenRecord(nil), cfg.APITokens...)
}
plan.sourceTokens = diskTokens
plan.tenantDisk = true
} else {
plan.sourceTokens = cfg.APITokens
}
} else {
plan.sourceTokens = cfg.APITokens
}
idx, ambigErr := findUniqueOwnedTokenIndex(plan.sourceTokens, inventory, tokenID)
if ambigErr != nil {
return ambigErr
}
plan.idx = idx
if idx >= 0 {
hash := strings.TrimSpace(plan.sourceTokens[idx].Hash)
if hash != "" {
if selectedHash == "" {
selectedHash = hash
} else if subtle.ConstantTimeCompare([]byte(selectedHash), []byte(hash)) != 1 {
return fmt.Errorf("ambiguous API token hash for ID %q across inventories", tokenID)
}
}
}
plans = append(plans, plan)
}
// Verify across every locked inventory that no surviving record (with a
// different ID or unowned scope) shares the selected credential hash
// before mutating any inventory. Otherwise the bearer would keep
// authenticating after Pulse reported revocation succeeded.
if expectedHash != "" || check.RequireStrictInventories {
// Self-uninstall must match the exact admitted credential hash, scope,
// and organization in the positively resolved authenticating inventory.
matchedAuth := false
for _, plan := range plans {
if plan.idx < 0 {
continue
}
if check.RequireStrictInventories || len(authConfigs) > 0 {
if _, ok := authConfigs[plan.inventory.Config]; !ok {
continue
}
}
cand := &plan.sourceTokens[plan.idx]
candHash := strings.TrimSpace(cand.Hash)
if candHash != "" && subtle.ConstantTimeCompare([]byte(candHash), []byte(expectedHash)) == 1 &&
uninstallTokenRecordAuthorized(cand, plan.inventory, tokenID, check) {
matchedAuth = true
}
}
if !matchedAuth || selectedHash == "" || subtle.ConstantTimeCompare([]byte(selectedHash), []byte(expectedHash)) != 1 {
return ErrHostAgentTokenMismatch
}
}
if selectedHash != "" {
for _, plan := range plans {
for i := range plan.sourceTokens {
if i == plan.idx {
continue
}
otherHash := strings.TrimSpace(plan.sourceTokens[i].Hash)
if otherHash != "" && subtle.ConstantTimeCompare([]byte(otherHash), []byte(selectedHash)) == 1 {
return fmt.Errorf("ambiguous API token hash for ID %q: another record shares this credential hash", tokenID)
}
}
}
}
for _, plan := range plans {
if plan.idx < 0 {
continue
}
inventory := plan.inventory
cfg := inventory.Config
var (
previousTokens []config.APITokenRecord
record *config.APITokenRecord
)
if plan.tenantDisk {
diskTokens := plan.sourceTokens
removedCopy := diskTokens[plan.idx].Clone()
previousTokens = append([]config.APITokenRecord(nil), diskTokens...)
nextTokens := make([]config.APITokenRecord, 0, len(diskTokens)-1)
nextTokens = append(nextTokens, diskTokens[:plan.idx]...)
nextTokens = append(nextTokens, diskTokens[plan.idx+1:]...)
if err := inventory.Persistence.SaveAPITokensAlreadyLocked(nextTokens); err != nil {
var syncErr *config.DurablePublishSyncError
if errors.As(err, &syncErr) {
// Rename already published nextTokens on disk: align memory and
// include this inventory in rollback before surfacing err.
cfg.APITokens = nextTokens
cfg.SortAPITokens()
committed = append(committed, revokedFrom{
inventory: inventory,
previousTokens: previousTokens,
removedRecord: removedCopy.Clone(),
postSaveRevision: inventory.Persistence.APITokensDirRevision(),
})
}
restoreLocked()
return fmt.Errorf("persist API token revocation: %w", err)
}
cfg.APITokens = nextTokens
cfg.SortAPITokens()
record = &removedCopy
} else {
previousTokens = append([]config.APITokenRecord(nil), cfg.APITokens...)
removedCopy := cfg.APITokens[plan.idx].Clone()
cfg.APITokens = append(cfg.APITokens[:plan.idx], cfg.APITokens[plan.idx+1:]...)
cfg.SortAPITokens()
record = &removedCopy
if inventory.Persistence != nil {
if err := inventory.Persistence.SaveAPITokensAlreadyLocked(cfg.APITokens); err != nil {
var syncErr *config.DurablePublishSyncError
if errors.As(err, &syncErr) {
// Rename already published the reduced inventory on disk:
// keep cfg aligned and include this inventory in rollback.
committed = append(committed, revokedFrom{
inventory: inventory,
previousTokens: previousTokens,
removedRecord: record.Clone(),
postSaveRevision: inventory.Persistence.APITokensDirRevision(),
})
} else {
cfg.APITokens = previousTokens
cfg.SortAPITokens()
}
restoreLocked()
return fmt.Errorf("persist API token revocation: %w", err)
}
}
}
var postRev uint64
if inventory.Persistence != nil {
postRev = inventory.Persistence.APITokensDirRevision()
}
committed = append(committed, revokedFrom{
inventory: inventory,
previousTokens: previousTokens,
removedRecord: record.Clone(),
postSaveRevision: postRev,
})
if removed == nil {
removed = record
}
}
return nil
})
if txErr != nil {
return nil, txErr
}
return removed, nil
}
// agentTokenUsedByLiveResource reports whether any currently monitored agent
// module still authenticates with tokenID. Unified-agent installs legitimately
// share one credential across host, Docker, and Kubernetes reports, so removing
// one module must not revoke the credential out from under its siblings.
// Callers that are removing a resource should delete it from state first.
func (m *Monitor) agentTokenUsedByLiveResource(tokenID string) bool {
tokenID = strings.TrimSpace(tokenID)
if tokenID == "" || m == nil || m.state == nil {
return false
}
for _, host := range m.state.GetHosts() {
if strings.TrimSpace(host.TokenID) == tokenID {
return true
}
}
for _, host := range m.state.GetDockerHosts() {
if strings.TrimSpace(host.TokenID) == tokenID {
return true
}
}
for _, cluster := range m.state.GetKubernetesClusters() {
if strings.TrimSpace(cluster.TokenID) == tokenID {
return true
}
}
return false
}