Files
Pulse/internal/api/security_first_run_reset.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

135 lines
4.4 KiB
Go

package api
import (
"encoding/json"
"net/http"
"os"
"strings"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
"github.com/rs/zerolog/log"
)
type firstRunResetResponse struct {
BootstrapToken string `json:"bootstrapToken"`
BootstrapTokenPath string `json:"bootstrapTokenPath,omitempty"`
}
func devModeEnabled() bool {
return os.Getenv("PULSE_DEV") == "true" || strings.EqualFold(os.Getenv("NODE_ENV"), "development")
}
func (r *Router) handleResetFirstRunSecurity(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if !devModeEnabled() {
http.Error(w, "Development mode required", http.StatusForbidden)
return
}
if !CheckAuth(r.config, w, req) {
return
}
if !ensureSettingsWriteScope(r.config, w, req) {
return
}
// Prepare the recovery credential before changing any active authentication
// state. A failure here must leave the caller's current credentials usable so
// they can repair the data path and retry the reset.
token, bootstrapCreated, path, err := loadOrCreateBootstrapToken(r.config.DataPath)
if err != nil {
log.Error().Err(err).Msg("Failed to recreate bootstrap token during first-run reset")
http.Error(w, "Failed to recreate bootstrap token", http.StatusInternalServerError)
return
}
rollbackBootstrap := func() {
if !bootstrapCreated {
return
}
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
log.Error().Err(err).Str("token_path", path).Msg("Failed to roll back bootstrap token after first-run reset failure")
}
}
// Remove restart-time password configuration before committing token
// revocation. Runtime authentication remains unchanged until both durable
// operations succeed.
config.Mu.RLock()
configPathSnap := r.config.ConfigPath
dataPathSnap := r.config.DataPath
config.Mu.RUnlock()
unlockEnv := config.LockAuthEnvFiles(resolveAuthEnvWritePaths(configPathSnap, dataPathSnap)...)
authEnvSnapshots, err := snapshotAuthEnvFiles(configPathSnap, dataPathSnap)
if err != nil {
unlockEnv()
rollbackBootstrap()
log.Warn().Err(err).Msg("Failed to snapshot auth env files during first-run reset")
http.Error(w, "Failed to read persisted auth configuration", http.StatusInternalServerError)
return
}
if err := removeAuthEnvFiles(configPathSnap, dataPathSnap); err != nil {
if restoreErr := restoreAuthEnvFiles(authEnvSnapshots); restoreErr != nil {
log.Error().Err(restoreErr).Msg("Failed to restore auth env files after first-run reset failure")
}
unlockEnv()
rollbackBootstrap()
log.Warn().Err(err).Msg("Failed to remove auth env files during first-run reset")
http.Error(w, "Failed to remove persisted auth configuration", http.StatusInternalServerError)
return
}
config.Mu.Lock()
previousAuthUser := strings.TrimSpace(r.config.AuthUser)
if r.persistence != nil {
if err := r.persistence.SaveAPITokensReplaceInventory([]config.APITokenRecord{}); err != nil {
if config.IsDurablePublishSyncError(err) {
// Rename already published the empty token inventory on disk:
// clear the live slice so withdrawn credentials cannot continue
// authenticating while returning the durability error.
r.config.APIToken = ""
r.config.APITokens = nil
}
config.Mu.Unlock()
if restoreErr := restoreAuthEnvFiles(authEnvSnapshots); restoreErr != nil {
log.Error().Err(restoreErr).Msg("Failed to restore auth env files after API token reset failure")
}
unlockEnv()
rollbackBootstrap()
log.Warn().Err(err).Msg("Failed to clear persisted API tokens during first-run reset")
http.Error(w, "Failed to clear persisted API tokens", http.StatusInternalServerError)
return
}
}
r.config.AuthUser = ""
r.syncConfiguredAdminAuthorizer()
r.config.AuthPass = ""
for _, key := range []string{
"PULSE_AUTH_USER",
"PULSE_AUTH_PASS",
"REQUIRE_AUTH",
} {
_ = os.Unsetenv(key)
}
config.AdvanceAuthEnvRevision()
r.config.APIToken = ""
r.config.APITokens = nil
config.Mu.Unlock()
unlockEnv()
if previousAuthUser != "" {
InvalidateUserSessions(previousAuthUser)
}
r.clearSession(w, req)
r.bootstrapTokenHash = internalauth.HashAPIToken(token)
r.bootstrapTokenPath = path
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(firstRunResetResponse{
BootstrapToken: token,
BootstrapTokenPath: path,
})
}