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.
283 lines
10 KiB
Go
283 lines
10 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/models"
|
|
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
|
|
)
|
|
|
|
// tokenMutationFailure is returned while config.Mu is held, but is written
|
|
// only after releasing it. Refusing a still-valid credential's lost privilege
|
|
// must not tell clients that the credential itself has become invalid.
|
|
type tokenMutationFailure struct {
|
|
status int
|
|
message string
|
|
missingScope bool
|
|
requiredScope string
|
|
}
|
|
|
|
func (f *tokenMutationFailure) Error() string { return f.message }
|
|
|
|
func (f *tokenMutationFailure) write(w http.ResponseWriter) {
|
|
if f.missingScope {
|
|
scope := f.requiredScope
|
|
if scope == "" {
|
|
scope = config.ScopeSettingsWrite
|
|
}
|
|
respondMissingScope(w, scope)
|
|
return
|
|
}
|
|
http.Error(w, f.message, f.status)
|
|
}
|
|
|
|
// currentTokenMutationCallerLocked rechecks the route's admitted token under
|
|
// the same config writer lock as the inventory transaction. Body reads and
|
|
// waiting for this lock can outlive revocation, rotation or a scope edit.
|
|
// The detached request record identifies the credential, not a lasting grant.
|
|
// Non-token authentication remains the route's responsibility.
|
|
// syncImportedAPITokensAlreadyLocked refreshes r.config.APITokens from disk if
|
|
// a root backup import committed a newer token inventory before publishing to
|
|
// memory. Caller must hold both config.Mu.Lock() and r.persistence's c.mu.Lock()
|
|
// (via WithAPITokenWriteLock). Returns an error so callers fail closed if the
|
|
// authoritative disk snapshot cannot be read.
|
|
func (r *Router) syncImportedAPITokensAlreadyLocked() error {
|
|
if r == nil || r.config == nil || r.persistence == nil {
|
|
return nil
|
|
}
|
|
return r.persistence.SyncPendingRootImportTokensAlreadyLocked(r.config)
|
|
}
|
|
|
|
type readOnlyNoLockOrgLoader struct {
|
|
mtp *config.MultiTenantPersistence
|
|
}
|
|
|
|
func (l readOnlyNoLockOrgLoader) GetOrganization(orgID string) (*models.Organization, error) {
|
|
org, err := l.mtp.LoadOrganizationReadOnlyNoLock(orgID)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return &models.Organization{ID: orgID, DisplayName: orgID}, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return org, nil
|
|
}
|
|
|
|
func (l readOnlyNoLockOrgLoader) GetOrganizationStrict(orgID string) (*models.Organization, error) {
|
|
return l.mtp.LoadOrganizationReadOnlyNoLock(orgID)
|
|
}
|
|
|
|
func (l readOnlyNoLockOrgLoader) ListOrganizationIDs() ([]string, error) {
|
|
return l.mtp.ListOrganizationIDs()
|
|
}
|
|
|
|
// checkTokenOrgAccessLocked evaluates token organization access (including
|
|
// owner organization membership for person-owned tokens) without acquiring
|
|
// organization-file or persistence directory locks and without creating tenant
|
|
// keys on disk.
|
|
func (r *Router) checkTokenOrgAccessLocked(ctx context.Context, token *config.APITokenRecord, orgID string) AuthorizationResult {
|
|
if r == nil || r.orgAccess == nil {
|
|
return NewAuthorizationChecker(nil).CheckAccessContext(ctx, token, "", orgID)
|
|
}
|
|
if mtLoader, ok := r.orgAccess.orgLoader.(*MultiTenantOrganizationLoader); ok && mtLoader != nil && mtLoader.persistence != nil {
|
|
checker := *r.orgAccess
|
|
checker.orgLoader = readOnlyNoLockOrgLoader{mtp: mtLoader.persistence}
|
|
return checker.CheckAccessContext(ctx, token, "", orgID)
|
|
}
|
|
return r.orgAccess.CheckAccessContext(ctx, token, "", orgID)
|
|
}
|
|
|
|
type tokenMutationLocksState struct {
|
|
tenantP *config.ConfigPersistence
|
|
preResolvedLive *config.Config
|
|
tenantResolved bool
|
|
}
|
|
|
|
func (r *Router) currentTokenMutationCallerLocked(req *http.Request) (*config.APITokenRecord, *tokenMutationFailure) {
|
|
return r.currentTokenMutationCallerWithTenantLocked(req, tokenMutationLocksState{})
|
|
}
|
|
|
|
func (r *Router) currentTokenMutationCallerWithPreResolvedTenantLocked(req *http.Request, preResolvedLive *config.Config) (*config.APITokenRecord, *tokenMutationFailure) {
|
|
return r.currentTokenMutationCallerWithTenantLocked(req, tokenMutationLocksState{
|
|
preResolvedLive: preResolvedLive,
|
|
tenantResolved: true,
|
|
})
|
|
}
|
|
|
|
// withTokenMutationWriteLocks resolves the tenant monitor config BEFORE
|
|
// acquiring any persistence directory lock (enforcing the strict acyclic lock
|
|
// order config.Mu -> mtm.mu -> c.mu sorted by ConfigDir) so publication under
|
|
// mtm.mu -> c.mu can never deadlock with token mutation handlers.
|
|
func (r *Router) withTokenMutationWriteLocks(req *http.Request, fn func(state tokenMutationLocksState) error) error {
|
|
var (
|
|
tenantP *config.ConfigPersistence
|
|
preResolvedLive *config.Config
|
|
tenantResolved bool
|
|
)
|
|
if req != nil && r != nil {
|
|
if source, ok := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource); ok && source.orgID != "" && source.orgID != "default" {
|
|
preResolvedLive = tenantTokenConfigForRequest(req)
|
|
tenantResolved = true
|
|
if r.multiTenant != nil {
|
|
if tp, err := r.multiTenant.GetPersistenceReadOnly(source.orgID); err == nil {
|
|
tenantP = tp
|
|
}
|
|
}
|
|
}
|
|
}
|
|
var persistences []*config.ConfigPersistence
|
|
if r != nil && r.persistence != nil {
|
|
persistences = append(persistences, r.persistence)
|
|
}
|
|
if tenantP != nil && (len(persistences) == 0 || (tenantP != persistences[0] && (tenantP.LockKey() == "" || tenantP.LockKey() != persistences[0].LockKey()))) {
|
|
persistences = append(persistences, tenantP)
|
|
}
|
|
if len(persistences) == 2 && persistences[1].LockKey() < persistences[0].LockKey() {
|
|
persistences[0], persistences[1] = persistences[1], persistences[0]
|
|
}
|
|
state := tokenMutationLocksState{
|
|
tenantP: tenantP,
|
|
preResolvedLive: preResolvedLive,
|
|
tenantResolved: tenantResolved,
|
|
}
|
|
var run func(idx int) error
|
|
run = func(idx int) error {
|
|
if idx >= len(persistences) {
|
|
return fn(state)
|
|
}
|
|
return persistences[idx].WithAPITokenWriteLock(func() error {
|
|
return run(idx + 1)
|
|
})
|
|
}
|
|
return run(0)
|
|
}
|
|
|
|
func (r *Router) currentTokenMutationCallerWithTenantLocked(req *http.Request, state tokenMutationLocksState) (*config.APITokenRecord, *tokenMutationFailure) {
|
|
if err := r.syncImportedAPITokensAlreadyLocked(); err != nil {
|
|
return nil, &tokenMutationFailure{status: http.StatusInternalServerError, message: "Failed to verify API token inventory"}
|
|
}
|
|
admitted := getAPITokenRecordFromRequest(req)
|
|
if admitted == nil {
|
|
return nil, nil
|
|
}
|
|
invalid := &tokenMutationFailure{status: http.StatusUnauthorized, message: "Invalid API token"}
|
|
live := r.config
|
|
var tenantOrgID string
|
|
if source, ok := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource); ok && source.orgID != "" && source.orgID != "default" {
|
|
// The shared issuer also serves organization-scoped relay credentials.
|
|
// Never fall back to another inventory when that owner is withdrawn.
|
|
tenantOrgID = source.orgID
|
|
if state.tenantResolved {
|
|
live = state.preResolvedLive
|
|
} else {
|
|
// Callers holding c.mu must pre-resolve tenant config before acquiring c.mu.
|
|
// Fail closed instead of calling PeekMonitor (mtm.mu) under c.mu.
|
|
return nil, invalid
|
|
}
|
|
}
|
|
if live == nil || config.HasPendingRootTokensImportForConfig(live) {
|
|
return nil, invalid
|
|
}
|
|
var current *config.APITokenRecord
|
|
if tenantOrgID != "" && r.multiTenant != nil {
|
|
tenantP := state.tenantP
|
|
alreadyLocked := tenantP != nil
|
|
if tenantP == nil {
|
|
var err error
|
|
tenantP, err = r.multiTenant.GetPersistenceReadOnly(tenantOrgID)
|
|
if err != nil {
|
|
return nil, invalid
|
|
}
|
|
}
|
|
if tenantP != nil {
|
|
var (
|
|
diskTokens []config.APITokenRecord
|
|
diskExists bool
|
|
diskErr error
|
|
pending bool
|
|
)
|
|
inspectDisk := func() error {
|
|
if config.HasPendingRootTokensImportForConfig(live) {
|
|
pending = true
|
|
return nil
|
|
}
|
|
diskTokens, diskExists, diskErr = tenantP.LoadAPITokensWithExistsAlreadyLocked()
|
|
return nil
|
|
}
|
|
if alreadyLocked {
|
|
_ = inspectDisk()
|
|
} else if r.persistence == nil || tenantP.ConfigDir() > r.persistence.ConfigDir() {
|
|
_ = tenantP.WithAPITokenWriteLock(inspectDisk)
|
|
} else {
|
|
// Cannot acquire tenant lock out of ConfigDir order; fail closed.
|
|
return nil, invalid
|
|
}
|
|
if diskErr != nil {
|
|
return nil, &tokenMutationFailure{status: http.StatusInternalServerError, message: "Failed to verify API token inventory"}
|
|
}
|
|
if pending {
|
|
return nil, invalid
|
|
}
|
|
if diskExists {
|
|
diskCfg := &config.Config{APITokens: diskTokens}
|
|
diskCfg.SortAPITokens()
|
|
current = admittedTokenLocked(diskCfg, admitted)
|
|
} else {
|
|
current = admittedTokenLocked(live, admitted)
|
|
}
|
|
} else {
|
|
current = admittedTokenLocked(live, admitted)
|
|
}
|
|
} else {
|
|
current = admittedTokenLocked(live, admitted)
|
|
}
|
|
if current == nil {
|
|
return nil, invalid
|
|
}
|
|
if !current.HasScope(config.ScopeSettingsWrite) {
|
|
return nil, &tokenMutationFailure{status: http.StatusForbidden, message: "Missing settings:write scope", missingScope: true}
|
|
}
|
|
// Keep the route's original instance boundary, without imposing one on
|
|
// the existing org-scoped issuer. A binding edit cannot turn an admitted
|
|
// instance request into permission to mutate the global inventory.
|
|
// Reuse the router's effective org authorizer so owner membership removal
|
|
// also withdraws org-scoped issuance authority.
|
|
if (tokenActsForInstance(admitted) && !tokenActsForInstance(current)) ||
|
|
!r.checkTokenOrgAccessLocked(req.Context(), current, GetOrgID(req.Context())).Allowed {
|
|
return nil, &tokenMutationFailure{status: http.StatusForbidden, message: "Admin privileges required"}
|
|
}
|
|
clone := current.Clone()
|
|
attachAPITokenRecord(req, &clone)
|
|
return &clone, nil
|
|
}
|
|
|
|
// admittedTokenLocked returns the live record of the credential a request was
|
|
// admitted with, or nil once that credential has been revoked, rotated,
|
|
// expired, re-owned or given an invalid runtime role. Scope and organization
|
|
// edits leave the credential valid; callers judge those against their route.
|
|
// The caller holds config.Mu.
|
|
func admittedTokenLocked(live *config.Config, admitted *config.APITokenRecord) *config.APITokenRecord {
|
|
for i := range live.APITokens {
|
|
current := &live.APITokens[i]
|
|
if !constantTimeStringEqual(current.Hash, admitted.Hash) {
|
|
continue
|
|
}
|
|
// Authentication chooses the first matching credential hash. A newly
|
|
// shadowing record must not let an older context choose a later grant.
|
|
if current.ID != admitted.ID {
|
|
return nil
|
|
}
|
|
role := strings.TrimSpace(current.Metadata[internalauth.RuntimeRoleMetadataKey])
|
|
if current.IsExpired() || apiTokenAuthenticatedUser(current) != apiTokenAuthenticatedUser(admitted) ||
|
|
internalauth.ValidateRoleScopes(role, current.Scopes) != nil {
|
|
return nil
|
|
}
|
|
return current
|
|
}
|
|
return nil
|
|
}
|