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.
1883 lines
69 KiB
Go
1883 lines
69 KiB
Go
package api
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"maps"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/discovery"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/notifications"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/telemetry"
|
|
pulseupdates "github.com/rcourtman/pulse-go-rewrite/internal/updates"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/utils"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/websocket"
|
|
"github.com/rcourtman/pulse-go-rewrite/pkg/edition"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// SystemSettingsMonitor defines the monitor interface needed by system settings
|
|
type SystemSettingsMonitor interface {
|
|
GetDiscoveryService() *discovery.Service
|
|
StartDiscoveryService(ctx context.Context, wsHub *websocket.Hub, subnet string)
|
|
StopDiscoveryService()
|
|
EnableTemperatureMonitoring()
|
|
DisableTemperatureMonitoring()
|
|
GetNotificationManager() *notifications.NotificationManager
|
|
SetBackupPollingEnabled(enabled bool)
|
|
SetBackupPollingInterval(interval time.Duration)
|
|
SetPBSPollingInterval(interval time.Duration)
|
|
SetPMGPollingInterval(interval time.Duration)
|
|
ResetSSHFailureBackoff()
|
|
}
|
|
|
|
// SystemSettingsHandler handles system settings
|
|
type SystemSettingsHandler struct {
|
|
// Serialize the complete persisted read/modify/apply transaction. Locking
|
|
// only the final writes would still lose fields from concurrent partial saves.
|
|
updateMu sync.Mutex
|
|
stateMu sync.RWMutex
|
|
themeBroadcastMu sync.Mutex // Serializes WebSocket theme broadcasts in commit order
|
|
latestThemeSeq uint64 // Monotonic commit sequence for theme updates
|
|
config *config.Config
|
|
persistence *config.ConfigPersistence
|
|
wsHub *websocket.Hub
|
|
reloadSystemSettingsFunc func() // Function to reload cached system settings
|
|
reloadMonitorFunc func() error
|
|
telemetryToggleFunc func(enabled bool) // Legacy test callback when telemetry is toggled
|
|
telemetryToggleGenFunc func(enabled bool, consentGen uint64) // Generation-stamped callback when telemetry is toggled at runtime
|
|
telemetryPreviewFunc func() (telemetry.Ping, error)
|
|
telemetryResetFunc func() (telemetry.Ping, error)
|
|
// Called after the Proxmox guest Docker inventory opt-in changes at
|
|
// runtime, so the router can reconfigure the monitor's checker and
|
|
// collector without a restart.
|
|
guestDockerInventoryToggleFunc func()
|
|
mtMonitor interface {
|
|
GetMonitor(string) (*monitoring.Monitor, error)
|
|
}
|
|
defaultMonitor SystemSettingsMonitor
|
|
autoUpdateCapabilityFunc func() pulseupdates.AutoUpdateCapability
|
|
isProEditionFunc func() bool
|
|
}
|
|
|
|
type SystemSettingsResponse struct {
|
|
config.SystemSettings
|
|
EnvOverrides map[string]bool `json:"envOverrides"`
|
|
AutoUpdateCapability *pulseupdates.AutoUpdateCapability `json:"autoUpdateCapability,omitempty"`
|
|
}
|
|
|
|
type TelemetryPreviewResponse struct {
|
|
Enabled bool `json:"enabled"`
|
|
Payload telemetry.Ping `json:"payload"`
|
|
}
|
|
|
|
func EmptySystemSettingsResponse() SystemSettingsResponse {
|
|
return SystemSettingsResponse{}.NormalizeCollections()
|
|
}
|
|
|
|
func (r SystemSettingsResponse) NormalizeCollections() SystemSettingsResponse {
|
|
if r.EnvOverrides == nil {
|
|
r.EnvOverrides = map[string]bool{}
|
|
}
|
|
return r
|
|
}
|
|
|
|
// NewSystemSettingsHandler creates a new system settings handler
|
|
func NewSystemSettingsHandler(cfg *config.Config, persistence *config.ConfigPersistence, wsHub *websocket.Hub, mtm *monitoring.MultiTenantMonitor, monitor SystemSettingsMonitor, reloadSystemSettingsFunc func(), reloadMonitorFunc func() error) *SystemSettingsHandler {
|
|
// If mtm is provided, try to populate defaultMonitor from "default" org if not provided.
|
|
if monitor == nil && mtm != nil {
|
|
if m, err := mtm.GetMonitor("default"); err == nil {
|
|
monitor = m
|
|
}
|
|
}
|
|
return &SystemSettingsHandler{
|
|
config: cfg,
|
|
persistence: persistence,
|
|
wsHub: wsHub,
|
|
mtMonitor: mtm,
|
|
defaultMonitor: monitor,
|
|
reloadSystemSettingsFunc: reloadSystemSettingsFunc,
|
|
reloadMonitorFunc: reloadMonitorFunc,
|
|
}
|
|
}
|
|
|
|
// SetTelemetryToggleFunc sets the callback invoked when telemetry is toggled
|
|
// at runtime (true = start, false = stop).
|
|
func (h *SystemSettingsHandler) SetTelemetryToggleFunc(fn func(enabled bool)) {
|
|
h.telemetryToggleFunc = fn
|
|
}
|
|
|
|
// SetTelemetryToggleGenerationFunc sets the generation-stamped callback invoked
|
|
// when telemetry is toggled at runtime.
|
|
func (h *SystemSettingsHandler) SetTelemetryToggleGenerationFunc(fn func(enabled bool, consentGen uint64)) {
|
|
h.telemetryToggleGenFunc = fn
|
|
}
|
|
|
|
// SetGuestDockerInventoryToggleFunc sets the callback invoked after the
|
|
// Proxmox guest Docker inventory opt-in changes at runtime.
|
|
func (h *SystemSettingsHandler) SetGuestDockerInventoryToggleFunc(fn func()) {
|
|
h.guestDockerInventoryToggleFunc = fn
|
|
}
|
|
|
|
// SetTelemetryPreviewFunc sets the callback used to build the exact telemetry
|
|
// payload preview exposed through the system settings API.
|
|
func (h *SystemSettingsHandler) SetTelemetryPreviewFunc(fn func() (telemetry.Ping, error)) {
|
|
h.telemetryPreviewFunc = fn
|
|
}
|
|
|
|
// SetTelemetryResetFunc sets the callback used to rotate the telemetry install
|
|
// identifier and rebuild the current preview payload.
|
|
func (h *SystemSettingsHandler) SetTelemetryResetFunc(fn func() (telemetry.Ping, error)) {
|
|
h.telemetryResetFunc = fn
|
|
}
|
|
|
|
// SetMonitor updates the monitor reference used by the handler at runtime.
|
|
func (h *SystemSettingsHandler) SetMonitor(m SystemSettingsMonitor) {
|
|
h.stateMu.Lock()
|
|
defer h.stateMu.Unlock()
|
|
h.defaultMonitor = m
|
|
}
|
|
|
|
// SetMultiTenantMonitor updates the multi-tenant monitor reference
|
|
func (h *SystemSettingsHandler) SetMultiTenantMonitor(mtm *monitoring.MultiTenantMonitor) {
|
|
var defaultMonitor SystemSettingsMonitor
|
|
if mtm != nil {
|
|
if m, err := mtm.GetMonitor("default"); err == nil {
|
|
defaultMonitor = m
|
|
}
|
|
}
|
|
|
|
h.stateMu.Lock()
|
|
defer h.stateMu.Unlock()
|
|
h.mtMonitor = mtm
|
|
if defaultMonitor != nil {
|
|
h.defaultMonitor = defaultMonitor
|
|
}
|
|
}
|
|
|
|
// updateInstanceConfig shares the actual mutation/capture boundary with tenant
|
|
// construction. Only config writes belong in fn; initialization and runtime
|
|
// side effects stay outside it. The call is synchronous, never queued.
|
|
func (h *SystemSettingsHandler) updateInstanceConfig(fn func()) {
|
|
h.stateMu.RLock()
|
|
mtMonitor := h.mtMonitor
|
|
h.stateMu.RUnlock()
|
|
if updater, ok := mtMonitor.(interface{ UpdateInstanceSettings(func()) }); ok && updater != nil {
|
|
updater.UpdateInstanceSettings(fn)
|
|
return
|
|
}
|
|
fn()
|
|
}
|
|
|
|
// forEachNotificationManager applies fn to the notification manager of every
|
|
// live tenant monitor when multi-tenant iteration is available, falling back
|
|
// to the request's monitor otherwise. Instance-wide notification settings
|
|
// (webhook security allowlist, public URL) must reach every org's manager.
|
|
func (h *SystemSettingsHandler) forEachNotificationManager(r *http.Request, fn func(*notifications.NotificationManager)) {
|
|
h.stateMu.RLock()
|
|
mtMonitor := h.mtMonitor
|
|
h.stateMu.RUnlock()
|
|
|
|
type monitorRanger interface {
|
|
ForEachMonitor(func(*monitoring.Monitor))
|
|
}
|
|
if ranger, ok := mtMonitor.(monitorRanger); ok && ranger != nil {
|
|
ranger.ForEachMonitor(func(m *monitoring.Monitor) {
|
|
if nm := m.GetNotificationManager(); nm != nil {
|
|
fn(nm)
|
|
}
|
|
})
|
|
return
|
|
}
|
|
if monitor := h.getMonitor(r.Context()); monitor != nil {
|
|
if nm := monitor.GetNotificationManager(); nm != nil {
|
|
fn(nm)
|
|
}
|
|
}
|
|
}
|
|
|
|
// forEachTenantMonitor applies fn to every live tenant monitor when
|
|
// multi-tenant iteration is available, falling back to the request's monitor
|
|
// otherwise. Instance-wide polling cadence settings must reach every org's
|
|
// monitor: each one polls against a detached copy of the base config, so
|
|
// mutating h.config alone never affects a running monitor.
|
|
func (h *SystemSettingsHandler) forEachTenantMonitor(r *http.Request, fn func(SystemSettingsMonitor)) {
|
|
h.stateMu.RLock()
|
|
mtMonitor := h.mtMonitor
|
|
h.stateMu.RUnlock()
|
|
|
|
type monitorRanger interface {
|
|
ForEachMonitor(func(*monitoring.Monitor))
|
|
}
|
|
if ranger, ok := mtMonitor.(monitorRanger); ok && ranger != nil {
|
|
ranger.ForEachMonitor(func(m *monitoring.Monitor) {
|
|
fn(m)
|
|
})
|
|
return
|
|
}
|
|
if monitor := h.getMonitor(r.Context()); monitor != nil {
|
|
fn(monitor)
|
|
}
|
|
}
|
|
|
|
func (h *SystemSettingsHandler) getMonitor(ctx context.Context) SystemSettingsMonitor {
|
|
h.stateMu.RLock()
|
|
mtMonitor := h.mtMonitor
|
|
defaultMonitor := h.defaultMonitor
|
|
h.stateMu.RUnlock()
|
|
|
|
orgID := strings.TrimSpace(GetOrgID(ctx))
|
|
if orgID == "" || orgID == "default" {
|
|
if mtMonitor != nil {
|
|
if m, err := mtMonitor.GetMonitor(orgID); err == nil && m != nil {
|
|
return m
|
|
}
|
|
}
|
|
return defaultMonitor
|
|
}
|
|
|
|
// Never fall back to the default organization's runtime for another
|
|
// organization: its requests would read or change the wrong tenant.
|
|
if mtMonitor == nil {
|
|
log.Warn().Str("org_id", orgID).Msg("Tenant monitor manager unavailable for system settings request")
|
|
return nil
|
|
}
|
|
m, err := mtMonitor.GetMonitor(orgID)
|
|
if err != nil || m == nil {
|
|
log.Warn().Err(err).Str("org_id", orgID).Msg("Failed to resolve tenant monitor for system settings request")
|
|
return nil
|
|
}
|
|
return m
|
|
}
|
|
|
|
// requireMonitor resolves the request organization's monitor, writing a 503
|
|
// and returning nil when it is unavailable.
|
|
func (h *SystemSettingsHandler) requireMonitor(w http.ResponseWriter, r *http.Request) SystemSettingsMonitor {
|
|
monitor := h.getMonitor(r.Context())
|
|
if monitor == nil {
|
|
writeErrorResponse(w, http.StatusServiceUnavailable, "tenant_unavailable", "Tenant monitor is not available", nil)
|
|
return nil
|
|
}
|
|
return monitor
|
|
}
|
|
|
|
// SetConfig updates the configuration reference used by the handler.
|
|
func (h *SystemSettingsHandler) SetConfig(cfg *config.Config) {
|
|
if cfg == nil {
|
|
return
|
|
}
|
|
h.stateMu.Lock()
|
|
h.config = cfg
|
|
h.stateMu.Unlock()
|
|
}
|
|
|
|
func (h *SystemSettingsHandler) currentConfig() *config.Config {
|
|
if h == nil {
|
|
return nil
|
|
}
|
|
h.stateMu.RLock()
|
|
cfg := h.config
|
|
h.stateMu.RUnlock()
|
|
return cfg
|
|
}
|
|
|
|
func (h *SystemSettingsHandler) ensureWriteAccess(w http.ResponseWriter, r *http.Request) bool {
|
|
cfg := h.currentConfig()
|
|
// Require authentication
|
|
authWriter := &responseCapture{ResponseWriter: w}
|
|
if !checkAuth(cfg, authWriter, r, false) {
|
|
if !authWriter.wrote {
|
|
writeErrorResponse(w, http.StatusUnauthorized, "unauthorized", "Unauthorized", nil)
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Check if using proxy auth and if so, verify admin status using a
|
|
// synchronized snapshot of the proxy auth fields so reload cannot race.
|
|
config.Mu.RLock()
|
|
var proxyCfg config.Config
|
|
if cfg != nil {
|
|
proxyCfg = config.Config{
|
|
ProxyAuthSecret: cfg.ProxyAuthSecret,
|
|
ProxyAuthUserHeader: cfg.ProxyAuthUserHeader,
|
|
ProxyAuthRoleHeader: cfg.ProxyAuthRoleHeader,
|
|
ProxyAuthAdminRole: cfg.ProxyAuthAdminRole,
|
|
ProxyAuthRoleSeparator: cfg.ProxyAuthRoleSeparator,
|
|
}
|
|
}
|
|
config.Mu.RUnlock()
|
|
if proxyCfg.ProxyAuthSecret != "" {
|
|
if valid, username, isAdmin := CheckProxyAuth(&proxyCfg, r); valid {
|
|
if !isAdmin {
|
|
log.Warn().
|
|
Str("ip", r.RemoteAddr).
|
|
Str("path", r.URL.Path).
|
|
Str("method", r.Method).
|
|
Str("username", username).
|
|
Msg("Non-admin user attempted to update system settings")
|
|
|
|
writeErrorResponse(w, http.StatusForbidden, "forbidden", "Admin privileges required", nil)
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
|
|
// SECURITY: Session users must match configured admin identity for settings writes.
|
|
if !ensureSettingsWriteScope(cfg, w, r) {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
func discoveryConfigMap(raw map[string]interface{}) (map[string]interface{}, bool) {
|
|
if raw == nil {
|
|
return nil, false
|
|
}
|
|
if val, ok := raw["discoveryConfig"]; ok {
|
|
if cfgMap, ok := val.(map[string]interface{}); ok {
|
|
return cfgMap, true
|
|
}
|
|
return nil, true
|
|
}
|
|
return nil, false
|
|
}
|
|
|
|
func parseDiscoveryStringArray(value interface{}, field string) ([]string, error) {
|
|
items, ok := value.([]interface{})
|
|
if !ok {
|
|
return nil, fmt.Errorf("%s must be an array of CIDR strings", field)
|
|
}
|
|
out := make([]string, 0, len(items))
|
|
for _, item := range items {
|
|
entry, ok := item.(string)
|
|
if !ok {
|
|
return nil, fmt.Errorf("%s entries must be strings", field)
|
|
}
|
|
out = append(out, entry)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func parseDiscoveryWholeNumber(value interface{}, field string) (int, error) {
|
|
raw, ok := value.(float64)
|
|
if !ok {
|
|
return 0, fmt.Errorf("%s must be a number", field)
|
|
}
|
|
if raw != float64(int(raw)) {
|
|
return 0, fmt.Errorf("%s must be a whole number", field)
|
|
}
|
|
return int(raw), nil
|
|
}
|
|
|
|
func applyDiscoveryConfigOverrides(current config.DiscoveryConfig, cfgMap map[string]interface{}) (config.DiscoveryConfig, error) {
|
|
if envVal, ok := cfgMap["environmentOverride"]; ok {
|
|
envStr, ok := envVal.(string)
|
|
if !ok {
|
|
return current, fmt.Errorf("discoveryConfig.environmentOverride must be a string")
|
|
}
|
|
canonicalEnv, valid := config.CanonicalDiscoveryEnvironment(envStr)
|
|
if !valid {
|
|
return current, fmt.Errorf("invalid discovery environment override: %s", envStr)
|
|
}
|
|
current.EnvironmentOverride = canonicalEnv
|
|
}
|
|
|
|
if val, ok := cfgMap["subnetAllowlist"]; ok {
|
|
allowlist, err := parseDiscoveryStringArray(val, "discoveryConfig.subnetAllowlist")
|
|
if err != nil {
|
|
return current, err
|
|
}
|
|
current.SubnetAllowlist = allowlist
|
|
}
|
|
|
|
if val, ok := cfgMap["subnetBlocklist"]; ok {
|
|
blocklist, err := parseDiscoveryStringArray(val, "discoveryConfig.subnetBlocklist")
|
|
if err != nil {
|
|
return current, err
|
|
}
|
|
current.SubnetBlocklist = blocklist
|
|
}
|
|
|
|
if val, ok := cfgMap["maxHostsPerScan"]; ok {
|
|
maxHosts, err := parseDiscoveryWholeNumber(val, "discoveryConfig.maxHostsPerScan")
|
|
if err != nil {
|
|
return current, err
|
|
}
|
|
current.MaxHostsPerScan = maxHosts
|
|
}
|
|
|
|
if val, ok := cfgMap["maxConcurrent"]; ok {
|
|
maxConcurrent, err := parseDiscoveryWholeNumber(val, "discoveryConfig.maxConcurrent")
|
|
if err != nil {
|
|
return current, err
|
|
}
|
|
current.MaxConcurrent = maxConcurrent
|
|
}
|
|
|
|
if val, ok := cfgMap["enableReverseDns"]; ok {
|
|
enabled, ok := val.(bool)
|
|
if !ok {
|
|
return current, fmt.Errorf("discoveryConfig.enableReverseDns must be a boolean")
|
|
}
|
|
current.EnableReverseDNS = enabled
|
|
}
|
|
|
|
if val, ok := cfgMap["scanGateways"]; ok {
|
|
enabled, ok := val.(bool)
|
|
if !ok {
|
|
return current, fmt.Errorf("discoveryConfig.scanGateways must be a boolean")
|
|
}
|
|
current.ScanGateways = enabled
|
|
}
|
|
|
|
if val, ok := cfgMap["dialTimeoutMs"]; ok {
|
|
dialTimeout, err := parseDiscoveryWholeNumber(val, "discoveryConfig.dialTimeoutMs")
|
|
if err != nil {
|
|
return current, err
|
|
}
|
|
current.DialTimeout = dialTimeout
|
|
}
|
|
|
|
if val, ok := cfgMap["httpTimeoutMs"]; ok {
|
|
httpTimeout, err := parseDiscoveryWholeNumber(val, "discoveryConfig.httpTimeoutMs")
|
|
if err != nil {
|
|
return current, err
|
|
}
|
|
current.HTTPTimeout = httpTimeout
|
|
}
|
|
|
|
return config.NormalizeDiscoveryConfig(current), nil
|
|
}
|
|
|
|
// validateSystemSettings validates settings before applying them
|
|
var (
|
|
systemSettingsCanonicalKeysOnce sync.Once
|
|
systemSettingsCanonicalKeys []string
|
|
)
|
|
|
|
func getSystemSettingsCanonicalKeys() []string {
|
|
systemSettingsCanonicalKeysOnce.Do(func() {
|
|
t := reflect.TypeOf(config.SystemSettings{})
|
|
keys := make([]string, 0, t.NumField())
|
|
for i := 0; i < t.NumField(); i++ {
|
|
tag := t.Field(i).Tag.Get("json")
|
|
if tag == "" || tag == "-" {
|
|
continue
|
|
}
|
|
name, _, _ := strings.Cut(tag, ",")
|
|
if name != "" && name != "-" {
|
|
keys = append(keys, name)
|
|
}
|
|
}
|
|
systemSettingsCanonicalKeys = keys
|
|
})
|
|
return systemSettingsCanonicalKeys
|
|
}
|
|
|
|
func canonicalizeSystemSettingsRawKeys(raw map[string]interface{}) map[string]interface{} {
|
|
if len(raw) == 0 {
|
|
return raw
|
|
}
|
|
canonicalKeys := getSystemSettingsCanonicalKeys()
|
|
out := make(map[string]interface{}, len(raw))
|
|
for k, v := range raw {
|
|
mapped := k
|
|
for _, canon := range canonicalKeys {
|
|
if strings.EqualFold(k, canon) {
|
|
mapped = canon
|
|
break
|
|
}
|
|
}
|
|
out[mapped] = v
|
|
}
|
|
return out
|
|
}
|
|
|
|
func validateSystemSettings(_ *config.SystemSettings, rawRequest map[string]interface{}) error {
|
|
if value, present := rawRequest["allowedOrigins"]; present {
|
|
if _, ok := value.(string); !ok {
|
|
return fmt.Errorf("allowedOrigins must be a string (use an empty string for same-origin only)")
|
|
}
|
|
}
|
|
|
|
if val, ok := rawRequest["reportBranding"]; ok {
|
|
settings, ok := val.(map[string]interface{})
|
|
if !ok {
|
|
return fmt.Errorf("reportBranding must be an object")
|
|
}
|
|
if err := validateReportBrandingSettings(settings); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
rawFieldFold := func(name string) (interface{}, bool) {
|
|
if val, ok := rawRequest[name]; ok {
|
|
return val, true
|
|
}
|
|
for k, v := range rawRequest {
|
|
if strings.EqualFold(k, name) {
|
|
return v, true
|
|
}
|
|
}
|
|
return nil, false
|
|
}
|
|
|
|
if val, ok := rawFieldFold("pvePollingInterval"); ok {
|
|
if interval, ok := val.(float64); ok {
|
|
if interval <= 0 {
|
|
return fmt.Errorf("PVE polling interval must be positive (minimum 10 seconds)")
|
|
}
|
|
if interval < 10 {
|
|
return fmt.Errorf("PVE polling interval must be at least 10 seconds")
|
|
}
|
|
if interval > 3600 {
|
|
return fmt.Errorf("PVE polling interval cannot exceed 3600 seconds (1 hour)")
|
|
}
|
|
} else {
|
|
return fmt.Errorf("PVE polling interval must be a number")
|
|
}
|
|
}
|
|
|
|
if val, ok := rawFieldFold("pbsPollingInterval"); ok {
|
|
if interval, ok := val.(float64); ok {
|
|
if interval <= 0 {
|
|
return fmt.Errorf("PBS polling interval must be positive (minimum 10 seconds)")
|
|
}
|
|
if interval < 10 {
|
|
return fmt.Errorf("PBS polling interval must be at least 10 seconds")
|
|
}
|
|
if interval > 3600 {
|
|
return fmt.Errorf("PBS polling interval cannot exceed 3600 seconds (1 hour)")
|
|
}
|
|
} else {
|
|
return fmt.Errorf("PBS polling interval must be a number")
|
|
}
|
|
}
|
|
|
|
if val, ok := rawFieldFold("pmgPollingInterval"); ok {
|
|
if interval, ok := val.(float64); ok {
|
|
if interval <= 0 {
|
|
return fmt.Errorf("PMG polling interval must be positive (minimum 10 seconds)")
|
|
}
|
|
if interval < 10 {
|
|
return fmt.Errorf("PMG polling interval must be at least 10 seconds")
|
|
}
|
|
if interval > 3600 {
|
|
return fmt.Errorf("PMG polling interval cannot exceed 3600 seconds (1 hour)")
|
|
}
|
|
} else {
|
|
return fmt.Errorf("PMG polling interval must be a number")
|
|
}
|
|
}
|
|
|
|
if val, ok := rawFieldFold("backupPollingInterval"); ok {
|
|
if interval, ok := val.(float64); ok {
|
|
if interval < 0 {
|
|
return fmt.Errorf("backup polling interval cannot be negative")
|
|
}
|
|
if interval > 0 && interval < 10 {
|
|
return fmt.Errorf("backup polling interval must be at least 10 seconds")
|
|
}
|
|
if interval > 604800 {
|
|
return fmt.Errorf("backup polling interval cannot exceed 604800 seconds (7 days)")
|
|
}
|
|
} else {
|
|
return fmt.Errorf("backup polling interval must be a number")
|
|
}
|
|
}
|
|
|
|
// Validate boolean fields have correct type
|
|
if val, ok := rawRequest["autoUpdateEnabled"]; ok {
|
|
if _, ok := val.(bool); !ok {
|
|
return fmt.Errorf("autoUpdateEnabled must be a boolean")
|
|
}
|
|
}
|
|
if val, ok := rawRequest["autoUpdatePreviewConsent"]; ok {
|
|
if _, ok := val.(bool); !ok {
|
|
return fmt.Errorf("autoUpdatePreviewConsent must be a boolean")
|
|
}
|
|
}
|
|
if val, ok := rawRequest["autoUpdateProConsent"]; ok {
|
|
if _, ok := val.(bool); !ok {
|
|
return fmt.Errorf("autoUpdateProConsent must be a boolean")
|
|
}
|
|
}
|
|
|
|
if val, ok := rawRequest["discoveryEnabled"]; ok {
|
|
if _, ok := val.(bool); !ok {
|
|
return fmt.Errorf("discoveryEnabled must be a boolean")
|
|
}
|
|
}
|
|
|
|
if val, ok := rawRequest["allowEmbedding"]; ok {
|
|
if _, ok := val.(bool); !ok {
|
|
return fmt.Errorf("allowEmbedding must be a boolean")
|
|
}
|
|
}
|
|
|
|
if val, ok := rawRequest["backupPollingEnabled"]; ok {
|
|
if _, ok := val.(bool); !ok {
|
|
return fmt.Errorf("backupPollingEnabled must be a boolean")
|
|
}
|
|
}
|
|
|
|
if val, ok := rawRequest["temperatureMonitoringEnabled"]; ok {
|
|
if _, ok := val.(bool); !ok {
|
|
return fmt.Errorf("temperatureMonitoringEnabled must be a boolean")
|
|
}
|
|
}
|
|
|
|
if val, ok := rawRequest["reduceProUpsellNoise"]; ok {
|
|
if _, ok := val.(bool); !ok {
|
|
return fmt.Errorf("reduceProUpsellNoise must be a boolean")
|
|
}
|
|
}
|
|
|
|
if cfgMap, cfgProvided := discoveryConfigMap(rawRequest); cfgProvided {
|
|
if cfgMap == nil {
|
|
return fmt.Errorf("discoveryConfig must be an object")
|
|
}
|
|
|
|
allowedDiscoveryConfigFields := map[string]struct{}{
|
|
"environmentOverride": {},
|
|
"subnetAllowlist": {},
|
|
"subnetBlocklist": {},
|
|
"maxHostsPerScan": {},
|
|
"maxConcurrent": {},
|
|
"enableReverseDns": {},
|
|
"scanGateways": {},
|
|
"dialTimeoutMs": {},
|
|
"httpTimeoutMs": {},
|
|
}
|
|
for key := range cfgMap {
|
|
if _, ok := allowedDiscoveryConfigFields[key]; !ok {
|
|
return fmt.Errorf("discoveryConfig.%s is not supported", key)
|
|
}
|
|
}
|
|
|
|
if envVal, exists := cfgMap["environmentOverride"]; exists {
|
|
envStr, ok := envVal.(string)
|
|
if !ok {
|
|
return fmt.Errorf("discoveryConfig.environmentOverride must be a string")
|
|
}
|
|
if !config.IsValidDiscoveryEnvironment(envStr) {
|
|
return fmt.Errorf("invalid discovery environment override: %s", envStr)
|
|
}
|
|
}
|
|
|
|
if allowVal, exists := cfgMap["subnetAllowlist"]; exists {
|
|
items, ok := allowVal.([]interface{})
|
|
if !ok {
|
|
return fmt.Errorf("discoveryConfig.subnetAllowlist must be an array of CIDR strings")
|
|
}
|
|
for _, item := range items {
|
|
cidr, ok := item.(string)
|
|
if !ok {
|
|
return fmt.Errorf("discoveryConfig.subnetAllowlist entries must be strings")
|
|
}
|
|
if _, _, err := net.ParseCIDR(cidr); err != nil {
|
|
return fmt.Errorf("invalid CIDR in discoveryConfig.subnetAllowlist: %s", cidr)
|
|
}
|
|
}
|
|
}
|
|
|
|
if blockVal, exists := cfgMap["subnetBlocklist"]; exists {
|
|
items, ok := blockVal.([]interface{})
|
|
if !ok {
|
|
return fmt.Errorf("discoveryConfig.subnetBlocklist must be an array of CIDR strings")
|
|
}
|
|
for _, item := range items {
|
|
cidr, ok := item.(string)
|
|
if !ok {
|
|
return fmt.Errorf("discoveryConfig.subnetBlocklist entries must be strings")
|
|
}
|
|
if _, _, err := net.ParseCIDR(cidr); err != nil {
|
|
return fmt.Errorf("invalid CIDR in discoveryConfig.subnetBlocklist: %s", cidr)
|
|
}
|
|
}
|
|
}
|
|
|
|
if hostsVal, exists := cfgMap["maxHostsPerScan"]; exists {
|
|
value, ok := hostsVal.(float64)
|
|
if !ok {
|
|
return fmt.Errorf("discoveryConfig.maxHostsPerScan must be a number")
|
|
}
|
|
if value <= 0 || value != float64(int(value)) {
|
|
return fmt.Errorf("discoveryConfig.maxHostsPerScan must be a whole number greater than zero")
|
|
}
|
|
}
|
|
|
|
if concurrentVal, exists := cfgMap["maxConcurrent"]; exists {
|
|
value, ok := concurrentVal.(float64)
|
|
if !ok {
|
|
return fmt.Errorf("discoveryConfig.maxConcurrent must be a number")
|
|
}
|
|
if value <= 0 || value > 1000 || value != float64(int(value)) {
|
|
return fmt.Errorf("discoveryConfig.maxConcurrent must be a whole number between 1 and 1000")
|
|
}
|
|
}
|
|
|
|
if val, exists := cfgMap["enableReverseDns"]; exists {
|
|
if _, ok := val.(bool); !ok {
|
|
return fmt.Errorf("discoveryConfig.enableReverseDns must be a boolean")
|
|
}
|
|
}
|
|
|
|
if val, exists := cfgMap["scanGateways"]; exists {
|
|
if _, ok := val.(bool); !ok {
|
|
return fmt.Errorf("discoveryConfig.scanGateways must be a boolean")
|
|
}
|
|
}
|
|
|
|
if val, exists := cfgMap["dialTimeoutMs"]; exists {
|
|
timeout, ok := val.(float64)
|
|
if !ok {
|
|
return fmt.Errorf("discoveryConfig.dialTimeoutMs must be a number")
|
|
}
|
|
if timeout <= 0 || timeout != float64(int(timeout)) {
|
|
return fmt.Errorf("discoveryConfig.dialTimeoutMs must be a whole number greater than zero")
|
|
}
|
|
}
|
|
|
|
if val, exists := cfgMap["httpTimeoutMs"]; exists {
|
|
timeout, ok := val.(float64)
|
|
if !ok {
|
|
return fmt.Errorf("discoveryConfig.httpTimeoutMs must be a number")
|
|
}
|
|
if timeout <= 0 || timeout != float64(int(timeout)) {
|
|
return fmt.Errorf("discoveryConfig.httpTimeoutMs must be a whole number greater than zero")
|
|
}
|
|
}
|
|
}
|
|
|
|
// Validate connection timeout (min 1 second, max 5 minutes)
|
|
if val, ok := rawRequest["connectionTimeout"]; ok {
|
|
if timeout, ok := val.(float64); ok {
|
|
if timeout < 0 {
|
|
return fmt.Errorf("connection timeout cannot be negative")
|
|
}
|
|
if timeout > 0 && timeout < 1 {
|
|
return fmt.Errorf("connection timeout must be at least 1 second")
|
|
}
|
|
if timeout > 300 {
|
|
return fmt.Errorf("connection timeout cannot exceed 300 seconds (5 minutes)")
|
|
}
|
|
} else {
|
|
return fmt.Errorf("connection timeout must be a number")
|
|
}
|
|
}
|
|
|
|
// Validate theme
|
|
if val, ok := rawRequest["theme"]; ok {
|
|
if theme, ok := val.(string); ok {
|
|
if theme != "" && theme != "light" && theme != "dark" {
|
|
return fmt.Errorf("theme must be 'light', 'dark', or empty")
|
|
}
|
|
} else {
|
|
return fmt.Errorf("theme must be a string")
|
|
}
|
|
}
|
|
|
|
// Validate update channel
|
|
if val, ok := rawRequest["updateChannel"]; ok {
|
|
if channel, ok := val.(string); ok {
|
|
if channel != "" && channel != "stable" && channel != "rc" {
|
|
return fmt.Errorf("update channel must be 'stable' or 'rc'")
|
|
}
|
|
} else {
|
|
return fmt.Errorf("update channel must be a string")
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func validateReportBrandingSettings(settings map[string]interface{}) error {
|
|
allowed := map[string]struct{}{
|
|
"displayName": {},
|
|
"logoBase64": {},
|
|
"logoFormat": {},
|
|
}
|
|
for key, val := range settings {
|
|
if _, ok := allowed[key]; !ok {
|
|
return fmt.Errorf("reportBranding.%s is not supported", key)
|
|
}
|
|
str, ok := val.(string)
|
|
if !ok {
|
|
return fmt.Errorf("reportBranding.%s must be a string", key)
|
|
}
|
|
if strings.ContainsAny(str, "\r\n") {
|
|
return fmt.Errorf("reportBranding.%s must not contain newlines", key)
|
|
}
|
|
switch key {
|
|
case "displayName":
|
|
if len(strings.TrimSpace(str)) > config.ReportBrandDisplayNameMaxLength {
|
|
return fmt.Errorf("reportBranding.displayName must be <= %d characters", config.ReportBrandDisplayNameMaxLength)
|
|
}
|
|
case "logoBase64":
|
|
if _, err := config.DecodeReportBrandLogoBase64(str); err != nil {
|
|
return fmt.Errorf("reportBranding.%s", err.Error())
|
|
}
|
|
case "logoFormat":
|
|
if _, ok := config.CanonicalReportBrandLogoFormat(str); !ok {
|
|
return fmt.Errorf("reportBranding.logoFormat must be png, jpg, jpeg, gif, or empty")
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// HandleGetSystemSettings returns the current system settings
|
|
func (h *SystemSettingsHandler) HandleGetSystemSettings(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)
|
|
return
|
|
}
|
|
|
|
cfg := h.currentConfig()
|
|
// SECURITY: Session users must match configured admin identity for settings reads.
|
|
if !ensureSettingsReadScope(cfg, w, r) {
|
|
return
|
|
}
|
|
|
|
settings, err := h.persistence.LoadSystemSettings()
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("Failed to load system settings")
|
|
settings = config.DefaultSystemSettings()
|
|
}
|
|
if settings == nil {
|
|
settings = config.DefaultSystemSettings()
|
|
}
|
|
|
|
// Log loaded settings for debugging
|
|
if settings != nil {
|
|
log.Debug().
|
|
Str("theme", settings.Theme).
|
|
Msg("Loaded system settings for API response")
|
|
|
|
config.Mu.RLock()
|
|
cfgUpdateChannel := cfg.UpdateChannel
|
|
cfgAllowedOrigins := cfg.AllowedOrigins
|
|
cfgPVEPollingInterval := cfg.PVEPollingInterval
|
|
cfgBackupPollingInterval := cfg.BackupPollingInterval
|
|
cfgEnableBackupPolling := cfg.EnableBackupPolling
|
|
cfgDiscovery := config.CloneDiscoveryConfig(cfg.Discovery)
|
|
cfgTemperatureMonitoringEnabled := cfg.TemperatureMonitoringEnabled
|
|
cfgDisableDockerUpdateActions := cfg.DisableDockerUpdateActions
|
|
cfgEnableProxmoxGuestDockerInventory := cfg.EnableProxmoxGuestDockerInventory
|
|
cfgEnvOverrides := maps.Clone(cfg.EnvOverrides)
|
|
config.Mu.RUnlock()
|
|
|
|
settings.UpdateChannel = config.EffectiveUpdateChannel(settings.UpdateChannel, cfgUpdateChannel)
|
|
// Expose the effective policy, including deployment overrides and clears.
|
|
settings.AllowedOrigins = cfgAllowedOrigins
|
|
// Always expose effective backup polling configuration
|
|
settings.PVEPollingInterval = int(cfgPVEPollingInterval.Seconds())
|
|
settings.BackupPollingInterval = int(cfgBackupPollingInterval.Seconds())
|
|
enabled := cfgEnableBackupPolling
|
|
settings.BackupPollingEnabled = &enabled
|
|
settings.DiscoveryConfig = cfgDiscovery
|
|
settings.TemperatureMonitoringEnabled = cfgTemperatureMonitoringEnabled
|
|
// Expose Docker update actions setting (respects env override)
|
|
settings.DisableDockerUpdateActions = cfgDisableDockerUpdateActions
|
|
// Expose the Proxmox guest Docker inventory opt-in (respects env override)
|
|
settings.EnableProxmoxGuestDockerInventory = cfgEnableProxmoxGuestDockerInventory
|
|
// Expose effective telemetry value from the shared synchronized consent resolver
|
|
effectiveTelemetry := ResolveEffectiveTelemetryEnabled(cfg, h.persistence)
|
|
settings.TelemetryEnabled = &effectiveTelemetry
|
|
proEdition := edition.IsPro()
|
|
if h.isProEditionFunc != nil {
|
|
proEdition = h.isProEditionFunc()
|
|
}
|
|
settings.AutoUpdateProConsent = config.EffectiveAutoUpdateProConsent(settings.AutoUpdateEnabled, proEdition, settings.AutoUpdateProConsent)
|
|
settings.AutoUpdatePreviewConsent = config.EffectiveAutoUpdatePreviewConsent(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent)
|
|
if proEdition && !settings.AutoUpdateProConsent {
|
|
settings.AutoUpdatePreviewConsent = false
|
|
}
|
|
settings.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabledForEdition(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent, proEdition, settings.AutoUpdateProConsent)
|
|
|
|
response := EmptySystemSettingsResponse()
|
|
response.SystemSettings = *settings
|
|
if len(cfgEnvOverrides) > 0 || config.IsAutoUpdateDisabledByEnv() {
|
|
copied := make(map[string]bool, len(cfgEnvOverrides)+2)
|
|
for k, v := range cfgEnvOverrides {
|
|
copied[k] = v
|
|
}
|
|
if config.IsAutoUpdateDisabledByEnv() {
|
|
copied["autoUpdateEnabled"] = true
|
|
copied["PULSE_DISABLE_AUTO_UPDATE"] = true
|
|
}
|
|
response.EnvOverrides = copied
|
|
}
|
|
detectCapability := h.autoUpdateCapabilityFunc
|
|
if detectCapability == nil {
|
|
detectCapability = pulseupdates.DetectAutoUpdateCapability
|
|
}
|
|
capVal := detectCapability()
|
|
response.AutoUpdateCapability = &capVal
|
|
response = response.NormalizeCollections()
|
|
|
|
if err := utils.WriteJSONResponse(w, response); err != nil {
|
|
log.Error().Err(err).Msg("Failed to write system settings response")
|
|
}
|
|
return
|
|
}
|
|
|
|
// Include env override information
|
|
response := EmptySystemSettingsResponse()
|
|
config.Mu.RLock()
|
|
cfgEnvOverrides := maps.Clone(cfg.EnvOverrides)
|
|
config.Mu.RUnlock()
|
|
if len(cfgEnvOverrides) > 0 || config.IsAutoUpdateDisabledByEnv() {
|
|
copied := make(map[string]bool, len(cfgEnvOverrides)+2)
|
|
for k, v := range cfgEnvOverrides {
|
|
copied[k] = v
|
|
}
|
|
if config.IsAutoUpdateDisabledByEnv() {
|
|
copied["autoUpdateEnabled"] = true
|
|
copied["PULSE_DISABLE_AUTO_UPDATE"] = true
|
|
}
|
|
response.EnvOverrides = copied
|
|
}
|
|
detectCapability := h.autoUpdateCapabilityFunc
|
|
if detectCapability == nil {
|
|
detectCapability = pulseupdates.DetectAutoUpdateCapability
|
|
}
|
|
capVal := detectCapability()
|
|
response.AutoUpdateCapability = &capVal
|
|
response = response.NormalizeCollections()
|
|
|
|
if err := utils.WriteJSONResponse(w, response); err != nil {
|
|
log.Error().Err(err).Msg("Failed to write system settings response")
|
|
}
|
|
}
|
|
|
|
// HandleGetTelemetryPreview returns the exact heartbeat payload Pulse would send
|
|
// using the current runtime telemetry configuration.
|
|
func (h *SystemSettingsHandler) HandleGetTelemetryPreview(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)
|
|
return
|
|
}
|
|
|
|
cfg := h.currentConfig()
|
|
if !ensureSettingsReadScope(cfg, w, r) {
|
|
return
|
|
}
|
|
|
|
if h.telemetryPreviewFunc == nil {
|
|
writeErrorResponse(w, http.StatusServiceUnavailable, "telemetry_unavailable", "Telemetry preview is unavailable", nil)
|
|
return
|
|
}
|
|
|
|
payload, err := h.telemetryPreviewFunc()
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("Failed to build telemetry preview")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "telemetry_preview_failed", "Failed to build telemetry preview", nil)
|
|
return
|
|
}
|
|
|
|
telemetryEnabled := ResolveEffectiveTelemetryEnabled(cfg, h.persistence)
|
|
if err := utils.WriteJSONResponse(w, TelemetryPreviewResponse{
|
|
Enabled: telemetryEnabled,
|
|
Payload: payload,
|
|
}); err != nil {
|
|
log.Error().Err(err).Msg("Failed to write telemetry preview response")
|
|
}
|
|
}
|
|
|
|
// HandleResetTelemetryID rotates the local telemetry install ID immediately and
|
|
// returns the refreshed preview payload.
|
|
func (h *SystemSettingsHandler) HandleResetTelemetryID(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)
|
|
return
|
|
}
|
|
|
|
if !h.ensureWriteAccess(w, r) {
|
|
return
|
|
}
|
|
|
|
if h.telemetryResetFunc == nil {
|
|
writeErrorResponse(w, http.StatusServiceUnavailable, "telemetry_unavailable", "Telemetry reset is unavailable", nil)
|
|
return
|
|
}
|
|
|
|
payload, err := h.telemetryResetFunc()
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("Failed to reset telemetry install ID")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "telemetry_reset_failed", "Failed to reset telemetry install ID", nil)
|
|
return
|
|
}
|
|
|
|
log.Info().Msg("Telemetry install ID reset")
|
|
|
|
telemetryEnabled := ResolveEffectiveTelemetryEnabled(h.currentConfig(), h.persistence)
|
|
if err := utils.WriteJSONResponse(w, TelemetryPreviewResponse{
|
|
Enabled: telemetryEnabled,
|
|
Payload: payload,
|
|
}); err != nil {
|
|
log.Error().Err(err).Msg("Failed to write telemetry reset response")
|
|
}
|
|
}
|
|
|
|
// HandleUpdateSystemSettings updates the system settings
|
|
func (h *SystemSettingsHandler) HandleUpdateSystemSettings(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)
|
|
return
|
|
}
|
|
|
|
h.updateMu.Lock()
|
|
updateMuHeld := true
|
|
releaseUpdateMu := func() {
|
|
if updateMuHeld {
|
|
updateMuHeld = false
|
|
h.updateMu.Unlock()
|
|
}
|
|
}
|
|
defer releaseUpdateMu()
|
|
|
|
if !h.ensureWriteAccess(w, r) {
|
|
return
|
|
}
|
|
|
|
// Load existing settings first to preserve fields not in the request.
|
|
// Fail closed on read/parse error so an ordinary settings save can never
|
|
// overwrite a corrupt or unreadable system.json with defaults.
|
|
existingSettings, err := h.persistence.LoadSystemSettings()
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("Failed to load existing settings")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "settings_load_failed", "Failed to load existing settings", nil)
|
|
return
|
|
}
|
|
if existingSettings == nil {
|
|
existingSettings = config.DefaultSystemSettings()
|
|
}
|
|
|
|
// Limit request body to 64KB to prevent memory exhaustion
|
|
r.Body = http.MaxBytesReader(w, r.Body, 64*1024)
|
|
bodyBytes, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", nil)
|
|
return
|
|
}
|
|
|
|
// Validate original JSON tokens before map/struct decoding so repeated
|
|
// identical spellings (e.g. duplicate telemetryEnabled) and conflicting
|
|
// case-fold aliases are rejected instead of silently collapsing.
|
|
strictFields, err := config.ValidateStrictSystemSettingsJSONObject(bodyBytes)
|
|
if err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", err.Error(), nil)
|
|
return
|
|
}
|
|
|
|
// Read the validated request body into a map to check which fields were provided
|
|
var rawRequest map[string]interface{}
|
|
if err := json.Unmarshal(bodyBytes, &rawRequest); err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", nil)
|
|
return
|
|
}
|
|
// Canonicalize top-level keys with strings.EqualFold against SystemSettings
|
|
// JSON tags so validation, persistence, and runtime updates agree with
|
|
// encoding/json for every case spelling (e.g. PBSPollingInterval).
|
|
rawRequest = canonicalizeSystemSettingsRawKeys(rawRequest)
|
|
|
|
// Decode original validated JSON bytes directly into updates struct
|
|
var updates config.SystemSettings
|
|
if err := json.Unmarshal(bodyBytes, &updates); err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", nil)
|
|
return
|
|
}
|
|
|
|
// Validate the settings
|
|
if err := validateSystemSettings(&updates, rawRequest); err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
|
|
return
|
|
}
|
|
|
|
// Use one case-insensitive field-presence decision across env-lock check,
|
|
// persistence, runtime mutation, and live toggle callback.
|
|
telemetryFieldPresent := false
|
|
for key := range strictFields {
|
|
if strings.EqualFold(key, "telemetryEnabled") {
|
|
telemetryFieldPresent = true
|
|
break
|
|
}
|
|
}
|
|
if !telemetryFieldPresent {
|
|
updates.TelemetryEnabled = nil
|
|
}
|
|
|
|
cfg := h.currentConfig()
|
|
// Snapshot all shared config fields once under config.Mu.RLock() and
|
|
// release before validation or persistence so concurrent reload/import
|
|
// writers never race with unlocked reads.
|
|
config.Mu.RLock()
|
|
telemetryEnvLocked := cfg.EnvOverrides["PULSE_TELEMETRY"] || cfg.EnvOverrides["telemetryEnabled"]
|
|
allowedOriginsLocked := cfg.EnvOverrides["ALLOWED_ORIGINS"] || cfg.EnvOverrides["allowedOrigins"]
|
|
currentAllowedOrigins := cfg.AllowedOrigins
|
|
guestDockerInventoryLocked := cfg.EnvOverrides["PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY"] ||
|
|
cfg.EnvOverrides["enableProxmoxGuestDockerInventory"]
|
|
currentUpdateChannel := cfg.UpdateChannel
|
|
prevTempEnabled := cfg.TemperatureMonitoringEnabled
|
|
currentPVEPollingInterval := cfg.PVEPollingInterval
|
|
prevDiscoveryEnabled := cfg.DiscoveryEnabled
|
|
config.Mu.RUnlock()
|
|
|
|
// Reject early if telemetryEnabled is locked by env var
|
|
if telemetryFieldPresent && telemetryEnvLocked {
|
|
writeErrorResponse(w, http.StatusConflict, "env_locked", "telemetryEnabled is locked by the PULSE_TELEMETRY environment variable", nil)
|
|
return
|
|
}
|
|
|
|
// A disabled deployment-owned field is still included by the settings form.
|
|
// Accept an unchanged value without copying the override into system.json;
|
|
// reject attempts to change it, before persisting any part of the patch.
|
|
_, allowedOriginsUpdated := rawRequest["allowedOrigins"]
|
|
if allowedOriginsUpdated && allowedOriginsLocked && updates.AllowedOrigins != currentAllowedOrigins {
|
|
writeErrorResponse(w, http.StatusConflict, "env_locked", "allowedOrigins is locked by the ALLOWED_ORIGINS environment variable", nil)
|
|
return
|
|
}
|
|
_, autoUpdateUpdated := rawRequest["autoUpdateEnabled"]
|
|
autoUpdateEnvLocked := config.IsAutoUpdateDisabledByEnv() || h.config.EnvOverrides["autoUpdateEnabled"] || h.config.EnvOverrides["PULSE_DISABLE_AUTO_UPDATE"]
|
|
if autoUpdateUpdated && autoUpdateEnvLocked && updates.AutoUpdateEnabled {
|
|
writeErrorResponse(w, http.StatusConflict, "env_locked", "autoUpdateEnabled is locked by the PULSE_DISABLE_AUTO_UPDATE environment variable", nil)
|
|
return
|
|
}
|
|
|
|
// Start with existing settings
|
|
settings := *existingSettings
|
|
discoveryConfigUpdated := false
|
|
tempToggleRequested := false
|
|
pveIntervalChanged := false
|
|
|
|
// Only update fields that were provided in the request
|
|
if _, ok := rawRequest["pvePollingInterval"]; ok {
|
|
settings.PVEPollingInterval = updates.PVEPollingInterval
|
|
}
|
|
if _, ok := rawRequest["pbsPollingInterval"]; ok {
|
|
settings.PBSPollingInterval = updates.PBSPollingInterval
|
|
}
|
|
if _, ok := rawRequest["pmgPollingInterval"]; ok {
|
|
settings.PMGPollingInterval = updates.PMGPollingInterval
|
|
}
|
|
if _, ok := rawRequest["backupPollingInterval"]; ok {
|
|
settings.BackupPollingInterval = updates.BackupPollingInterval
|
|
}
|
|
if allowedOriginsUpdated && !allowedOriginsLocked {
|
|
settings.AllowedOrigins = updates.AllowedOrigins
|
|
}
|
|
if _, ok := rawRequest["connectionTimeout"]; ok {
|
|
settings.ConnectionTimeout = updates.ConnectionTimeout
|
|
}
|
|
if updates.UpdateChannel != "" {
|
|
settings.UpdateChannel = updates.UpdateChannel
|
|
}
|
|
if updates.Theme != "" {
|
|
settings.Theme = updates.Theme
|
|
}
|
|
if updates.DiscoverySubnet != "" {
|
|
settings.DiscoverySubnet = updates.DiscoverySubnet
|
|
}
|
|
if cfgMap, ok := discoveryConfigMap(rawRequest); ok && cfgMap != nil {
|
|
current := config.CloneDiscoveryConfig(settings.DiscoveryConfig)
|
|
normalizedDiscoveryConfig, err := applyDiscoveryConfigOverrides(current, cfgMap)
|
|
if err != nil {
|
|
writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
|
|
return
|
|
}
|
|
settings.DiscoveryConfig = normalizedDiscoveryConfig
|
|
discoveryConfigUpdated = true
|
|
}
|
|
// Allow clearing of AllowedEmbedOrigins by setting to empty string
|
|
if _, ok := rawRequest["allowedEmbedOrigins"]; ok {
|
|
settings.AllowedEmbedOrigins = updates.AllowedEmbedOrigins
|
|
}
|
|
// Allow configuring webhook private CIDR allowlist
|
|
if _, ok := rawRequest["webhookAllowedPrivateCIDRs"]; ok {
|
|
settings.WebhookAllowedPrivateCIDRs = updates.WebhookAllowedPrivateCIDRs
|
|
}
|
|
// Allow configuring public URL for notifications (used in email alerts)
|
|
if _, ok := rawRequest["publicURL"]; ok {
|
|
settings.PublicURL = updates.PublicURL
|
|
}
|
|
// Allow per-runtime report branding overrides. The reporting layer still
|
|
// enforces the white_label entitlement before rendering these values.
|
|
if _, ok := rawRequest["reportBranding"]; ok {
|
|
settings.ReportBranding = updates.ReportBranding
|
|
}
|
|
|
|
// Boolean fields need special handling since false is a valid value
|
|
if _, ok := rawRequest["autoUpdateEnabled"]; ok {
|
|
settings.AutoUpdateEnabled = updates.AutoUpdateEnabled
|
|
}
|
|
if _, ok := rawRequest["autoUpdatePreviewConsent"]; ok {
|
|
settings.AutoUpdatePreviewConsent = updates.AutoUpdatePreviewConsent
|
|
}
|
|
if _, ok := rawRequest["autoUpdateProConsent"]; ok {
|
|
settings.AutoUpdateProConsent = updates.AutoUpdateProConsent
|
|
}
|
|
if _, ok := rawRequest["discoveryEnabled"]; ok {
|
|
settings.DiscoveryEnabled = updates.DiscoveryEnabled
|
|
}
|
|
if _, ok := rawRequest["allowEmbedding"]; ok {
|
|
settings.AllowEmbedding = updates.AllowEmbedding
|
|
}
|
|
if _, ok := rawRequest["hideLocalLogin"]; ok {
|
|
settings.HideLocalLogin = updates.HideLocalLogin
|
|
}
|
|
if _, ok := rawRequest["backupPollingEnabled"]; ok {
|
|
settings.BackupPollingEnabled = updates.BackupPollingEnabled
|
|
}
|
|
if _, ok := rawRequest["temperatureMonitoringEnabled"]; ok {
|
|
settings.TemperatureMonitoringEnabled = updates.TemperatureMonitoringEnabled
|
|
tempToggleRequested = true
|
|
}
|
|
if _, ok := rawRequest["disableDockerUpdateActions"]; ok {
|
|
settings.DisableDockerUpdateActions = updates.DisableDockerUpdateActions
|
|
}
|
|
guestDockerInventoryToggleRequested := false
|
|
if _, ok := rawRequest["enableProxmoxGuestDockerInventory"]; ok {
|
|
// The environment opt-in is a deploy-time decision; a locked value
|
|
// must not be changeable through the API at all.
|
|
if guestDockerInventoryLocked {
|
|
writeErrorResponse(w, http.StatusBadRequest, "env_override",
|
|
"Proxmox guest Docker inventory is locked by the PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY environment variable", nil)
|
|
return
|
|
}
|
|
settings.EnableProxmoxGuestDockerInventory = updates.EnableProxmoxGuestDockerInventory
|
|
guestDockerInventoryToggleRequested = true
|
|
}
|
|
if _, ok := rawRequest["reduceProUpsellNoise"]; ok {
|
|
settings.ReduceProUpsellNoise = updates.ReduceProUpsellNoise
|
|
}
|
|
if telemetryFieldPresent && updates.TelemetryEnabled != nil {
|
|
settings.TelemetryEnabled = updates.TelemetryEnabled
|
|
// Note: h.config.TelemetryEnabled is updated after successful persistence below
|
|
}
|
|
if _, ok := rawRequest["fullWidthMode"]; ok {
|
|
settings.FullWidthMode = updates.FullWidthMode
|
|
}
|
|
settings.UpdateChannel = config.EffectiveUpdateChannel(settings.UpdateChannel, currentUpdateChannel)
|
|
proEdition := edition.IsPro()
|
|
if h.isProEditionFunc != nil {
|
|
proEdition = h.isProEditionFunc()
|
|
}
|
|
settings.AutoUpdateProConsent = config.EffectiveAutoUpdateProConsent(settings.AutoUpdateEnabled, proEdition, settings.AutoUpdateProConsent)
|
|
settings.AutoUpdatePreviewConsent = config.EffectiveAutoUpdatePreviewConsent(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent)
|
|
if proEdition && !settings.AutoUpdateProConsent {
|
|
settings.AutoUpdatePreviewConsent = false
|
|
}
|
|
settings.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabledForEdition(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent, proEdition, settings.AutoUpdateProConsent)
|
|
|
|
// Pre-save validation (may return errors before anything is persisted)
|
|
if settings.Theme != "" && settings.Theme != "light" && settings.Theme != "dark" {
|
|
writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid theme value. Must be 'light', 'dark', or empty", nil)
|
|
return
|
|
}
|
|
// Validate CIDRs before persistence (parse only — do NOT mutate runtime yet).
|
|
var parsedCIDRNets []*net.IPNet
|
|
cidrUpdateRequested := false
|
|
if _, ok := rawRequest["webhookAllowedPrivateCIDRs"]; ok {
|
|
cidrUpdateRequested = true
|
|
var err error
|
|
parsedCIDRNets, err = notifications.ParseAllowedPrivateCIDRs(settings.WebhookAllowedPrivateCIDRs)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("Failed to validate webhook allowed private CIDRs")
|
|
writeErrorResponse(w, http.StatusBadRequest, "validation_error", fmt.Sprintf("Invalid webhook allowed private CIDRs: %v", err), nil)
|
|
return
|
|
}
|
|
}
|
|
|
|
// Detect PVE interval change (compare before mutation, apply after save)
|
|
if _, ok := rawRequest["pvePollingInterval"]; ok && settings.PVEPollingInterval > 0 {
|
|
newInterval := time.Duration(settings.PVEPollingInterval) * time.Second
|
|
if newInterval < 10*time.Second {
|
|
newInterval = 10 * time.Second
|
|
}
|
|
if currentPVEPollingInterval != newInterval {
|
|
pveIntervalChanged = true
|
|
}
|
|
}
|
|
|
|
// ---- Persist FIRST atomically, then apply to in-memory config ----
|
|
// Re-read env overrides briefly under config.Mu.RLock() and release before
|
|
// persistence I/O so a stalled config volume never blocks checkAuth across
|
|
// tenants, and never acquire config.Mu inside the persistence callback (no
|
|
// lock-order inversion with monitor reload or config import). Apply ONLY
|
|
// the requested patch fields directly onto `latest` inside
|
|
// UpdateSystemSettings so a concurrent backup import is never overwritten.
|
|
var (
|
|
saveErr error
|
|
persistedSettings config.SystemSettings
|
|
telemetryCommitGen uint64
|
|
telemetryEnvLockedNow bool
|
|
allowedOriginsLockedNow bool
|
|
guestDockerInventoryLockedNow bool
|
|
)
|
|
cfgMapForPatch, hasDiscoveryCfgPatch := discoveryConfigMap(rawRequest)
|
|
config.Mu.RLock()
|
|
cfg = h.currentConfig()
|
|
allowedOriginsLocked = cfg.EnvOverrides["ALLOWED_ORIGINS"] || cfg.EnvOverrides["allowedOrigins"]
|
|
latestUpdateChannel := cfg.UpdateChannel
|
|
if telemetryFieldPresent && (cfg.EnvOverrides["PULSE_TELEMETRY"] || cfg.EnvOverrides["telemetryEnabled"]) {
|
|
telemetryEnvLockedNow = true
|
|
} else if allowedOriginsUpdated && allowedOriginsLocked && updates.AllowedOrigins != cfg.AllowedOrigins {
|
|
allowedOriginsLockedNow = true
|
|
} else if guestDockerInventoryToggleRequested && (cfg.EnvOverrides["PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY"] || cfg.EnvOverrides["enableProxmoxGuestDockerInventory"]) {
|
|
guestDockerInventoryLockedNow = true
|
|
}
|
|
config.Mu.RUnlock()
|
|
|
|
if !telemetryEnvLockedNow && !allowedOriginsLockedNow && !guestDockerInventoryLockedNow {
|
|
clearConsentFence := telemetryFieldPresent && updates.TelemetryEnabled != nil
|
|
persistedSettings, telemetryCommitGen, saveErr = h.persistence.UpdateSystemSettingsWithConsentGenerationOptions(func(latest *config.SystemSettings) error {
|
|
if _, ok := rawRequest["pvePollingInterval"]; ok {
|
|
latest.PVEPollingInterval = updates.PVEPollingInterval
|
|
}
|
|
if _, ok := rawRequest["pbsPollingInterval"]; ok {
|
|
latest.PBSPollingInterval = updates.PBSPollingInterval
|
|
}
|
|
if _, ok := rawRequest["pmgPollingInterval"]; ok {
|
|
latest.PMGPollingInterval = updates.PMGPollingInterval
|
|
}
|
|
if _, ok := rawRequest["backupPollingInterval"]; ok {
|
|
latest.BackupPollingInterval = updates.BackupPollingInterval
|
|
}
|
|
if allowedOriginsUpdated && !allowedOriginsLocked {
|
|
latest.AllowedOrigins = updates.AllowedOrigins
|
|
}
|
|
if _, ok := rawRequest["connectionTimeout"]; ok {
|
|
latest.ConnectionTimeout = updates.ConnectionTimeout
|
|
}
|
|
if updates.UpdateChannel != "" {
|
|
latest.UpdateChannel = updates.UpdateChannel
|
|
}
|
|
if updates.Theme != "" {
|
|
latest.Theme = updates.Theme
|
|
}
|
|
if updates.DiscoverySubnet != "" {
|
|
latest.DiscoverySubnet = updates.DiscoverySubnet
|
|
}
|
|
if hasDiscoveryCfgPatch && cfgMapForPatch != nil {
|
|
curDisc := config.CloneDiscoveryConfig(latest.DiscoveryConfig)
|
|
normDisc, err := applyDiscoveryConfigOverrides(curDisc, cfgMapForPatch)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
latest.DiscoveryConfig = normDisc
|
|
}
|
|
if _, ok := rawRequest["allowedEmbedOrigins"]; ok {
|
|
latest.AllowedEmbedOrigins = updates.AllowedEmbedOrigins
|
|
}
|
|
if _, ok := rawRequest["webhookAllowedPrivateCIDRs"]; ok {
|
|
latest.WebhookAllowedPrivateCIDRs = updates.WebhookAllowedPrivateCIDRs
|
|
}
|
|
if _, ok := rawRequest["publicURL"]; ok {
|
|
latest.PublicURL = updates.PublicURL
|
|
}
|
|
if _, ok := rawRequest["reportBranding"]; ok {
|
|
latest.ReportBranding = updates.ReportBranding
|
|
}
|
|
if _, ok := rawRequest["autoUpdateEnabled"]; ok {
|
|
latest.AutoUpdateEnabled = updates.AutoUpdateEnabled
|
|
}
|
|
if _, ok := rawRequest["autoUpdatePreviewConsent"]; ok {
|
|
latest.AutoUpdatePreviewConsent = updates.AutoUpdatePreviewConsent
|
|
}
|
|
if _, ok := rawRequest["autoUpdateProConsent"]; ok {
|
|
latest.AutoUpdateProConsent = updates.AutoUpdateProConsent
|
|
}
|
|
if _, ok := rawRequest["discoveryEnabled"]; ok {
|
|
latest.DiscoveryEnabled = updates.DiscoveryEnabled
|
|
}
|
|
if _, ok := rawRequest["allowEmbedding"]; ok {
|
|
latest.AllowEmbedding = updates.AllowEmbedding
|
|
}
|
|
if _, ok := rawRequest["hideLocalLogin"]; ok {
|
|
latest.HideLocalLogin = updates.HideLocalLogin
|
|
}
|
|
if _, ok := rawRequest["backupPollingEnabled"]; ok {
|
|
latest.BackupPollingEnabled = updates.BackupPollingEnabled
|
|
}
|
|
if _, ok := rawRequest["temperatureMonitoringEnabled"]; ok {
|
|
latest.TemperatureMonitoringEnabled = updates.TemperatureMonitoringEnabled
|
|
}
|
|
if _, ok := rawRequest["disableDockerUpdateActions"]; ok {
|
|
latest.DisableDockerUpdateActions = updates.DisableDockerUpdateActions
|
|
}
|
|
if guestDockerInventoryToggleRequested {
|
|
latest.EnableProxmoxGuestDockerInventory = updates.EnableProxmoxGuestDockerInventory
|
|
}
|
|
if _, ok := rawRequest["reduceProUpsellNoise"]; ok {
|
|
latest.ReduceProUpsellNoise = updates.ReduceProUpsellNoise
|
|
}
|
|
if telemetryFieldPresent && updates.TelemetryEnabled != nil {
|
|
latest.TelemetryEnabled = updates.TelemetryEnabled
|
|
}
|
|
if _, ok := rawRequest["fullWidthMode"]; ok {
|
|
latest.FullWidthMode = updates.FullWidthMode
|
|
}
|
|
latest.UpdateChannel = config.EffectiveUpdateChannel(latest.UpdateChannel, latestUpdateChannel)
|
|
latest.AutoUpdateProConsent = config.EffectiveAutoUpdateProConsent(latest.AutoUpdateEnabled, proEdition, latest.AutoUpdateProConsent)
|
|
latest.AutoUpdatePreviewConsent = config.EffectiveAutoUpdatePreviewConsent(latest.UpdateChannel, latest.AutoUpdateEnabled, latest.AutoUpdatePreviewConsent)
|
|
if proEdition && !latest.AutoUpdateProConsent {
|
|
latest.AutoUpdatePreviewConsent = false
|
|
}
|
|
latest.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabledForEdition(latest.UpdateChannel, latest.AutoUpdateEnabled, latest.AutoUpdatePreviewConsent, proEdition, latest.AutoUpdateProConsent)
|
|
return nil
|
|
}, clearConsentFence)
|
|
}
|
|
|
|
if telemetryEnvLockedNow {
|
|
writeErrorResponse(w, http.StatusConflict, "env_locked", "telemetryEnabled is locked by the PULSE_TELEMETRY environment variable", nil)
|
|
return
|
|
}
|
|
if allowedOriginsLockedNow {
|
|
writeErrorResponse(w, http.StatusConflict, "env_locked", "allowedOrigins is locked by the ALLOWED_ORIGINS environment variable", nil)
|
|
return
|
|
}
|
|
if guestDockerInventoryLockedNow {
|
|
writeErrorResponse(w, http.StatusBadRequest, "env_override",
|
|
"Proxmox guest Docker inventory is locked by the PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY environment variable", nil)
|
|
return
|
|
}
|
|
if saveErr != nil {
|
|
log.Error().Err(saveErr).Msg("Failed to save system settings")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "save_failed", "Failed to save settings", nil)
|
|
return
|
|
}
|
|
// Use the freshly merged persisted settings so runtime publication reflects
|
|
// any concurrent import/update fields preserved in `latest`.
|
|
settings = persistedSettings
|
|
|
|
// ---- Apply config and capture tenant runtime settings together ----
|
|
// Disk has committed. Publish all shared config fields under config.Mu so
|
|
// concurrent GET /api/system/settings, /api/runtime/display, and reload
|
|
// readers never race with writes, and re-check the telemetry env lock and
|
|
// committed consent generation before mutating cfg.TelemetryEnabled so a
|
|
// newer concurrent import cannot be overwritten by an older settings POST.
|
|
guestDockerInventoryChanged, telemetryChanged := false, false
|
|
var telemetryPublishedGen uint64
|
|
appliedDiscoverySubnet := ""
|
|
var appliedBackupPollingInterval time.Duration
|
|
h.updateInstanceConfig(func() {
|
|
config.Mu.Lock()
|
|
defer config.Mu.Unlock()
|
|
cfg := h.currentConfig()
|
|
|
|
if _, ok := rawRequest["pvePollingInterval"]; ok && settings.PVEPollingInterval > 0 {
|
|
newInterval := time.Duration(settings.PVEPollingInterval) * time.Second
|
|
if newInterval < 10*time.Second {
|
|
newInterval = 10 * time.Second
|
|
}
|
|
cfg.PVEPollingInterval = newInterval
|
|
}
|
|
if allowedOriginsUpdated && !cfg.EnvOverrides["ALLOWED_ORIGINS"] && !cfg.EnvOverrides["allowedOrigins"] {
|
|
cfg.AllowedOrigins = settings.AllowedOrigins
|
|
config.AdvanceAllowedOriginsRevision()
|
|
}
|
|
if _, ok := rawRequest["connectionTimeout"]; ok && settings.ConnectionTimeout > 0 {
|
|
cfg.ConnectionTimeout = time.Duration(settings.ConnectionTimeout) * time.Second
|
|
}
|
|
if _, ok := rawRequest["pbsPollingInterval"]; ok && settings.PBSPollingInterval > 0 {
|
|
cfg.PBSPollingInterval = time.Duration(settings.PBSPollingInterval) * time.Second
|
|
}
|
|
if _, ok := rawRequest["pmgPollingInterval"]; ok && settings.PMGPollingInterval > 0 {
|
|
cfg.PMGPollingInterval = time.Duration(settings.PMGPollingInterval) * time.Second
|
|
}
|
|
if _, ok := rawRequest["backupPollingInterval"]; ok {
|
|
if settings.BackupPollingInterval <= 0 {
|
|
cfg.BackupPollingInterval = 0
|
|
} else {
|
|
cfg.BackupPollingInterval = time.Duration(settings.BackupPollingInterval) * time.Second
|
|
}
|
|
}
|
|
if _, ok := rawRequest["backupPollingEnabled"]; ok && settings.BackupPollingEnabled != nil {
|
|
cfg.EnableBackupPolling = *settings.BackupPollingEnabled
|
|
}
|
|
if updates.UpdateChannel != "" {
|
|
cfg.UpdateChannel = settings.UpdateChannel
|
|
}
|
|
_, autoUpdateRequested := rawRequest["autoUpdateEnabled"]
|
|
_, previewConsentRequested := rawRequest["autoUpdatePreviewConsent"]
|
|
_, proConsentRequested := rawRequest["autoUpdateProConsent"]
|
|
if autoUpdateRequested || previewConsentRequested || proConsentRequested || updates.UpdateChannel != "" {
|
|
cfg.AutoUpdateProConsent = settings.AutoUpdateProConsent
|
|
cfg.AutoUpdatePreviewConsent = settings.AutoUpdatePreviewConsent
|
|
cfg.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabledForEdition(cfg.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent, proEdition, settings.AutoUpdateProConsent)
|
|
}
|
|
if _, ok := rawRequest["discoveryEnabled"]; ok {
|
|
cfg.DiscoveryEnabled = settings.DiscoveryEnabled
|
|
}
|
|
if updates.DiscoverySubnet != "" {
|
|
cfg.DiscoverySubnet = settings.DiscoverySubnet
|
|
}
|
|
if discoveryConfigUpdated {
|
|
cfg.Discovery = config.CloneDiscoveryConfig(settings.DiscoveryConfig)
|
|
}
|
|
if tempToggleRequested {
|
|
cfg.TemperatureMonitoringEnabled = settings.TemperatureMonitoringEnabled
|
|
}
|
|
if _, ok := rawRequest["disableDockerUpdateActions"]; ok {
|
|
cfg.DisableDockerUpdateActions = settings.DisableDockerUpdateActions
|
|
}
|
|
if guestDockerInventoryToggleRequested &&
|
|
!cfg.EnvOverrides["PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY"] &&
|
|
!cfg.EnvOverrides["enableProxmoxGuestDockerInventory"] &&
|
|
cfg.EnableProxmoxGuestDockerInventory != settings.EnableProxmoxGuestDockerInventory {
|
|
cfg.EnableProxmoxGuestDockerInventory = settings.EnableProxmoxGuestDockerInventory
|
|
guestDockerInventoryChanged = true
|
|
}
|
|
// A null/omitted preference is not a transition, even if disk and runtime
|
|
// differ. Re-verify EnvOverrides and the committed consent generation
|
|
// under config.Mu so a concurrent reload or newer backup import cannot
|
|
// be overwritten by an earlier settings POST.
|
|
if telemetryFieldPresent && updates.TelemetryEnabled != nil &&
|
|
!cfg.EnvOverrides["PULSE_TELEMETRY"] && !cfg.EnvOverrides["telemetryEnabled"] &&
|
|
config.TelemetryConsentGeneration() == telemetryCommitGen {
|
|
if cfg.TelemetryEnabled != *updates.TelemetryEnabled {
|
|
cfg.TelemetryEnabled = *updates.TelemetryEnabled
|
|
telemetryChanged = true
|
|
AdvanceTelemetryConsentGeneration()
|
|
telemetryPublishedGen = config.TelemetryConsentGeneration()
|
|
}
|
|
}
|
|
if _, ok := rawRequest["publicURL"]; ok {
|
|
cfg.PublicURL = settings.PublicURL
|
|
// Operator input, even empty, supersedes any auto-detected guess.
|
|
cfg.PublicURLAutoDetected = false
|
|
}
|
|
appliedDiscoverySubnet = cfg.DiscoverySubnet
|
|
appliedBackupPollingInterval = cfg.BackupPollingInterval
|
|
})
|
|
if guestDockerInventoryChanged {
|
|
if h.guestDockerInventoryToggleFunc != nil {
|
|
h.guestDockerInventoryToggleFunc()
|
|
}
|
|
log.Info().Bool("enabled", settings.EnableProxmoxGuestDockerInventory).
|
|
Msg("Proxmox guest Docker inventory opt-in changed via settings")
|
|
}
|
|
|
|
// ---- Side effects (discovery, temperature, notifications) ----
|
|
_, discoveryToggleRequested := rawRequest["discoveryEnabled"]
|
|
if h.getMonitor(r.Context()) != nil {
|
|
if discoveryToggleRequested && settings.DiscoveryEnabled && !prevDiscoveryEnabled {
|
|
subnet := appliedDiscoverySubnet
|
|
if subnet == "" {
|
|
subnet = "auto"
|
|
}
|
|
h.getMonitor(r.Context()).StartDiscoveryService(context.Background(), h.wsHub, subnet)
|
|
log.Info().Msg("Discovery service started via settings update")
|
|
} else if discoveryToggleRequested && !settings.DiscoveryEnabled && prevDiscoveryEnabled {
|
|
h.getMonitor(r.Context()).StopDiscoveryService()
|
|
log.Info().Msg("Discovery service stopped via settings update")
|
|
} else if updates.DiscoverySubnet != "" && settings.DiscoveryEnabled {
|
|
if svc := h.getMonitor(r.Context()).GetDiscoveryService(); svc != nil {
|
|
svc.SetSubnet(settings.DiscoverySubnet)
|
|
}
|
|
}
|
|
if discoveryConfigUpdated && settings.DiscoveryEnabled {
|
|
if svc := h.getMonitor(r.Context()).GetDiscoveryService(); svc != nil {
|
|
log.Info().Msg("Discovery configuration changed; triggering refresh")
|
|
svc.ForceRefresh()
|
|
}
|
|
}
|
|
}
|
|
if tempToggleRequested && h.getMonitor(r.Context()) != nil {
|
|
if settings.TemperatureMonitoringEnabled && !prevTempEnabled {
|
|
h.getMonitor(r.Context()).EnableTemperatureMonitoring()
|
|
} else if !settings.TemperatureMonitoringEnabled && prevTempEnabled {
|
|
h.getMonitor(r.Context()).DisableTemperatureMonitoring()
|
|
}
|
|
}
|
|
// Webhook security allowlist and public URL are instance-wide settings:
|
|
// apply them to every live tenant monitor's notification manager, not
|
|
// just the org the admin happened to have selected.
|
|
if cidrUpdateRequested {
|
|
h.forEachNotificationManager(r, func(nm *notifications.NotificationManager) {
|
|
nm.ApplyAllowedPrivateCIDRs(settings.WebhookAllowedPrivateCIDRs, parsedCIDRNets)
|
|
})
|
|
}
|
|
if _, ok := rawRequest["publicURL"]; ok {
|
|
h.forEachNotificationManager(r, func(nm *notifications.NotificationManager) {
|
|
nm.SetPublicURL(settings.PublicURL)
|
|
})
|
|
log.Info().Str("publicURL", settings.PublicURL).Msg("Updated notification public URL from settings")
|
|
}
|
|
// Polling cadence settings are read every cycle by each tenant monitor
|
|
// from its own detached config copy, so push them into the live monitors
|
|
// directly; only pvePollingInterval triggers a full monitor reload.
|
|
if _, ok := rawRequest["backupPollingEnabled"]; ok && settings.BackupPollingEnabled != nil {
|
|
enabled := *settings.BackupPollingEnabled
|
|
h.forEachTenantMonitor(r, func(m SystemSettingsMonitor) {
|
|
m.SetBackupPollingEnabled(enabled)
|
|
})
|
|
}
|
|
if _, ok := rawRequest["backupPollingInterval"]; ok {
|
|
interval := appliedBackupPollingInterval
|
|
h.forEachTenantMonitor(r, func(m SystemSettingsMonitor) {
|
|
m.SetBackupPollingInterval(interval)
|
|
})
|
|
}
|
|
if _, ok := rawRequest["pbsPollingInterval"]; ok && settings.PBSPollingInterval > 0 {
|
|
interval := time.Duration(settings.PBSPollingInterval) * time.Second
|
|
h.forEachTenantMonitor(r, func(m SystemSettingsMonitor) {
|
|
m.SetPBSPollingInterval(interval)
|
|
})
|
|
}
|
|
if _, ok := rawRequest["pmgPollingInterval"]; ok && settings.PMGPollingInterval > 0 {
|
|
interval := time.Duration(settings.PMGPollingInterval) * time.Second
|
|
h.forEachTenantMonitor(r, func(m SystemSettingsMonitor) {
|
|
m.SetPMGPollingInterval(interval)
|
|
})
|
|
}
|
|
|
|
// A settings save is an operator touchpoint that often follows repairing
|
|
// SSH access; clear the temperature SSH backoff windows so the next poll
|
|
// cycle retries instead of waiting one out (#1638).
|
|
h.forEachTenantMonitor(r, func(m SystemSettingsMonitor) {
|
|
m.ResetSSHFailureBackoff()
|
|
})
|
|
|
|
// Assign a monotonic commit sequence for theme broadcasts while updateMu
|
|
// is still held so an earlier POST that pauses in telemetry or reload
|
|
// callbacks cannot broadcast an obsolete theme after a newer save.
|
|
var themeCommitSeq uint64
|
|
if settings.Theme != "" {
|
|
h.themeBroadcastMu.Lock()
|
|
h.latestThemeSeq++
|
|
themeCommitSeq = h.latestThemeSeq
|
|
h.themeBroadcastMu.Unlock()
|
|
}
|
|
|
|
// Release updateMu once persistence, runtime config publication, and live
|
|
// monitor/notification updates have all been applied in order, BEFORE
|
|
// running telemetryToggleFunc (which may block on install-ID storage on
|
|
// opt-in) or reload hooks so a stalled opt-in never blocks a later opt-out.
|
|
releaseUpdateMu()
|
|
|
|
if telemetryChanged {
|
|
if h.telemetryToggleGenFunc != nil {
|
|
h.telemetryToggleGenFunc(*updates.TelemetryEnabled, telemetryPublishedGen)
|
|
} else if h.telemetryToggleFunc != nil && config.TelemetryConsentGeneration() == telemetryPublishedGen {
|
|
h.telemetryToggleFunc(*updates.TelemetryEnabled)
|
|
}
|
|
}
|
|
|
|
// Reload cached system settings after successful save
|
|
if h.reloadSystemSettingsFunc != nil {
|
|
h.reloadSystemSettingsFunc()
|
|
}
|
|
|
|
if pveIntervalChanged && h.reloadMonitorFunc != nil {
|
|
if err := h.reloadMonitorFunc(); err != nil {
|
|
log.Error().Err(err).Msg("Failed to reload monitor after PVE polling interval change")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "reload_failed", "Configuration saved but failed to reload monitor", nil)
|
|
return
|
|
}
|
|
}
|
|
|
|
log.Info().Msg("System settings updated")
|
|
|
|
// Broadcast theme change to all connected clients only if no newer save
|
|
// has already committed a replacement theme.
|
|
if themeCommitSeq != 0 && h.wsHub != nil {
|
|
h.themeBroadcastMu.Lock()
|
|
if themeCommitSeq == h.latestThemeSeq {
|
|
h.wsHub.BroadcastMessage(websocket.Message{
|
|
Type: "settingsUpdate",
|
|
Data: map[string]interface{}{
|
|
"theme": settings.Theme,
|
|
},
|
|
})
|
|
log.Debug().Str("theme", settings.Theme).Msg("Broadcasting theme change to WebSocket clients")
|
|
}
|
|
h.themeBroadcastMu.Unlock()
|
|
}
|
|
|
|
if err := utils.WriteJSONResponse(w, map[string]bool{"success": true}); err != nil {
|
|
log.Error().Err(err).Msg("Failed to write system settings update response")
|
|
}
|
|
}
|
|
|
|
// sshConfigJumpHop matches one [user@]host[:port] hop of a ProxyJump value.
|
|
const sshConfigJumpHop = `(?:[A-Za-z0-9_][A-Za-z0-9._-]*@)?[A-Za-z0-9][A-Za-z0-9._-]*(?::[0-9]{1,5})?`
|
|
|
|
// sshConfigDirectiveValues lists the only directives Pulse needs for ProxyJump
|
|
// and the form each of their arguments must take. Values are limited to plain
|
|
// names, addresses and paths: OpenSSH builds the jump command from ProxyJump
|
|
// (and from Hostname, through %h) and hands it to a shell, so shell syntax,
|
|
// quoting or a leading '-' in a value is command execution on the Pulse host.
|
|
var sshConfigDirectiveValues = map[string]*regexp.Regexp{
|
|
"host": regexp.MustCompile(`^!?[A-Za-z0-9*?:][A-Za-z0-9._:*?-]*$`),
|
|
"hostname": regexp.MustCompile(`^[A-Za-z0-9:][A-Za-z0-9._:-]*$`),
|
|
"proxyjump": regexp.MustCompile(`^` + sshConfigJumpHop + `(?:,` + sshConfigJumpHop + `)*$`),
|
|
"user": regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]*$`),
|
|
"identityfile": regexp.MustCompile(`^[A-Za-z0-9._~/][A-Za-z0-9._~/-]*$`),
|
|
"stricthostkeychecking": regexp.MustCompile(`^(?i:yes|no|accept-new|ask|off)$`),
|
|
}
|
|
|
|
// validSSHConfigArguments reports whether args are acceptable arguments for an
|
|
// allowlisted directive. Host takes one or more patterns; every other
|
|
// directive takes exactly one value.
|
|
func validSSHConfigArguments(directive string, args []string) bool {
|
|
valuePattern := sshConfigDirectiveValues[directive]
|
|
if valuePattern == nil || len(args) == 0 || (directive != "host" && len(args) != 1) {
|
|
return false
|
|
}
|
|
for _, arg := range args {
|
|
if !valuePattern.MatchString(arg) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// HandleSSHConfig writes SSH configuration for Pulse user
|
|
func (h *SystemSettingsHandler) HandleSSHConfig(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)
|
|
return
|
|
}
|
|
|
|
// Limit request body to 32KB to prevent memory exhaustion
|
|
r.Body = http.MaxBytesReader(w, r.Body, 32*1024)
|
|
defer r.Body.Close()
|
|
|
|
// Read SSH config content from request body
|
|
sshConfig, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
// Check if body was too large
|
|
var maxBytesErr *http.MaxBytesError
|
|
if errors.As(err, &maxBytesErr) {
|
|
log.Warn().Msg("SSH config request body too large")
|
|
writeErrorResponse(w, http.StatusRequestEntityTooLarge, "request_too_large", "Request body too large", nil)
|
|
return
|
|
}
|
|
log.Error().Err(err).Msg("Failed to read SSH config from request")
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Failed to read request body", nil)
|
|
return
|
|
}
|
|
|
|
// Basic validation: ensure it looks like SSH config
|
|
configStr := string(sshConfig)
|
|
if len(configStr) == 0 {
|
|
log.Error().Msg("Empty SSH config received")
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Empty SSH config", nil)
|
|
return
|
|
}
|
|
|
|
// Security: Use allowlist-based validation (safer than blocklist)
|
|
// Only permit the specific directives Pulse needs for ProxyJump, and only
|
|
// with values that cannot reach a shell (see sshConfigDirectiveValues).
|
|
// Parse and validate each line
|
|
scanner := bufio.NewScanner(strings.NewReader(configStr))
|
|
lineNum := 0
|
|
for scanner.Scan() {
|
|
lineNum++
|
|
|
|
// Split into words on blanks only, as OpenSSH does, so the words
|
|
// checked here are the words ssh reads back from the written file.
|
|
fields := strings.FieldsFunc(scanner.Text(), func(r rune) bool { return r == ' ' || r == '\t' })
|
|
|
|
// Skip empty lines and comment lines
|
|
if len(fields) == 0 || strings.HasPrefix(fields[0], "#") {
|
|
continue
|
|
}
|
|
|
|
// Extract directive (first word)
|
|
directive := strings.ToLower(fields[0])
|
|
if _, allowed := sshConfigDirectiveValues[directive]; !allowed {
|
|
log.Warn().
|
|
Str("directive", fields[0]).
|
|
Int("line", lineNum).
|
|
Msg("Rejected SSH config with forbidden directive")
|
|
writeErrorResponse(w, http.StatusBadRequest, "validation_error", fmt.Sprintf("SSH config contains forbidden directive: %s", fields[0]), nil)
|
|
return
|
|
}
|
|
|
|
// Strip a trailing comment. Only a word that starts with '#' begins
|
|
// one; OpenSSH keeps a '#' inside a word as part of the value.
|
|
args := fields[1:]
|
|
for i, arg := range args {
|
|
if strings.HasPrefix(arg, "#") {
|
|
args = args[:i]
|
|
break
|
|
}
|
|
}
|
|
|
|
if !validSSHConfigArguments(directive, args) {
|
|
log.Warn().
|
|
Str("directive", fields[0]).
|
|
Int("line", lineNum).
|
|
Msg("Rejected SSH config with invalid directive value")
|
|
writeErrorResponse(w, http.StatusBadRequest, "validation_error", fmt.Sprintf("SSH config contains invalid value for directive: %s", fields[0]), nil)
|
|
return
|
|
}
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
log.Error().Err(err).Msg("Failed to parse SSH config")
|
|
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid SSH config format", nil)
|
|
return
|
|
}
|
|
|
|
// Get the Pulse user's home directory
|
|
homeDir := os.Getenv("HOME")
|
|
if homeDir == "" {
|
|
homeDir = "/home/pulse" // fallback
|
|
}
|
|
|
|
// Create .ssh directory if it doesn't exist
|
|
sshDir := filepath.Join(homeDir, ".ssh")
|
|
if err := os.MkdirAll(sshDir, 0700); err != nil {
|
|
log.Error().Err(err).Str("dir", sshDir).Msg("Failed to create .ssh directory")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "internal_error", "Failed to create SSH directory", nil)
|
|
return
|
|
}
|
|
// Harden permissions even when the directory already existed.
|
|
if err := os.Chmod(sshDir, 0700); err != nil {
|
|
log.Error().Err(err).Str("dir", sshDir).Msg("Failed to set .ssh directory permissions")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "internal_error", "Failed to secure SSH directory", nil)
|
|
return
|
|
}
|
|
|
|
// Write SSH config file
|
|
configPath := filepath.Join(sshDir, "config")
|
|
if err := os.WriteFile(configPath, sshConfig, 0600); err != nil {
|
|
log.Error().Err(err).Str("path", configPath).Msg("Failed to write SSH config")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "internal_error", "Failed to write SSH config", nil)
|
|
return
|
|
}
|
|
// os.WriteFile does not change mode on existing files; enforce least-privilege.
|
|
if err := os.Chmod(configPath, 0600); err != nil {
|
|
log.Error().Err(err).Str("path", configPath).Msg("Failed to set SSH config file permissions")
|
|
writeErrorResponse(w, http.StatusInternalServerError, "internal_error", "Failed to secure SSH config", nil)
|
|
return
|
|
}
|
|
|
|
log.Info().Str("path", configPath).Int("size", len(sshConfig)).Msg("SSH config written successfully")
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if err := json.NewEncoder(w).Encode(map[string]bool{"success": true}); err != nil {
|
|
log.Error().Err(err).Msg("Failed to encode success response")
|
|
}
|
|
}
|