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.
714 lines
26 KiB
Go
714 lines
26 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/telemetry"
|
|
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
const infrastructureMapTopologyWindowDays = 30
|
|
|
|
// AdvanceTelemetryConsentGeneration bumps the shared monotonic consent epoch
|
|
// whenever runtime or persisted telemetry consent transitions so in-flight
|
|
// topology writes spanning a consent transition are never recorded.
|
|
func AdvanceTelemetryConsentGeneration() {
|
|
config.AdvanceTelemetryConsentGeneration()
|
|
}
|
|
|
|
func currentTelemetryConsentGeneration() uint64 {
|
|
return config.TelemetryConsentGeneration()
|
|
}
|
|
|
|
type infrastructureMapActivityRequest struct {
|
|
Activity string `json:"activity"`
|
|
}
|
|
|
|
// HandleInfrastructureMapActivity accepts one closed, content-free map
|
|
// milestone: the page was opened, an image was saved, or an image was saved
|
|
// with names hidden. The browser deduplicates each value per session;
|
|
// this boundary rejects everything outside the declared set and persists only
|
|
// counts. Nothing the map draws is ever part of the request.
|
|
func (r *Router) HandleInfrastructureMapActivity(w http.ResponseWriter, req *http.Request) {
|
|
if req.Method != http.MethodPost {
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
var payload infrastructureMapActivityRequest
|
|
dec := json.NewDecoder(http.MaxBytesReader(w, req.Body, 1024))
|
|
dec.DisallowUnknownFields()
|
|
if err := dec.Decode(&payload); err != nil {
|
|
http.Error(w, "Invalid request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
var discard json.RawMessage
|
|
if err := dec.Decode(&discard); err != io.EOF {
|
|
http.Error(w, "Invalid request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
activity := strings.TrimSpace(payload.Activity)
|
|
if !config.IsInfrastructureMapActivity(activity) {
|
|
http.Error(w, "Unknown infrastructure map activity", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
consentGen, enabled, indeterminate := r.topologyConsentSnapshotDetailed()
|
|
if !enabled || indeterminate {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
persistence := r.persistenceForOrgReadOnly(req.Context())
|
|
if persistence != nil {
|
|
if _, err := persistence.RecordInfrastructureMapActivityWithRootConsent(r.persistence, activity, time.Now().UTC(), consentGen); err != nil {
|
|
log.Debug().Err(err).Str("activity", activity).Msg("Failed to record infrastructure map activity")
|
|
}
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (r *Router) topologyClockNow(completedAt time.Time) time.Time {
|
|
if r != nil && r.topologyNow != nil {
|
|
return r.topologyNow().UTC()
|
|
}
|
|
if !completedAt.IsZero() {
|
|
return completedAt.UTC()
|
|
}
|
|
return time.Now().UTC()
|
|
}
|
|
|
|
// ResolveEffectiveTelemetryEnabled reports whether outbound usage telemetry is
|
|
// currently permitted under one synchronized consent source shared across
|
|
// topology recording, runtime senders, settings/preview responses, and
|
|
// /api/runtime/display:
|
|
// 1. Environment overrides (PULSE_TELEMETRY) win immediately.
|
|
// 2. A false runtime config flag fails closed immediately without waiting on
|
|
// disk I/O so an opt-out cannot race behind a blocked settings read.
|
|
// 3. Persisted system.json is consulted when persistence is available. An
|
|
// unreadable, corrupt, or non-object file fails closed (false), an explicit
|
|
// telemetryEnabled value decides consent, and an absent file or omitted
|
|
// field uses the synchronized runtime config flag.
|
|
func ResolveEffectiveTelemetryEnabled(cfg *config.Config, persistence *config.ConfigPersistence) bool {
|
|
enabled, _ := ResolveEffectiveTelemetryEnabledWithStatus(cfg, persistence)
|
|
return enabled
|
|
}
|
|
|
|
// ResolveEffectiveTelemetryEnabledWithStatus reports effective consent and
|
|
// whether a false result was caused solely by the transient root-import fence.
|
|
func ResolveEffectiveTelemetryEnabledWithStatus(cfg *config.Config, persistence *config.ConfigPersistence) (enabled bool, transientFence bool) {
|
|
enabled = true
|
|
envOverride := false
|
|
if cfg != nil {
|
|
config.Mu.RLock()
|
|
enabled = cfg.TelemetryEnabled
|
|
envOverride = cfg.EnvOverrides["telemetryEnabled"] || cfg.EnvOverrides["PULSE_TELEMETRY"]
|
|
config.Mu.RUnlock()
|
|
if envOverride {
|
|
return enabled, false
|
|
}
|
|
if !enabled {
|
|
return false, false
|
|
}
|
|
}
|
|
if persistence != nil {
|
|
settings, err := persistence.LoadSystemSettingsForConsent()
|
|
if err != nil {
|
|
return false, true
|
|
}
|
|
if settings != nil && settings.TelemetryEnabled != nil {
|
|
return *settings.TelemetryEnabled, false
|
|
}
|
|
}
|
|
return enabled, false
|
|
}
|
|
|
|
// ResolveEffectiveTelemetryEnabledFromDir resolves effective telemetry consent
|
|
// directly from dataDir without eagerly constructing a full ConfigPersistence.
|
|
func ResolveEffectiveTelemetryEnabledFromDir(cfg *config.Config, dataDir string) bool {
|
|
enabled := true
|
|
envOverride := false
|
|
if cfg != nil {
|
|
config.Mu.RLock()
|
|
enabled = cfg.TelemetryEnabled
|
|
envOverride = cfg.EnvOverrides["telemetryEnabled"] || cfg.EnvOverrides["PULSE_TELEMETRY"]
|
|
config.Mu.RUnlock()
|
|
if envOverride {
|
|
return enabled
|
|
}
|
|
if !enabled {
|
|
return false
|
|
}
|
|
}
|
|
if strings.TrimSpace(dataDir) != "" {
|
|
settings, err := config.LoadSystemSettingsForConsentFromDir(dataDir)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if settings != nil && settings.TelemetryEnabled != nil {
|
|
return *settings.TelemetryEnabled
|
|
}
|
|
}
|
|
return enabled
|
|
}
|
|
|
|
// EffectiveTelemetryEnabled reports whether outbound usage telemetry is
|
|
// currently permitted for this router.
|
|
func (r *Router) EffectiveTelemetryEnabled() bool {
|
|
if r == nil {
|
|
return false
|
|
}
|
|
return ResolveEffectiveTelemetryEnabled(r.config, r.persistence)
|
|
}
|
|
|
|
// EffectiveTelemetryEnabledStatus reports effective consent alongside whether
|
|
// the read hit the transient root-import fence (for reload reconciliation).
|
|
func (r *Router) EffectiveTelemetryEnabledStatus() (bool, bool) {
|
|
if r == nil {
|
|
return false, false
|
|
}
|
|
return ResolveEffectiveTelemetryEnabledWithStatus(r.config, r.persistence)
|
|
}
|
|
|
|
func (r *Router) topologyConsentSnapshot() (uint64, bool) {
|
|
gen, enabled, _ := r.topologyConsentSnapshotDetailed()
|
|
return gen, enabled
|
|
}
|
|
|
|
func (r *Router) topologyConsentSnapshotDetailed() (uint64, bool, bool) {
|
|
genBefore := currentTelemetryConsentGeneration()
|
|
enabled, indeterminate := r.EffectiveTelemetryEnabledStatus()
|
|
genAfter := currentTelemetryConsentGeneration()
|
|
if genBefore != genAfter {
|
|
return genAfter, false, false
|
|
}
|
|
return genAfter, enabled, indeterminate
|
|
}
|
|
|
|
func (r *Router) isTopologyRequestFastEligible(req *http.Request) bool {
|
|
if r == nil || req == nil || isFirstPartyTopologyBrowserRequest(req) {
|
|
return false
|
|
}
|
|
return getAPITokenRecordFromRequest(req) != nil
|
|
}
|
|
|
|
// isFirstPartyTopologyBrowserRequest reports whether a GET /api/agent/topology
|
|
// request came from Pulse's own web UI. Scoped to topology telemetry so
|
|
// existing external-agent capability and history-read series keep their prior
|
|
// classification. When Sec-Fetch-Site is present, same-origin decides it. When
|
|
// Fetch Metadata is absent (plain HTTP or older browsers), explicit Origin or
|
|
// Referer headers are compared against the trusted-proxy-aware request origin
|
|
// (requestOriginBaseURL) before falling back to X-Requested-With when no
|
|
// origin metadata survived.
|
|
func isFirstPartyTopologyBrowserRequest(req *http.Request) bool {
|
|
if req == nil {
|
|
return false
|
|
}
|
|
if secFetchSite := strings.ToLower(strings.TrimSpace(req.Header.Get("Sec-Fetch-Site"))); secFetchSite != "" {
|
|
return secFetchSite == "same-origin"
|
|
}
|
|
if strings.TrimSpace(req.Header.Get("Origin")) != "" || strings.TrimSpace(req.Header.Get("Referer")) != "" {
|
|
expected := requestOriginBaseURL(req)
|
|
if expected == "" {
|
|
expected = requestOrigin(req)
|
|
}
|
|
return browserOriginMetadataMatches(req, expected, false)
|
|
}
|
|
return requestIsPulseWebClient(req)
|
|
}
|
|
|
|
// recordInfrastructureMapTopologyReadDay records one content-free UTC day
|
|
// marker on root persistence after HandleTopology's ResponseWriter accepts the
|
|
// complete live 200 OK body while the request context remains active.
|
|
// Disabled telemetry, mock-mode, transitioning, unverified-provenance, or
|
|
// unresolved-monitor snapshots, first-party browser requests, and requests
|
|
// without a valid monitoring:read API token are ignored.
|
|
func (r *Router) recordInfrastructureMapTopologyReadDay(req *http.Request, completedAt time.Time, telemetryConsentedThroughWrite bool, anonymized bool, liveEligible bool) {
|
|
if r == nil || req == nil || !liveEligible || !telemetryConsentedThroughWrite || isFirstPartyTopologyBrowserRequest(req) {
|
|
return
|
|
}
|
|
now := r.topologyClockNow(completedAt)
|
|
if !apiTokenCoversExternalAgentSurface(getAPITokenRecordFromRequest(req), now, config.ScopeMonitoringRead) {
|
|
return
|
|
}
|
|
persistence := r.persistence
|
|
if persistence == nil {
|
|
return
|
|
}
|
|
surface := strings.TrimSpace(req.Header.Get(agentcapabilities.AgentSurfaceHeader))
|
|
cli := surface == agentcapabilities.AgentSurfacePulseCLI
|
|
mcp := surface == agentcapabilities.AgentSurfacePulseMCP
|
|
if err := persistence.RecordInfrastructureMapTopologyReadDay(now, cli, mcp, anonymized); err != nil {
|
|
log.Debug().Err(err).Msg("Failed to record infrastructure map topology read day")
|
|
}
|
|
}
|
|
|
|
func (r *Router) recordInfrastructureMapTopologyReadDayWithConsentGen(completedAt time.Time, cli, mcp, anonymized bool, expectedConsentGen uint64) {
|
|
if r == nil {
|
|
return
|
|
}
|
|
persistence := r.persistence
|
|
if persistence == nil {
|
|
return
|
|
}
|
|
now := r.topologyClockNow(completedAt)
|
|
if err := persistence.RecordInfrastructureMapTopologyReadDayWithConsentGen(now, cli, mcp, anonymized, expectedConsentGen); err != nil {
|
|
log.Debug().Err(err).Msg("Failed to record infrastructure map topology read day")
|
|
}
|
|
}
|
|
|
|
func (r *Router) beginInfrastructureMapTopologyPendingWrite(completedAt time.Time) (time.Time, func()) {
|
|
if r == nil || r.persistence == nil {
|
|
return completedAt, nil
|
|
}
|
|
p := r.persistence
|
|
now := r.topologyClockNow(completedAt)
|
|
p.BeginTopologyPendingWrite(now)
|
|
return now, func() {
|
|
p.EndTopologyPendingWrite(now)
|
|
}
|
|
}
|
|
|
|
// SetTelemetryReconcileFunc wires the runtime telemetry reconcile hook for
|
|
// failed default-org config imports whose root-import fence may have delayed
|
|
// startup or opt-in admission.
|
|
func (r *Router) SetTelemetryReconcileFunc(fn func()) {
|
|
if r == nil || r.configHandlers == nil {
|
|
return
|
|
}
|
|
r.configHandlers.SetTelemetryReconcileFunc(fn)
|
|
}
|
|
|
|
func (r *Router) markInfrastructureMapTopologyDegradedInMemory(completedAt time.Time, expectedConsentGen uint64) {
|
|
if r == nil || r.persistence == nil {
|
|
return
|
|
}
|
|
// Discard request-derived loss evidence if consent was already revoked in
|
|
// memory or if the consent generation advanced since pre-write sampling.
|
|
if !r.isTopologyConsentFastPermitted() {
|
|
return
|
|
}
|
|
// Compare generation unconditionally, including initial generation 0.
|
|
if config.TelemetryConsentGeneration() != expectedConsentGen {
|
|
return
|
|
}
|
|
// Queue as a request-derived loss day requiring disk-consent confirmation
|
|
// in the background drainer before anything is persisted to disk.
|
|
r.persistence.RecordInfrastructureMapTopologyRequestLossWithConsentGen(r.topologyClockNow(completedAt), expectedConsentGen)
|
|
}
|
|
|
|
// WaitTopologyInit waits for NewRouter's background topology tally initialization.
|
|
func (r *Router) WaitTopologyInit() {
|
|
if r == nil {
|
|
return
|
|
}
|
|
r.topologyInitWG.Wait()
|
|
}
|
|
|
|
// WaitTopologyObservers waits for in-flight async topology read observers.
|
|
// isTopologyConsentFastPermitted checks only the in-memory runtime config and
|
|
// environment override (zero disk I/O) so reads after opt-out skip the bounded
|
|
// disk consent-lookup pool entirely.
|
|
func (r *Router) isTopologyConsentFastPermitted() bool {
|
|
if r == nil || r.config == nil {
|
|
return false
|
|
}
|
|
if !config.Mu.TryRLock() {
|
|
// Never stall the synchronous HTTP response path behind a blocked
|
|
// config.Mu writer. Fall through to the bounded consent sampler, which
|
|
// enforces the 250ms budget and fails closed without persisting loss.
|
|
return true
|
|
}
|
|
enabled := r.config.TelemetryEnabled
|
|
config.Mu.RUnlock()
|
|
return enabled
|
|
}
|
|
|
|
// isTopologyTokenEligibleAtCompletion performs a pure in-memory, read-only
|
|
// check (config.Mu.RLock only, zero LastUsedAt mutation, zero disk I/O) of the
|
|
// caller's live token record for revocation, scope removal, and completion-time
|
|
// expiry before post-write saturation or timeout paths can record a marker or
|
|
// loss watermark.
|
|
// topologyCompletionTokenFastCheck validates token revocation, shadowing,
|
|
// scope, org binding, and completion-time expiry purely in memory (zero disk
|
|
// I/O) and reports whether owner org-membership must also be verified off the
|
|
// HTTP response path.
|
|
type topologyCompletionTokenCheckResult struct {
|
|
eligible bool
|
|
lockContended bool
|
|
expiredAtCompletion bool
|
|
needsOrgMembershipCheck bool
|
|
cloned *config.APITokenRecord
|
|
orgID string
|
|
deferredReq *http.Request
|
|
}
|
|
|
|
func (r *Router) evaluateTopologyCompletionTokenWithCfgLocked(targetCfg *config.Config, admitted *config.APITokenRecord, tenantInventory bool, orgID string, now time.Time) (eligible bool, needsOrgMembershipCheck bool, cloned *config.APITokenRecord) {
|
|
if targetCfg == nil {
|
|
if !tenantInventory && r.config == nil {
|
|
c := admitted.Clone()
|
|
return apiTokenCoversExternalAgentSurface(&c, now, config.ScopeMonitoringRead), false, &c
|
|
}
|
|
return false, false, nil
|
|
}
|
|
if (!tenantInventory && r.persistence != nil && r.persistence.HasPendingRootTokensImport()) || config.HasPendingRootTokensImportForConfig(targetCfg) {
|
|
return false, false, nil
|
|
}
|
|
for i := range targetCfg.APITokens {
|
|
candidate := &targetCfg.APITokens[i]
|
|
if !constantTimeStringEqual(candidate.Hash, admitted.Hash) {
|
|
continue
|
|
}
|
|
// Authentication chooses the first matching credential hash. A shadowing
|
|
// record with the same hash withdraws authority from any later record.
|
|
if candidate.ID != admitted.ID || apiTokenAuthenticatedUser(candidate) != apiTokenAuthenticatedUser(admitted) {
|
|
break
|
|
}
|
|
copyRec := candidate.Clone()
|
|
scopes := copyRec.Scopes
|
|
if len(scopes) == 0 {
|
|
scopes = []string{config.ScopeWildcard}
|
|
}
|
|
role := strings.TrimSpace(copyRec.Metadata[internalauth.RuntimeRoleMetadataKey])
|
|
if internalauth.ValidateRoleScopes(role, scopes) != nil {
|
|
break
|
|
}
|
|
cloned = ©Rec
|
|
break
|
|
}
|
|
if cloned == nil {
|
|
return false, false, nil
|
|
}
|
|
if !cloned.CanAccessOrg(orgID) || !apiTokenCoversExternalAgentSurface(cloned, now, config.ScopeMonitoringRead) {
|
|
return false, false, nil
|
|
}
|
|
needsOrgMembershipCheck = orgID != "default" && apiTokenActsForOwner(cloned) && r.orgAccess != nil && r.orgAccess.orgLoader != nil
|
|
return true, needsOrgMembershipCheck, cloned
|
|
}
|
|
|
|
func (r *Router) topologyCompletionTokenFastCheck(req *http.Request, completedAt time.Time) topologyCompletionTokenCheckResult {
|
|
if r == nil || req == nil || isFirstPartyTopologyBrowserRequest(req) {
|
|
return topologyCompletionTokenCheckResult{}
|
|
}
|
|
admitted := getAPITokenRecordFromRequest(req)
|
|
if admitted == nil {
|
|
return topologyCompletionTokenCheckResult{}
|
|
}
|
|
orgID := strings.TrimSpace(GetOrgID(req.Context()))
|
|
if orgID == "" {
|
|
orgID = "default"
|
|
}
|
|
now := r.topologyClockNow(completedAt)
|
|
if admitted.ExpiresAt != nil && !now.Before(*admitted.ExpiresAt) {
|
|
return topologyCompletionTokenCheckResult{expiredAtCompletion: true, orgID: orgID}
|
|
}
|
|
source, tenantInventory := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)
|
|
tenantInventory = tenantInventory && source.orgID != "" && source.orgID != "default"
|
|
|
|
if !config.Mu.TryRLock() {
|
|
// Never stall a completed HTTP topology response waiting on a write-locked
|
|
// config.Mu. Clone the request metadata and defer bounded completion-time
|
|
// revalidation to the async post-write worker with explicit loss accounting.
|
|
return topologyCompletionTokenCheckResult{
|
|
lockContended: true,
|
|
orgID: orgID,
|
|
deferredReq: req.Clone(context.WithoutCancel(req.Context())),
|
|
}
|
|
}
|
|
targetCfg := r.config
|
|
if tenantInventory {
|
|
var mtmContended bool
|
|
targetCfg, mtmContended = tryTenantTokenConfigForRequest(req)
|
|
if mtmContended {
|
|
config.Mu.RUnlock()
|
|
return topologyCompletionTokenCheckResult{
|
|
lockContended: true,
|
|
orgID: orgID,
|
|
deferredReq: req.Clone(context.WithoutCancel(req.Context())),
|
|
}
|
|
}
|
|
}
|
|
eligible, needsMembership, cloned := r.evaluateTopologyCompletionTokenWithCfgLocked(targetCfg, admitted, tenantInventory, orgID, now)
|
|
config.Mu.RUnlock()
|
|
return topologyCompletionTokenCheckResult{
|
|
eligible: eligible,
|
|
needsOrgMembershipCheck: needsMembership,
|
|
cloned: cloned,
|
|
orgID: orgID,
|
|
}
|
|
}
|
|
|
|
func (r *Router) checkTopologyCompletionTokenBounded(ctx context.Context, req *http.Request, completedAt time.Time) (res topologyCompletionTokenCheckResult, timedOut bool) {
|
|
if r == nil || req == nil {
|
|
return topologyCompletionTokenCheckResult{}, false
|
|
}
|
|
admitted := getAPITokenRecordFromRequest(req)
|
|
if admitted == nil {
|
|
return topologyCompletionTokenCheckResult{}, false
|
|
}
|
|
orgID := strings.TrimSpace(GetOrgID(req.Context()))
|
|
if orgID == "" {
|
|
orgID = "default"
|
|
}
|
|
now := r.topologyClockNow(completedAt)
|
|
if admitted.ExpiresAt != nil && !now.Before(*admitted.ExpiresAt) {
|
|
return topologyCompletionTokenCheckResult{expiredAtCompletion: true, orgID: orgID}, false
|
|
}
|
|
source, tenantInventory := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)
|
|
tenantInventory = tenantInventory && source.orgID != "" && source.orgID != "default"
|
|
|
|
slots := r.getTopologyOrgMembershipSlots()
|
|
select {
|
|
case slots <- struct{}{}:
|
|
default:
|
|
return topologyCompletionTokenCheckResult{lockContended: true, orgID: orgID}, true
|
|
}
|
|
ch := make(chan topologyCompletionTokenCheckResult, 1)
|
|
r.topologyOrgMembershipWG.Add(1)
|
|
go func() {
|
|
defer func() {
|
|
<-slots
|
|
r.topologyOrgMembershipWG.Done()
|
|
}()
|
|
config.Mu.RLock()
|
|
targetCfg := r.config
|
|
if tenantInventory {
|
|
targetCfg = tenantTokenConfigForRequest(req)
|
|
}
|
|
eligible, needsMembership, cloned := r.evaluateTopologyCompletionTokenWithCfgLocked(targetCfg, admitted, tenantInventory, orgID, now)
|
|
config.Mu.RUnlock()
|
|
ch <- topologyCompletionTokenCheckResult{
|
|
eligible: eligible,
|
|
needsOrgMembershipCheck: needsMembership,
|
|
cloned: cloned,
|
|
orgID: orgID,
|
|
}
|
|
}()
|
|
timer := time.NewTimer(defaultTopologyConsentLookupTimeout)
|
|
defer timer.Stop()
|
|
select {
|
|
case out := <-ch:
|
|
return out, false
|
|
case <-ctx.Done():
|
|
return topologyCompletionTokenCheckResult{lockContended: true, orgID: orgID}, true
|
|
case <-timer.C:
|
|
return topologyCompletionTokenCheckResult{lockContended: true, orgID: orgID}, true
|
|
}
|
|
}
|
|
|
|
func (r *Router) isTopologyTokenEligibleAtCompletion(req *http.Request, completedAt time.Time) bool {
|
|
res := r.topologyCompletionTokenFastCheck(req, completedAt)
|
|
if res.lockContended {
|
|
var timedOut bool
|
|
res, timedOut = r.checkTopologyCompletionTokenBounded(req.Context(), req, completedAt)
|
|
if timedOut {
|
|
return false
|
|
}
|
|
}
|
|
if !res.eligible {
|
|
return false
|
|
}
|
|
if res.needsOrgMembershipCheck && !r.checkTokenOrgAccessLocked(req.Context(), res.cloned, res.orgID).Allowed {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (r *Router) getTopologyOrgMembershipSlots() chan struct{} {
|
|
r.topologyOrgMembershipSlotsOnce.Do(func() {
|
|
r.topologyOrgMembershipSlots = make(chan struct{}, cap(topologyPostWriteSlots))
|
|
})
|
|
return r.topologyOrgMembershipSlots
|
|
}
|
|
|
|
func (r *Router) checkTopologyTokenOrgMembershipBounded(ctx context.Context, token *config.APITokenRecord, orgID string) (allowed bool, indeterminate bool, timedOut bool) {
|
|
if token == nil || orgID == "" || orgID == "default" || r == nil || r.orgAccess == nil || r.orgAccess.orgLoader == nil {
|
|
return true, false, false
|
|
}
|
|
slots := r.getTopologyOrgMembershipSlots()
|
|
timer := time.NewTimer(defaultTopologyConsentLookupTimeout)
|
|
defer timer.Stop()
|
|
select {
|
|
case slots <- struct{}{}:
|
|
case <-timer.C:
|
|
return false, false, true
|
|
}
|
|
resCh := make(chan AuthorizationResult, 1)
|
|
r.topologyOrgMembershipWG.Add(1)
|
|
go func() {
|
|
defer func() {
|
|
<-slots
|
|
r.topologyOrgMembershipWG.Done()
|
|
}()
|
|
resCh <- r.checkTokenOrgAccessLocked(ctx, token, orgID)
|
|
}()
|
|
select {
|
|
case res := <-resCh:
|
|
return res.Allowed, res.Indeterminate, false
|
|
case <-timer.C:
|
|
return false, false, true
|
|
}
|
|
}
|
|
|
|
func (r *Router) WaitTopologyObservers() {
|
|
if r == nil {
|
|
return
|
|
}
|
|
if r.agentContextHandler != nil {
|
|
r.agentContextHandler.WaitTopologyObservers()
|
|
}
|
|
r.topologyOrgMembershipWG.Wait()
|
|
if r.persistence != nil {
|
|
r.persistence.WaitTopologyUncertaintyWrites()
|
|
}
|
|
}
|
|
|
|
// WaitTopologyDrain drains startup tally initialization, in-flight async
|
|
// topology observers, and persisted uncertainty watermarks during graceful
|
|
// shutdown, bounded by ctx.
|
|
func (r *Router) WaitTopologyDrain(ctx context.Context) {
|
|
if r == nil {
|
|
return
|
|
}
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
// 1. Drain startup init and already-admitted post-write observers while
|
|
// sidecar loss admission is STILL open so an observer that times out
|
|
// can still enqueue and persist its loss watermark.
|
|
r.WaitTopologyInit()
|
|
if r.agentContextHandler != nil {
|
|
r.agentContextHandler.WaitTopologyObservers()
|
|
}
|
|
r.topologyOrgMembershipWG.Wait()
|
|
// 2. Wait for any currently active drainer to finish so failures it
|
|
// reports are captured in the retry queue, then close admission and
|
|
// promote any retained retry work into one final bounded flush.
|
|
if r.persistence != nil {
|
|
r.persistence.WaitTopologyUncertaintyWrites()
|
|
r.persistence.CloseTopologyBackgroundAdmission()
|
|
r.persistence.WaitTopologyUncertaintyWrites()
|
|
}
|
|
}()
|
|
if ctx == nil {
|
|
<-done
|
|
return
|
|
}
|
|
select {
|
|
case <-done:
|
|
case <-ctx.Done():
|
|
}
|
|
}
|
|
|
|
func countDayIntersection(subset, base map[string]struct{}) int {
|
|
total := 0
|
|
for day := range subset {
|
|
if _, ok := base[day]; ok {
|
|
total++
|
|
}
|
|
}
|
|
return total
|
|
}
|
|
|
|
// ApplyInfrastructureMapTelemetrySnapshot aggregates the bounded, content-free
|
|
// map counters for the existing daily telemetry ping. Browser milestones are
|
|
// summed across local organizations, while install-level topology read-day
|
|
// markers and degradation state are read together under a single root
|
|
// persistence lock with subset days intersected against root read days.
|
|
func (r *Router) ApplyInfrastructureMapTelemetrySnapshot(s *telemetry.Snapshot, now time.Time) {
|
|
r.applyInfrastructureMapTelemetrySnapshot(s, now, false)
|
|
}
|
|
|
|
// ApplyInfrastructureMapTelemetrySnapshotReadOnly populates topology telemetry
|
|
// counts strictly without any disk side effects (never writing a degraded
|
|
// sidecar or queuing background maintenance), even when telemetry is enabled.
|
|
func (r *Router) ApplyInfrastructureMapTelemetrySnapshotReadOnly(s *telemetry.Snapshot, now time.Time) {
|
|
r.applyInfrastructureMapTelemetrySnapshot(s, now, true)
|
|
}
|
|
|
|
func (r *Router) applyInfrastructureMapTelemetrySnapshot(s *telemetry.Snapshot, now time.Time, readOnly bool) {
|
|
if r == nil || s == nil {
|
|
return
|
|
}
|
|
if now.IsZero() {
|
|
now = time.Now()
|
|
}
|
|
nowUTC := now.UTC()
|
|
since := nowUTC.Add(-telemetry.PulseIntelligenceTelemetryWindow)
|
|
|
|
if orgIDs, orgErr := r.pulseIntelligenceTelemetryOrgIDs(); orgErr == nil {
|
|
for _, orgID := range orgIDs {
|
|
persistence := r.persistence
|
|
if orgID != "default" && r.multiTenant != nil {
|
|
var err error
|
|
persistence, err = r.multiTenant.GetPersistenceReadOnly(orgID)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
}
|
|
if persistence == nil {
|
|
continue
|
|
}
|
|
tally, err := persistence.LoadInfrastructureMapActivityTally()
|
|
if err != nil || tally == nil {
|
|
continue
|
|
}
|
|
s.InfrastructureMapOpenSessions30d += tally.CountSince(config.InfrastructureMapActivityOpen, since)
|
|
s.InfrastructureMapExportSessions30d += tally.CountSince(config.InfrastructureMapActivityExport, since)
|
|
s.InfrastructureMapExportNamesHiddenSessions30d += tally.CountSince(config.InfrastructureMapActivityExportNamesHidden, since)
|
|
}
|
|
}
|
|
|
|
s.InfrastructureMapTopologyTelemetryAvailable = false
|
|
s.InfrastructureMapTopologyReadDays30d = 0
|
|
s.InfrastructureMapTopologyCLIDays30d = 0
|
|
s.InfrastructureMapTopologyMCPDays30d = 0
|
|
s.InfrastructureMapTopologyAnonymizedDays30d = 0
|
|
|
|
if r.persistence == nil {
|
|
return
|
|
}
|
|
var (
|
|
rootTally *config.InfrastructureMapTopologyTallyData
|
|
available bool
|
|
err error
|
|
)
|
|
if readOnly {
|
|
rootTally, available, err = r.persistence.LoadInfrastructureMapTopologyTallySnapshotReadOnly(nowUTC, infrastructureMapTopologyWindowDays)
|
|
} else if r.config != nil {
|
|
consentGen, enabled, indet := r.topologyConsentSnapshotDetailed()
|
|
if !enabled || indet {
|
|
rootTally, available, err = r.persistence.LoadInfrastructureMapTopologyTallySnapshotReadOnly(nowUTC, infrastructureMapTopologyWindowDays)
|
|
} else {
|
|
rootTally, available, err = r.persistence.LoadInfrastructureMapTopologyTallySnapshotWithConsentGen(nowUTC, infrastructureMapTopologyWindowDays, consentGen)
|
|
}
|
|
} else {
|
|
rootTally, available, err = r.persistence.LoadInfrastructureMapTopologyTallySnapshot(nowUTC, infrastructureMapTopologyWindowDays)
|
|
}
|
|
if err != nil || !available || rootTally == nil {
|
|
if err != nil {
|
|
log.Warn().Err(err).Msg("Infrastructure map topology telemetry unavailable, skipping root tally counts")
|
|
}
|
|
return
|
|
}
|
|
rootReadDays := rootTally.ActiveDaySetInWindow(config.InfrastructureMapActivityTopologyRead, nowUTC, infrastructureMapTopologyWindowDays)
|
|
rootCLIDays := rootTally.ActiveDaySetInWindow(config.InfrastructureMapActivityTopologyCLI, nowUTC, infrastructureMapTopologyWindowDays)
|
|
rootMCPDays := rootTally.ActiveDaySetInWindow(config.InfrastructureMapActivityTopologyMCP, nowUTC, infrastructureMapTopologyWindowDays)
|
|
rootAnonDays := rootTally.ActiveDaySetInWindow(config.InfrastructureMapActivityTopologyAnonymized, nowUTC, infrastructureMapTopologyWindowDays)
|
|
|
|
readDays := min(len(rootReadDays), infrastructureMapTopologyWindowDays)
|
|
s.InfrastructureMapTopologyTelemetryAvailable = true
|
|
s.InfrastructureMapTopologyReadDays30d = readDays
|
|
s.InfrastructureMapTopologyCLIDays30d = min(countDayIntersection(rootCLIDays, rootReadDays), readDays)
|
|
s.InfrastructureMapTopologyMCPDays30d = min(countDayIntersection(rootMCPDays, rootReadDays), readDays)
|
|
s.InfrastructureMapTopologyAnonymizedDays30d = min(countDayIntersection(rootAnonDays, rootReadDays), readDays)
|
|
}
|