Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
refactor: remove legacy pulse-sensor-proxy temperature monitoring
rcourtmand4a6c0d2e883
diff --git a/cmd/pulse-sensor-proxy/README.md b/cmd/pulse-sensor-proxy/README.mddeleted file mode 100644index 83ff1ba520..0000000000--- a/cmd/pulse-sensor-proxy/README.md+++ /dev/null@@ -1,238 +0,0 @@-# pulse-sensor-proxy--> **Deprecated in v5:** `pulse-sensor-proxy` is deprecated and not recommended for new deployments.-> Temperature monitoring should be done via the unified agent (`pulse-agent --enable-proxmox`).-> This README is retained for existing installations during the migration window.-> See `docs/TEMPERATURE_MONITORING.md`.--The sensor proxy keeps SSH identities and temperature polling logic on the-Proxmox host while presenting a small RPC surface (Unix socket or HTTPS) to the-Pulse server. It protects SSH keys from container breakouts, enforces per-UID-capabilities, and produces append-only audit logs.--## Installation Options--| Scenario | Command |-| --- | --- |-| **Recommended (automated)** | `curl -fsSL https://github.com/rcourtman/Pulse/releases/latest/download/install-sensor-proxy.sh \| bash` |-| **Manual build** | `go build ./cmd/pulse-sensor-proxy` and `sudo install -m 0755 pulse-sensor-proxy /usr/local/bin/` |-| **Prebuilt artifact** | Download `pulse-sensor-proxy-<platform>-<arch>` from GitHub Releases, or copy it from `/opt/pulse/bin/` inside the Pulse Docker image. |--The installer script provisions:--- User & group: `pulse-sensor-proxy`-- Binary: `/usr/local/bin/pulse-sensor-proxy`-- Config: `/etc/pulse-sensor-proxy/config.yaml`-- SSH material: `/var/lib/pulse-sensor-proxy/ssh`-- Socket: `/run/pulse-sensor-proxy/pulse-sensor-proxy.sock`-- Logs: `/var/log/pulse/sensor-proxy/{proxy.log,audit.log}` (append-only)-- Systemd units: `pulse-sensor-proxy.service`, cleanup + self-heal timers--Start the service and verify status:--```bash-systemctl enable --now pulse-sensor-proxy-systemctl status pulse-sensor-proxy --no-pager-journalctl -u pulse-sensor-proxy -n 50-```--## Configuration--The proxy reads `/etc/pulse-sensor-proxy/config.yaml` (see-`config.example.yaml`). Key fields:--| Key | Purpose | Notes |-| --- | --- | --- |-| `allowed_source_subnets` | Restrict peers by CIDR | Empty list = auto-detect host networks |-| `allowed_peers[].uid/gid` | Capability-scoped authorisation | Prefer over legacy `allowed_peer_uids`|-| `allowed_peers[].capabilities` | `read`, `write`, `admin` | `read` covers `get_temperature`; `admin` required for `ensure_cluster_keys` |-| `metrics_address` | Prometheus listener | Default `127.0.0.1:9127`; set `disabled` to turn off |-| `require_proxmox_hostkeys` | Enforce known-host matches | Protects against SSH MITM |-| `max_ssh_output_bytes` | Cap command output | Prevents memory exhaustion (default 1 MiB) |-| `rate_limit.per_peer_interval_ms` / `per_peer_burst` | Token bucket guardrails | Keep interval ≥100 ms in production |-| `http_*` keys | HTTPS bridge mode | Needs TLS files plus bearer token |-| `allowed_nodes_file` | Path to allowed nodes list | Default: `/etc/pulse-sensor-proxy/allowed_nodes.yaml` |--### Configuration Management CLI--The proxy includes built-in commands for safe configuration management. These prevent corruption by using atomic writes and file locking.--**Validate configuration:**-```bash-# Validate config.yaml and allowed_nodes.yaml-pulse-sensor-proxy config validate--# Validate specific config file-pulse-sensor-proxy config validate --config /path/to/config.yaml--# Validate specific allowed_nodes file-pulse-sensor-proxy config validate --allowed-nodes /path/to/allowed_nodes.yaml-```--**Manage allowed nodes:**-```bash-# Add nodes to the allowed list (merge mode)-pulse-sensor-proxy config set-allowed-nodes --merge 192.168.0.1 --merge node1.local--# Replace entire list with new nodes-pulse-sensor-proxy config set-allowed-nodes --replace --merge 192.168.0.1 --merge 192.168.0.2--# Clear the allowed nodes list (replace with empty)-pulse-sensor-proxy config set-allowed-nodes --replace--# Use custom path-pulse-sensor-proxy config set-allowed-nodes --allowed-nodes /custom/path.yaml --merge 192.168.0.10-```--**How it works:**-- All writes are atomic (temp file + rename)-- File locking prevents concurrent modifications-- Deduplication and normalization happen automatically-- Empty lists are allowed (useful for security lockdown or IPC-only clusters)-- Config validation runs before service startup (systemd ExecStartPre)--**Best practices:**-- Use the CLI instead of manual editing whenever possible-- The installer automatically uses these commands-- Manual edits to `config.yaml` are safe if the service is stopped-- Never edit `allowed_nodes.yaml` while the service is running--### Allowed Nodes File--The proxy maintains a separate YAML file for the authorized node list at-`/etc/pulse-sensor-proxy/allowed_nodes.yaml`. This separation prevents-config corruption when the installer or control-plane sync updates the list.--Format:-```yaml-# Managed by pulse-sensor-proxy config CLI-# Do not edit manually while service is running-allowed_nodes:- - 192.168.0.1- - 192.168.0.2- - node1.local- - node2.example.com-```--The file is optional - if missing or empty, the proxy falls back to IPC-based-discovery (pvecm status) when available.--### Environment Overrides--- `PULSE_SENSOR_PROXY_SOCKET`, `PULSE_SENSOR_PROXY_SSH_DIR`,- `PULSE_SENSOR_PROXY_CONFIG` – relocate runtime paths-- `PULSE_SENSOR_PROXY_USER` – run under a different service account (defaults to- `pulse-sensor-proxy`)-- `PULSE_SENSOR_PROXY_ALLOWED_SUBNETS` – comma-separated list appended at boot-- `PULSE_SENSOR_PROXY_ALLOWED_PEER_UIDS/GIDS` – extend authorisation without- editing YAML-- `PULSE_SENSOR_PROXY_ALLOW_IDMAPPED_ROOT` – explicitly allow/deny ID-mapped root-- `PULSE_SENSOR_PROXY_READ_TIMEOUT` / `_WRITE_TIMEOUT` – Go duration strings-- `PULSE_SENSOR_PROXY_AUDIT_LOG` – custom log path (still append-only)--## HTTP Mode--Set `http_enabled: true` when the backend cannot mount the Unix socket (for-example, Kubernetes). Requirements:--1. Populate `http_listen_addr` (e.g. `0.0.0.0:9443`).-2. Provide `http_tls_cert`/`http_tls_key`. The installer can place certs under- `/etc/pulse-sensor-proxy/tls`.-3. Set a long `http_auth_token`. Pulse sends it as a bearer token.-4. Restrict `allowed_source_subnets` to the Pulse control-plane addresses.--The HTTP server exports `/temps` and `/health`, enforces Bearer tokens, and logs-all HTTP access attempts to the audit log.--## Audit Logging & Rotation--- Location: `/var/log/pulse/sensor-proxy/audit.log`-- Format: JSON with hash chaining (`prev_hash`, `event_hash`, `seq`)-- Access: Owned by `pulse-sensor-proxy`, `0640`, `chattr +a`--Follow standard log rotation practices (e.g., `logrotate`) for rotation (remove `+a`,-truncate, restart service, reapply `+a`). Also consider forwarding with-`scripts/setup-log-forwarding.sh`; see-See standard rsyslog practices for log forwarding and verification.-steps.--## Metrics & Monitoring--| Signal | Command |-| --- | --- |-| Prometheus metrics | `curl -s http://127.0.0.1:9127/metrics \| head` |-| Scheduler health (Pulse) | `curl -s http://localhost:7655/api/monitoring/scheduler/health \| jq '.instances[] \| select(.key \| contains(\"temperature\")) \| {key, breaker: .breaker.state, deadLetter: .deadLetter.present}'` |-| Journal logs | `journalctl -u pulse-sensor-proxy -f` |-| Rate-limit hits | `journalctl -u pulse-sensor-proxy \| grep "rate limit"` |--Set alerts on:--- `pulse_proxy_rate_limit_hits_total` spikes (potential abuse)-- `pulse_proxy_hostkey_changes_total` increments (SSH MITM)-- Temperature instances showing `breaker.state != "closed"` for >10 minutes--## Troubleshooting--| Symptom | Guidance |-| --- | --- |-| Service fails to start with "Config validation failed" | Run `pulse-sensor-proxy config validate` to see specific errors. Check for duplicate keys or malformed YAML. |-| Config corruption detected during startup | Older versions had dual code paths. Update to the latest release and reinstall the proxy. The migration runs automatically. |-| Temperature monitoring stops working after config change | Validate config first with `pulse-sensor-proxy config validate`, then restart service: `systemctl restart pulse-sensor-proxy`. |-| `Cannot open audit log file` | Check permissions on `/var/log/pulse/sensor-proxy`. Remove `chattr +a` only during rotation. |-| `connection denied` in audit log | UID/GID not listed in `allowed_peers`. Verify Pulse container UID mapping. |-| `HTTP request from unauthorized source IP` | Update `allowed_source_subnets` or run through a reverse proxy that advertises the client IP via `ProxyProtocol` (not supported yet). |-| `rate limit exceeded` | Increase `rate_limit.per_peer_burst` or fix noisy hosts before relaxing limits. |-| `temperature pollers stuck` | Hit `/api/monitoring/scheduler/health`, ensure breakers are `closed`, restart Pulse + proxy if necessary. |-| Lock file permissions error | Lock files use 0600 to prevent unprivileged DoS. Check file ownership matches proxy user. |--### Config Corruption Recovery--If you suspect config corruption (service won't start, temperatures stopped):--1. **Validate the config:**- ```bash- pulse-sensor-proxy config validate- ```--2. **If corruption is detected, reinstall the proxy:**- ```bash- curl -fsSL https://github.com/rcourtman/Pulse/releases/latest/download/install-sensor-proxy.sh | \- sudo bash -s -- --standalone --pulse-server http://your-pulse:7655- ```- The installer automatically migrates to file-based config and fixes corruption.--3. **Check for duplicate allowed_nodes blocks:**- ```bash- grep -n "allowed_nodes:" /etc/pulse-sensor-proxy/config.yaml- ```- Should only appear once. Multiple instances indicate corruption that Phase 1 migration will fix.--4. **Manual recovery (if installer unavailable):**- ```bash- # Stop the service- sudo systemctl stop pulse-sensor-proxy-- # Validate and identify issues- pulse-sensor-proxy config validate --config /etc/pulse-sensor-proxy/config.yaml-- # If allowed_nodes appears in config.yaml, extract it manually:- grep -A 100 "^allowed_nodes:" /etc/pulse-sensor-proxy/config.yaml | \- head -n 20 > /tmp/nodes.txt-- # Remove duplicate allowed_nodes from config.yaml (edit manually)- # Then create allowed_nodes.yaml:- pulse-sensor-proxy config set-allowed-nodes --replace --merge node1 --merge node2-- # Add allowed_nodes_file reference to config.yaml if missing:- echo "allowed_nodes_file: /etc/pulse-sensor-proxy/allowed_nodes.yaml" | \- sudo tee -a /etc/pulse-sensor-proxy/config.yaml-- # Validate again- pulse-sensor-proxy config validate-- # Start service- sudo systemctl start pulse-sensor-proxy- ```--For additional hardening steps, read the main `docs/security/TEMPERATURE_MONITORING.md` guide and-`docs/security/TEMPERATURE_MONITORING.md`.diff --git a/cmd/pulse-sensor-proxy/audit.go b/cmd/pulse-sensor-proxy/audit.godeleted file mode 100644index 9ec43e8656..0000000000--- a/cmd/pulse-sensor-proxy/audit.go+++ /dev/null@@ -1,336 +0,0 @@-package main--import (- "crypto/sha256"- "encoding/hex"- "encoding/json"- "os"- "sync"- "time"-- "github.com/rs/zerolog"- "github.com/rs/zerolog/log"-)--// auditLogger emits append-only, hash-chained audit events.-type auditLogger struct {- mu sync.Mutex- file *os.File- logger zerolog.Logger- prevHash []byte- sequence uint64-}--// AuditEvent captures a single security-relevant action.-type AuditEvent struct {- Sequence uint64 `json:"seq"`- Timestamp time.Time `json:"ts"`- EventType string `json:"event_type"`- CorrelationID string `json:"correlation_id,omitempty"`- PeerUID *uint32 `json:"peer_uid,omitempty"`- PeerGID *uint32 `json:"peer_gid,omitempty"`- PeerPID *uint32 `json:"peer_pid,omitempty"`- RemoteAddr string `json:"remote_addr,omitempty"`- Command string `json:"command,omitempty"`- Args []string `json:"args,omitempty"`- Target string `json:"target,omitempty"`- Decision string `json:"decision,omitempty"`- Reason string `json:"reason,omitempty"`- Limiter string `json:"limiter,omitempty"`- ExitCode *int `json:"exit_code,omitempty"`- DurationMs *int64 `json:"duration_ms,omitempty"`- StdoutHash string `json:"stdout_sha256,omitempty"`- StderrHash string `json:"stderr_sha256,omitempty"`- Error string `json:"error,omitempty"`- PrevHash string `json:"prev_hash"`- EventHash string `json:"event_hash"`-}--// newAuditLogger opens the audit log file and prepares hash chaining.-// If the file cannot be opened (e.g., read-only filesystem), it automatically-// falls back to stderr which integrates with systemd journal.-// This function always succeeds and returns a valid audit logger.-func newAuditLogger(path string) *auditLogger {- // Try to open the audit log file- file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)- var writer zerolog.Logger- var usedFallback bool-- if err != nil {- // Fallback to stderr if file cannot be opened- log.Warn().- Err(err).- Str("path", path).- Msg("Cannot open audit log file, falling back to stderr (systemd journal)")-- writer = zerolog.New(os.Stderr).With().Timestamp().Logger()- usedFallback = true- file = nil- } else {- writer = zerolog.New(file).With().Timestamp().Logger()- }-- // Log initialization event to standard logger (not to audit log itself)- if usedFallback {- log.Warn().- Str("path", path).- Str("mode", "stderr").- Msg("Audit logger initialized with stderr fallback due to filesystem constraints")- } else {- log.Info().- Str("path", path).- Str("mode", "file").- Msg("Audit logger initialized with file backend")- }-- return &auditLogger{- file: file,- logger: writer,- }-}--// Close flushes and closes the audit log file.-func (a *auditLogger) Close() error {- a.mu.Lock()- defer a.mu.Unlock()- if a.file == nil {- return nil- }- err := a.file.Close()- a.file = nil- return err-}--// LogConnectionAccepted records an authorized connection.-func (a *auditLogger) LogConnectionAccepted(correlationID string, cred *peerCredentials, remote string) {- event := AuditEvent{- EventType: "connection.accepted",- CorrelationID: correlationID,- RemoteAddr: remote,- Decision: "allowed",- }- event.applyPeer(cred)- a.log(&event)-}--// LogConnectionDenied records a rejected connection attempt.-func (a *auditLogger) LogConnectionDenied(correlationID string, cred *peerCredentials, remote, reason string) {- event := AuditEvent{- EventType: "connection.denied",- CorrelationID: correlationID,- RemoteAddr: remote,- Decision: "denied",- Reason: reason,- }- event.applyPeer(cred)- a.log(&event)-}--// LogRateLimitHit records limiter rejections.-func (a *auditLogger) LogRateLimitHit(correlationID string, cred *peerCredentials, remote, limiter string) {- event := AuditEvent{- EventType: "limiter.rejection",- CorrelationID: correlationID,- RemoteAddr: remote,- Decision: "denied",- Limiter: limiter,- }- event.applyPeer(cred)- a.log(&event)-}--// LogCommandStart records command execution approval.-func (a *auditLogger) LogCommandStart(correlationID string, cred *peerCredentials, remote, target, command string, args []string) {- event := AuditEvent{- EventType: "command.start",- CorrelationID: correlationID,- RemoteAddr: remote,- Decision: "allowed",- Command: command,- Args: args,- Target: target,- }- event.applyPeer(cred)- a.log(&event)-}--// LogCommandResult records command completion.-func (a *auditLogger) LogCommandResult(correlationID string, cred *peerCredentials, remote, target, command string, args []string, exitCode int, duration time.Duration, stdoutHash, stderrHash string, execErr error) {- event := AuditEvent{- EventType: "command.finish",- CorrelationID: correlationID,- RemoteAddr: remote,- Command: command,- Args: args,- Target: target,- ExitCode: intPtr(exitCode),- StdoutHash: stdoutHash,- StderrHash: stderrHash,- }- event.applyPeer(cred)- if duration > 0 {- ms := duration.Milliseconds()- event.DurationMs = int64Ptr(ms)- }- if execErr != nil {- event.Error = execErr.Error()- event.Decision = "failed"- } else {- event.Decision = "completed"- }- a.log(&event)-}--// LogValidationFailure records validator rejections.-func (a *auditLogger) LogValidationFailure(correlationID string, cred *peerCredentials, remote, command string, args []string, reason string) {- event := AuditEvent{- EventType: "command.validation_failed",- CorrelationID: correlationID,- RemoteAddr: remote,- Command: command,- Args: args,- Decision: "denied",- Reason: reason,- }- event.applyPeer(cred)- a.log(&event)-}--func (e *AuditEvent) applyPeer(cred *peerCredentials) {- if cred == nil {- return- }- e.PeerUID = uint32Ptr(cred.uid)- e.PeerGID = uint32Ptr(cred.gid)- e.PeerPID = uint32Ptr(cred.pid)-}--// log persists the event with hash chaining.-func (a *auditLogger) log(event *AuditEvent) {- if event == nil {- log.Error().Msg("audit log called with nil event")- return- }-- a.mu.Lock()- defer a.mu.Unlock()-- a.sequence++- event.Sequence = a.sequence-- if event.Timestamp.IsZero() {- event.Timestamp = time.Now().UTC()- } else {- event.Timestamp = event.Timestamp.UTC()- }-- event.PrevHash = hex.EncodeToString(a.prevHash)-- payload, err := eventMarshalForHash(event)- if err != nil {- log.Error().Err(err).Msg("failed to marshal audit event")- return- }-- sum := sha256.Sum256(append(a.prevHash, payload...))- a.prevHash = sum[:]- event.EventHash = hex.EncodeToString(sum[:])-- a.logger.Info().Fields(eventToMap(event)).Send()-}--func eventMarshalForHash(event *AuditEvent) ([]byte, error) {- clone := *event- clone.EventHash = ""- return json.Marshal(clone)-}--func eventToMap(event *AuditEvent) map[string]interface{} {- m := map[string]interface{}{- "ts": event.Timestamp.Format(time.RFC3339Nano),- "event_type": event.EventType,- "seq": event.Sequence,- "prev_hash": event.PrevHash,- "event_hash": event.EventHash,- "decision": event.Decision,- "correlation_id": event.CorrelationID,- }-- if event.PeerUID != nil {- m["peer_uid"] = *event.PeerUID- }- if event.PeerGID != nil {- m["peer_gid"] = *event.PeerGID- }- if event.PeerPID != nil {- m["peer_pid"] = *event.PeerPID- }- if event.RemoteAddr != "" {- m["remote_addr"] = event.RemoteAddr- }- if event.Command != "" {- m["command"] = event.Command- }- if len(event.Args) > 0 {- m["args"] = event.Args- }- if event.Target != "" {- m["target"] = event.Target- }- if event.Reason != "" {- m["reason"] = event.Reason- }- if event.Limiter != "" {- m["limiter"] = event.Limiter- }- if event.ExitCode != nil {- m["exit_code"] = *event.ExitCode- }- if event.DurationMs != nil {- m["duration_ms"] = *event.DurationMs- }- if event.StdoutHash != "" {- m["stdout_sha256"] = event.StdoutHash- }- if event.StderrHash != "" {- m["stderr_sha256"] = event.StderrHash- }- if event.Error != "" {- m["error"] = event.Error- }-- return m-}--func uint32Ptr(v uint32) *uint32 {- value := v- return &value-}--func intPtr(v int) *int {- value := v- return &value-}--func int64Ptr(v int64) *int64 {- value := v- return &value-}--// LogHTTPRequest logs HTTP requests for audit trail-func (a *auditLogger) LogHTTPRequest(remoteAddr, method, path string, statusCode int, reason string) {- if a == nil {- return- }-- event := AuditEvent{- EventType: "http_request",- RemoteAddr: remoteAddr,- Command: method,- Target: path,- ExitCode: &statusCode,- Reason: reason,- }-- a.log(&event)-}diff --git a/cmd/pulse-sensor-proxy/audit_test.go b/cmd/pulse-sensor-proxy/audit_test.godeleted file mode 100644index b99ae47958..0000000000--- a/cmd/pulse-sensor-proxy/audit_test.go+++ /dev/null@@ -1,144 +0,0 @@-package main--import (- "bufio"- "encoding/json"- "errors"- "os"- "testing"- "time"-)--type auditRecord map[string]interface{}--func TestAuditLogValidationFailure(t *testing.T) {- tmp, err := os.CreateTemp("", "audit-test-*.log")- if err != nil {- t.Fatalf("temp file: %v", err)- }- path := tmp.Name()- tmp.Close()- defer os.Remove(path)-- logger := newAuditLogger(path)-- cred := &peerCredentials{uid: 1000, gid: 1000, pid: 4242}- logger.LogValidationFailure("corr-123", cred, "remote", "get_temperature", []string{"node"}, "invalid_node")- logger.Close()-- file, err := os.Open(path)- if err != nil {- t.Fatalf("open log: %v", err)- }- defer file.Close()-- scanner := bufio.NewScanner(file)- if !scanner.Scan() {- t.Fatalf("expected at least one audit entry (file may be empty)")- }-- line := scanner.Bytes()- if len(line) == 0 {- t.Fatalf("empty line in audit log")- }-- t.Logf("Audit log line: %s", string(line))-- var record auditRecord- if err := json.Unmarshal(line, &record); err != nil {- t.Fatalf("unmarshal (line=%s): %v", string(line), err)- }-- t.Logf("Parsed record: %+v", record)-- if record["event_type"] != "command.validation_failed" {- t.Fatalf("unexpected event_type: %v (full record: %+v)", record["event_type"], record)- }- if record["correlation_id"] != "corr-123" {- t.Fatalf("unexpected correlation id: %v", record["correlation_id"])- }- if record["command"] != "get_temperature" {- t.Fatalf("unexpected command: %v", record["command"])- }- if record["reason"] != "invalid_node" {- t.Fatalf("unexpected reason: %v", record["reason"])- }- if record["decision"] != "denied" {- t.Fatalf("unexpected decision: %v", record["decision"])- }- if record["event_hash"] == "" {- t.Fatalf("expected event_hash to be set")- }-}--func TestAuditLoggerFallback(t *testing.T) {- // Try to open a file in a non-existent directory to trigger fallback- logger := newAuditLogger("/nonexistent/directory/audit.log")- if logger.file != nil {- t.Error("expected file to be nil for fallback")- }-- // Should not panic when logging to fallback- logger.LogConnectionAccepted("corr-456", &peerCredentials{uid: 0}, "local")- logger.Close()-}--func TestAuditLoggerAllEvents(t *testing.T) {- tmp, err := os.CreateTemp("", "audit-test-all-*.log")- if err != nil {- t.Fatal(err)- }- path := tmp.Name()- tmp.Close()- defer os.Remove(path)-- logger := newAuditLogger(path)- cred := &peerCredentials{uid: 1000, gid: 1000, pid: 4242}-- logger.LogConnectionAccepted("c1", cred, "r1")- logger.LogConnectionDenied("c2", cred, "r2", "bad token")- logger.LogRateLimitHit("c3", cred, "r3", "global")- logger.LogCommandStart("c4", cred, "r4", "t4", "cmd4", []string{"arg4"})- logger.LogCommandResult("c5", cred, "r5", "t5", "cmd5", []string{"arg5"}, 0, time.Second, "h1", "h2", nil)- logger.LogCommandResult("c6", cred, "r6", "t6", "cmd6", []string{"arg6"}, 1, time.Second, "", "", errors.New("exec error"))- logger.LogHTTPRequest("r7", "GET", "/path", 200, "ok")-- // Log with nil creds- logger.LogConnectionAccepted("c8", nil, "r8")-- // Log with nil logger (should handle gracefully if possible, but it's a pointer receiver)- // logger.log(nil) // Already tested indirectly via internal calls if event is nil-- logger.Close()- // Double close should be fine- logger.Close()-- // Basic verification that all lines are present- file, err := os.Open(path)- if err != nil {- t.Fatal(err)- }- defer file.Close()- scanner := bufio.NewScanner(file)- count := 0- for scanner.Scan() {- count++- }- if count != 8 {- t.Errorf("expected 8 audit entries, got %d", count)- }-}--func TestAuditEvent_ApplyPeer_Nil(t *testing.T) {- e := &AuditEvent{}- e.applyPeer(nil)- if e.PeerUID != nil {- t.Error("expected PeerUID to be nil")- }-}--func TestAuditLogNilEvent(t *testing.T) {- logger := newAuditLogger("") // This might fail or use fallback- // Calling a.log(nil) directly to test the nil check- logger.log(nil)-}diff --git a/cmd/pulse-sensor-proxy/auth.go b/cmd/pulse-sensor-proxy/auth.godeleted file mode 100644index 86bbf9a8b1..0000000000--- a/cmd/pulse-sensor-proxy/auth.go+++ /dev/null@@ -1,279 +0,0 @@-package main--import (- "errors"- "fmt"- "os"- "strconv"- "strings"-- "github.com/rs/zerolog/log"-)--// peerCredentials holds extracted credentials from SO_PEERCRED-type peerCredentials struct {- uid uint32- pid uint32- gid uint32-}--type idRange struct {- start uint64- length uint64-}--func (r idRange) contains(v uint32) bool {- value := uint64(v)- return value >= r.start && value < r.start+r.length-}--// initAuthRules builds in-memory allow lists for peer validation-func (p *Proxy) initAuthRules() error {- p.allowedPeerUIDs = make(map[uint32]struct{})- p.allowedPeerGIDs = make(map[uint32]struct{})- p.peerCapabilities = make(map[uint32]Capability)-- addCapability := func(uid uint32, caps Capability) {- if caps == 0 {- caps = CapabilityRead- }- if existing, ok := p.peerCapabilities[uid]; ok {- p.peerCapabilities[uid] = existing | caps- } else {- p.peerCapabilities[uid] = caps- }- }-- // Always allow root and the proxy's own user- p.allowedPeerUIDs[0] = struct{}{}- addCapability(0, capabilityLegacyAll)- p.allowedPeerUIDs[uint32(os.Getuid())] = struct{}{}- addCapability(uint32(os.Getuid()), capabilityLegacyAll)- p.allowedPeerGIDs[0] = struct{}{}- p.allowedPeerGIDs[uint32(os.Getgid())] = struct{}{}-- if len(p.config.AllowedPeers) > 0 {- for _, peer := range p.config.AllowedPeers {- p.allowedPeerUIDs[peer.UID] = struct{}{}- addCapability(peer.UID, parseCapabilityList(peer.Capabilities))- }- log.Info().Int("peer_capability_entries", len(p.config.AllowedPeers)).Msg("Loaded capability entries for peers")- }-- if len(p.config.AllowedPeerUIDs) > 0 {- for _, uid := range dedupeUint32(p.config.AllowedPeerUIDs) {- p.allowedPeerUIDs[uid] = struct{}{}- if _, ok := p.peerCapabilities[uid]; !ok {- addCapability(uid, capabilityLegacyAll)- }- }- log.Info().- Int("explicit_uid_allow_count", len(p.config.AllowedPeerUIDs)).- Msg("Loaded explicit peer UID allow-list entries")- }-- if len(p.config.AllowedPeerGIDs) > 0 {- for _, gid := range dedupeUint32(p.config.AllowedPeerGIDs) {- p.allowedPeerGIDs[gid] = struct{}{}- }- log.Info().- Int("explicit_gid_allow_count", len(p.config.AllowedPeerGIDs)).- Msg("Loaded explicit peer GID allow-list entries")- }-- if !p.config.AllowIDMappedRoot {- log.Info().Msg("ID-mapped root authentication disabled")- return nil- }-- users := dedupeStrings(p.config.AllowedIDMapUsers)- if len(users) == 0 {- users = []string{"root"}- }-- uidRanges, gidRanges, err := loadIDMappingRanges(users)- if err != nil {- return err- }-- p.idMappedUIDRanges = uidRanges- p.idMappedGIDRanges = gidRanges-- if len(uidRanges) == 0 || len(gidRanges) == 0 {- log.Warn().- Strs("users", users).- Msg("allow_idmapped_root enabled but no subordinate ID ranges detected; LXC connections may fail")- } else {- log.Info().- Int("uid_range_count", len(uidRanges)).- Int("gid_range_count", len(gidRanges)).- Strs("users", users).- Msg("Loaded subordinate ID ranges for ID-mapped root authentication")- }-- return nil-}--// authorizePeer verifies the peer credentials against configured allow lists and returns capabilities.-func (p *Proxy) authorizePeer(cred *peerCredentials) (Capability, error) {- if cred == nil {- return 0, fmt.Errorf("missing peer credentials")- }-- if caps, ok := p.peerCapabilities[cred.uid]; ok {- log.Debug().- Uint32("uid", cred.uid).- Msg("Peer authorized via UID allow-list")- return caps, nil- }-- if len(p.allowedPeerGIDs) > 0 {- if _, ok := p.allowedPeerGIDs[cred.gid]; ok {- log.Debug().- Uint32("gid", cred.gid).- Msg("Peer authorized via GID allow-list")- return capabilityLegacyAll, nil- }- }-- if p.config.AllowIDMappedRoot && p.isIDMappedRoot(cred) {- log.Debug().- Uint32("uid", cred.uid).- Uint32("gid", cred.gid).- Msg("Peer authorized via ID-mapped root range")- return CapabilityRead, nil- }-- return 0, fmt.Errorf("unauthorized: uid=%d gid=%d", cred.uid, cred.gid)-}--func (p *Proxy) isIDMappedRoot(cred *peerCredentials) bool {- if len(p.idMappedUIDRanges) == 0 || len(p.idMappedGIDRanges) == 0 {- return false- }-- if !rangeContains(p.idMappedUIDRanges, cred.uid) {- return false- }-- if !rangeContains(p.idMappedGIDRanges, cred.gid) {- return false- }-- return true-}--func rangeContains(ranges []idRange, value uint32) bool {- for _, r := range ranges {- if r.contains(value) {- return true- }- }- return false-}--func dedupeUint32(values []uint32) []uint32 {- seen := make(map[uint32]struct{})- var result []uint32- for _, val := range values {- if _, ok := seen[val]; ok {- continue- }- seen[val] = struct{}{}- result = append(result, val)- }- return result-}--func dedupeStrings(values []string) []string {- seen := make(map[string]struct{})- var result []string- for _, val := range values {- trimmed := strings.TrimSpace(val)- if trimmed == "" {- continue- }- if _, ok := seen[trimmed]; ok {- continue- }- seen[trimmed] = struct{}{}- result = append(result, trimmed)- }- return result-}--func loadSubIDRanges(path string, users []string) ([]idRange, error) {- data, err := os.ReadFile(path)- if err != nil {- if errors.Is(err, os.ErrNotExist) {- return nil, nil- }- return nil, err- }-- userFilter := make(map[string]struct{}, len(users))- for _, user := range users {- userFilter[user] = struct{}{}- }-- lines := strings.Split(string(data), "\n")- var ranges []idRange-- for _, line := range lines {- line = strings.TrimSpace(line)- if line == "" || strings.HasPrefix(line, "#") {- continue- }-- parts := strings.Split(line, ":")- if len(parts) < 3 {- continue- }-- if len(userFilter) > 0 {- if _, ok := userFilter[parts[0]]; !ok {- continue- }- }-- start, err := strconv.ParseUint(parts[1], 10, 64)- if err != nil {- log.Warn().- Str("entry", line).- Err(err).- Msg("Skipping subordinate ID entry with invalid start value")- continue- }-- length, err := strconv.ParseUint(parts[2], 10, 64)- if err != nil || length == 0 {- log.Warn().- Str("entry", line).- Err(err).- Msg("Skipping subordinate ID entry with invalid length")- continue- }-- ranges = append(ranges, idRange{start: start, length: length})- }-- return ranges, nil-}--// subUIDPath and subGIDPath are variables to allow testing override-var (- subUIDPath = "/etc/subuid"- subGIDPath = "/etc/subgid"-)--func loadIDMappingRanges(users []string) ([]idRange, []idRange, error) {- uidRanges, err := loadSubIDRanges(subUIDPath, users)- if err != nil {- return nil, nil, fmt.Errorf("loading subordinate UID ranges: %w", err)- }- gidRanges, err := loadSubIDRanges(subGIDPath, users)- if err != nil {- return nil, nil, fmt.Errorf("loading subordinate GID ranges: %w", err)- }- return uidRanges, gidRanges, nil-}diff --git a/cmd/pulse-sensor-proxy/auth_test.go b/cmd/pulse-sensor-proxy/auth_test.godeleted file mode 100644index e04003596b..0000000000--- a/cmd/pulse-sensor-proxy/auth_test.go+++ /dev/null@@ -1,397 +0,0 @@-package main--import (- "os"- "path/filepath"- "testing"-)--func TestAuthorizePeer(t *testing.T) {- p := &Proxy{- config: &Config{AllowIDMappedRoot: true},- allowedPeerUIDs: map[uint32]struct{}{0: {}},- allowedPeerGIDs: map[uint32]struct{}{0: {}},- idMappedUIDRanges: []idRange{{start: 165536, length: 65536}},- idMappedGIDRanges: []idRange{{start: 165536, length: 65536}},- }-- if _, err := p.authorizePeer(&peerCredentials{uid: 0, gid: 0}); err != nil {- t.Fatalf("expected root to be authorized, got %v", err)- }-- if _, err := p.authorizePeer(&peerCredentials{uid: 170000, gid: 170000}); err != nil {- t.Fatalf("expected idmapped root to be authorized, got %v", err)- }-- if _, err := p.authorizePeer(&peerCredentials{uid: 900, gid: 900}); err == nil {- t.Fatalf("expected non-allowed user to be rejected")- }-}--func TestAuthorizePeerWithGIDAllowList(t *testing.T) {- p := &Proxy{- config: &Config{AllowIDMappedRoot: false},- allowedPeerUIDs: map[uint32]struct{}{},- allowedPeerGIDs: map[uint32]struct{}{2000: {}},- idMappedUIDRanges: nil,- idMappedGIDRanges: nil,- }-- // Should authorize because GID is explicitly allowed- if _, err := p.authorizePeer(&peerCredentials{uid: 1500, gid: 2000}); err != nil {- t.Fatalf("expected peer to be authorized via GID allow-list, got %v", err)- }-- // Should reject because UID and GID are not permitted- if _, err := p.authorizePeer(&peerCredentials{uid: 1500, gid: 3000}); err == nil {- t.Fatalf("expected peer to be rejected when GID not in allow-list")- }-}--func TestAuthorizePeerCapabilities(t *testing.T) {- p := &Proxy{- config: &Config{},- allowedPeerUIDs: map[uint32]struct{}{1000: {}},- peerCapabilities: map[uint32]Capability{1000: CapabilityRead},- }-- caps, err := p.authorizePeer(&peerCredentials{uid: 1000, gid: 1000})- if err != nil {- t.Fatalf("expected authorization to succeed: %v", err)- }- if !caps.Has(CapabilityRead) {- t.Fatal("expected read capability")- }- if caps.Has(CapabilityAdmin) {- t.Fatal("did not expect admin capability")- }-- // Legacy behaviour (all capabilities) when configured accordingly- p.allowedPeerUIDs[2000] = struct{}{}- p.peerCapabilities[2000] = capabilityLegacyAll- caps, err = p.authorizePeer(&peerCredentials{uid: 2000, gid: 2000})- if err != nil {- t.Fatalf("expected legacy authorization to succeed: %v", err)- }- if !caps.Has(CapabilityAdmin) {- t.Fatal("expected admin capability for legacy peer")- }-}--func TestDedupeUint32(t *testing.T) {- tests := []struct {- name string- input []uint32- expected []uint32- }{- {- name: "nil input",- input: nil,- expected: nil,- },- {- name: "empty slice",- input: []uint32{},- expected: nil,- },- {- name: "no duplicates",- input: []uint32{1, 2, 3},- expected: []uint32{1, 2, 3},- },- {- name: "all duplicates",- input: []uint32{5, 5, 5, 5},- expected: []uint32{5},- },- {- name: "mixed duplicates",- input: []uint32{1, 2, 1, 3, 2, 4},- expected: []uint32{1, 2, 3, 4},- },- {- name: "single element",- input: []uint32{42},- expected: []uint32{42},- },- {- name: "preserves order",- input: []uint32{3, 1, 4, 1, 5, 9, 2, 6, 5, 3},- expected: []uint32{3, 1, 4, 5, 9, 2, 6},- },- {- name: "zero values",- input: []uint32{0, 1, 0, 2},- expected: []uint32{0, 1, 2},- },- {- name: "max uint32",- input: []uint32{4294967295, 0, 4294967295},- expected: []uint32{4294967295, 0},- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := dedupeUint32(tc.input)-- if len(result) != len(tc.expected) {- t.Errorf("dedupeUint32(%v) = %v (len %d), want %v (len %d)",- tc.input, result, len(result), tc.expected, len(tc.expected))- return- }-- for i := range result {- if result[i] != tc.expected[i] {- t.Errorf("dedupeUint32(%v) = %v, want %v", tc.input, result, tc.expected)- return- }- }- })- }-}--func TestDedupeStrings(t *testing.T) {- tests := []struct {- name string- input []string- expected []string- }{- {- name: "nil input",- input: nil,- expected: nil,- },- {- name: "empty slice",- input: []string{},- expected: nil,- },- {- name: "no duplicates",- input: []string{"a", "b", "c"},- expected: []string{"a", "b", "c"},- },- {- name: "all duplicates",- input: []string{"foo", "foo", "foo"},- expected: []string{"foo"},- },- {- name: "mixed duplicates",- input: []string{"a", "b", "a", "c", "b"},- expected: []string{"a", "b", "c"},- },- {- name: "single element",- input: []string{"single"},- expected: []string{"single"},- },- {- name: "preserves order",- input: []string{"c", "a", "b", "a", "c"},- expected: []string{"c", "a", "b"},- },- {- name: "trims whitespace",- input: []string{" foo ", "bar", "foo"},- expected: []string{"foo", "bar"},- },- {- name: "filters empty after trim",- input: []string{"a", " ", "", "b"},- expected: []string{"a", "b"},- },- {- name: "whitespace only",- input: []string{" ", "\t", "\n"},- expected: nil,- },- {- name: "case sensitive",- input: []string{"Foo", "foo", "FOO"},- expected: []string{"Foo", "foo", "FOO"},- },- {- name: "leading and trailing whitespace dedup",- input: []string{" test", "test ", "test"},- expected: []string{"test"},- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := dedupeStrings(tc.input)-- if len(result) != len(tc.expected) {- t.Errorf("dedupeStrings(%v) = %v (len %d), want %v (len %d)",- tc.input, result, len(result), tc.expected, len(tc.expected))- return- }-- for i := range result {- if result[i] != tc.expected[i] {- t.Errorf("dedupeStrings(%v) = %v, want %v", tc.input, result, tc.expected)- return- }- }- })- }-}--func TestInitAuthRules(t *testing.T) {- p := &Proxy{- config: &Config{- AllowedPeers: []PeerConfig{- {UID: 1001, Capabilities: []string{"read", "write"}},- },- AllowedPeerUIDs: []uint32{1002, 1002},- AllowedPeerGIDs: []uint32{2001},- },- }-- if err := p.initAuthRules(); err != nil {- t.Fatalf("initAuthRules failed: %v", err)- }-- if _, ok := p.allowedPeerUIDs[1001]; !ok {- t.Error("expected UID 1001 to be allowed")- }- if caps := p.peerCapabilities[1001]; !caps.Has(CapabilityWrite) {- t.Error("expected UID 1001 to have write capability")- }-- if _, ok := p.allowedPeerUIDs[1002]; !ok {- t.Error("expected UID 1002 to be allowed")- }- if caps := p.peerCapabilities[1002]; !caps.Has(CapabilityAdmin) {- t.Error("expected UID 1002 to have legacy all capabilities")- }-- if _, ok := p.allowedPeerGIDs[2001]; !ok {- t.Error("expected GID 2001 to be allowed")- }-}--func TestLoadSubIDRanges(t *testing.T) {- tmpFile, err := os.CreateTemp("", "subuid")- if err != nil {- t.Fatal(err)- }- defer os.Remove(tmpFile.Name())-- content := `root:100000:65536-# commented:line:100-user1:200000:1000-invalid:start:65536-toolong:100:notanumber-short:line-zero:300000:0-`- if err := os.WriteFile(tmpFile.Name(), []byte(content), 0644); err != nil {- t.Fatal(err)- }-- // Test with filter- ranges, err := loadSubIDRanges(tmpFile.Name(), []string{"root", "user1"})- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if len(ranges) != 2 {- t.Fatalf("expected 2 ranges, got %d", len(ranges))- }-- // Test without filter (should return all valid)- ranges, err = loadSubIDRanges(tmpFile.Name(), nil)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- // root and user1 are valid. zero has length 0 so skipped. invalid/toolong/short are invalid.- if len(ranges) != 2 {- t.Fatalf("expected 2 ranges, got %d", len(ranges))- }-- // Test missing file - use path under /tmp to reliably get "not exists" vs "permission denied"- ranges, err = loadSubIDRanges("/tmp/nonexistent_subid_test_file_xyz123", nil)- if err != nil {- t.Fatalf("expected no error for nonexistent file, got %v", err)- }- if ranges != nil {- t.Fatal("expected nil ranges for nonexistent file")- }-}--func TestAuthorizePeerEdgeCases(t *testing.T) {- p := &Proxy{- config: &Config{},- }-- if _, err := p.authorizePeer(nil); err == nil {- t.Error("expected error for nil credentials")- }-- p.config.AllowIDMappedRoot = true- // No ranges loaded- if p.isIDMappedRoot(&peerCredentials{uid: 100000, gid: 100000}) {- t.Error("expected isIDMappedRoot to be false when no ranges loaded")- }-- p.idMappedUIDRanges = []idRange{{start: 100000, length: 1000}}- p.idMappedGIDRanges = []idRange{{start: 100000, length: 1000}}-- if !p.isIDMappedRoot(&peerCredentials{uid: 100500, gid: 100500}) {- t.Error("expected isIDMappedRoot to be true for valid range")- }-- if p.isIDMappedRoot(&peerCredentials{uid: 200000, gid: 100500}) {- t.Error("expected isIDMappedRoot to be false for invalid UID")- }-- if p.isIDMappedRoot(&peerCredentials{uid: 100500, gid: 200000}) {- t.Error("expected isIDMappedRoot to be false for invalid GID")- }-}--func TestLoadIDMappingRanges(t *testing.T) {- // We can't easily mock /etc/subuid but we can call it to get coverage- _, _, _ = loadIDMappingRanges([]string{"root"})-}--func TestLoadIDMappingRanges_Error(t *testing.T) {- // Save old paths- oldUID := subUIDPath- oldGID := subGIDPath- defer func() {- subUIDPath = oldUID- subGIDPath = oldGID- }()-- // Point to directory to cause read error- tmpDir := t.TempDir()- subUIDPath = tmpDir- subGIDPath = tmpDir-- _, _, err := loadIDMappingRanges([]string{"root"})- if err == nil {- t.Error("expected error when UID file is a directory")- }-- // Make UID valid (empty file is valid) but GID invalid- uidFile := filepath.Join(tmpDir, "uid")- os.WriteFile(uidFile, []byte("root:100000:65536"), 0644)- subUIDPath = uidFile-- _, _, err = loadIDMappingRanges([]string{"root"})- if err == nil {- t.Error("expected error when GID file is a directory")- }-}--func TestLoadSubIDRanges_ReadError(t *testing.T) {- // Passing a directory as a file path should trigger a read error- dir := t.TempDir()- _, err := loadSubIDRanges(dir, []string{"root"})- if err == nil {- t.Error("expected error when reading a directory")- }-}diff --git a/cmd/pulse-sensor-proxy/capabilities.go b/cmd/pulse-sensor-proxy/capabilities.godeleted file mode 100644index 23960e9a32..0000000000--- a/cmd/pulse-sensor-proxy/capabilities.go+++ /dev/null@@ -1,49 +0,0 @@-package main--import "strings"--// Capability represents a permission bit granted to a peer.-type Capability uint32--const (- CapabilityRead Capability = 1 << iota- CapabilityWrite- CapabilityAdmin- capabilityLegacyAll = CapabilityRead | CapabilityWrite | CapabilityAdmin-)--func (c Capability) Has(flag Capability) bool {- return c&flag == flag-}--func parseCapabilityList(values []string) Capability {- if len(values) == 0 {- return CapabilityRead- }- var caps Capability- for _, raw := range values {- switch strings.ToLower(strings.TrimSpace(raw)) {- case "read":- caps |= CapabilityRead- case "write":- caps |= CapabilityWrite- case "admin":- caps |= CapabilityAdmin- }- }- return caps-}--func capabilityNames(c Capability) []string {- names := make([]string, 0, 3)- if c.Has(CapabilityRead) {- names = append(names, "read")- }- if c.Has(CapabilityWrite) {- names = append(names, "write")- }- if c.Has(CapabilityAdmin) {- names = append(names, "admin")- }- return names-}diff --git a/cmd/pulse-sensor-proxy/capabilities_test.go b/cmd/pulse-sensor-proxy/capabilities_test.godeleted file mode 100644index 3553135b42..0000000000--- a/cmd/pulse-sensor-proxy/capabilities_test.go+++ /dev/null@@ -1,441 +0,0 @@-package main--import (- "testing"-)--func TestCapability_Has(t *testing.T) {- tests := []struct {- name string- cap Capability- flag Capability- expected bool- }{- // Single capability checks- {- name: "read has read",- cap: CapabilityRead,- flag: CapabilityRead,- expected: true,- },- {- name: "read does not have write",- cap: CapabilityRead,- flag: CapabilityWrite,- expected: false,- },- {- name: "read does not have admin",- cap: CapabilityRead,- flag: CapabilityAdmin,- expected: false,- },- {- name: "write has write",- cap: CapabilityWrite,- flag: CapabilityWrite,- expected: true,- },- {- name: "admin has admin",- cap: CapabilityAdmin,- flag: CapabilityAdmin,- expected: true,- },-- // Combined capability checks- {- name: "read+write has read",- cap: CapabilityRead | CapabilityWrite,- flag: CapabilityRead,- expected: true,- },- {- name: "read+write has write",- cap: CapabilityRead | CapabilityWrite,- flag: CapabilityWrite,- expected: true,- },- {- name: "read+write does not have admin",- cap: CapabilityRead | CapabilityWrite,- flag: CapabilityAdmin,- expected: false,- },- {- name: "all capabilities has read",- cap: CapabilityRead | CapabilityWrite | CapabilityAdmin,- flag: CapabilityRead,- expected: true,- },- {- name: "all capabilities has write",- cap: CapabilityRead | CapabilityWrite | CapabilityAdmin,- flag: CapabilityWrite,- expected: true,- },- {- name: "all capabilities has admin",- cap: CapabilityRead | CapabilityWrite | CapabilityAdmin,- flag: CapabilityAdmin,- expected: true,- },-- // Zero capability- {- name: "zero capability does not have read",- cap: 0,- flag: CapabilityRead,- expected: false,- },- {- name: "zero capability does not have write",- cap: 0,- flag: CapabilityWrite,- expected: false,- },-- // Check for combined flags- {- name: "read+write has read+write combined",- cap: CapabilityRead | CapabilityWrite,- flag: CapabilityRead | CapabilityWrite,- expected: true,- },- {- name: "read only does not have read+write combined",- cap: CapabilityRead,- flag: CapabilityRead | CapabilityWrite,- expected: false,- },-- // Legacy all constant- {- name: "legacy all has read",- cap: capabilityLegacyAll,- flag: CapabilityRead,- expected: true,- },- {- name: "legacy all has write",- cap: capabilityLegacyAll,- flag: CapabilityWrite,- expected: true,- },- {- name: "legacy all has admin",- cap: capabilityLegacyAll,- flag: CapabilityAdmin,- expected: true,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := tt.cap.Has(tt.flag)- if got != tt.expected {- t.Errorf("Capability(%d).Has(%d) = %v, want %v", tt.cap, tt.flag, got, tt.expected)- }- })- }-}--func TestParseCapabilityList(t *testing.T) {- tests := []struct {- name string- input []string- expected Capability- }{- // Empty/nil input defaults to read- {- name: "nil slice defaults to read",- input: nil,- expected: CapabilityRead,- },- {- name: "empty slice defaults to read",- input: []string{},- expected: CapabilityRead,- },-- // Single capabilities- {- name: "parse read",- input: []string{"read"},- expected: CapabilityRead,- },- {- name: "parse write",- input: []string{"write"},- expected: CapabilityWrite,- },- {- name: "parse admin",- input: []string{"admin"},- expected: CapabilityAdmin,- },-- // Case insensitivity- {- name: "parse READ uppercase",- input: []string{"READ"},- expected: CapabilityRead,- },- {- name: "parse Write mixed case",- input: []string{"Write"},- expected: CapabilityWrite,- },- {- name: "parse ADMIN uppercase",- input: []string{"ADMIN"},- expected: CapabilityAdmin,- },-- // Whitespace handling- {- name: "parse with leading space",- input: []string{" read"},- expected: CapabilityRead,- },- {- name: "parse with trailing space",- input: []string{"write "},- expected: CapabilityWrite,- },- {- name: "parse with surrounding space",- input: []string{" admin "},- expected: CapabilityAdmin,- },-- // Multiple capabilities- {- name: "parse read and write",- input: []string{"read", "write"},- expected: CapabilityRead | CapabilityWrite,- },- {- name: "parse read and admin",- input: []string{"read", "admin"},- expected: CapabilityRead | CapabilityAdmin,- },- {- name: "parse write and admin",- input: []string{"write", "admin"},- expected: CapabilityWrite | CapabilityAdmin,- },- {- name: "parse all three",- input: []string{"read", "write", "admin"},- expected: CapabilityRead | CapabilityWrite | CapabilityAdmin,- },-- // Duplicate handling (should still work - OR is idempotent)- {- name: "duplicates ignored",- input: []string{"read", "read", "read"},- expected: CapabilityRead,- },- {- name: "duplicates with others",- input: []string{"read", "write", "read"},- expected: CapabilityRead | CapabilityWrite,- },-- // Unknown capabilities ignored- {- name: "unknown capability ignored",- input: []string{"unknown"},- expected: 0,- },- {- name: "unknown with valid",- input: []string{"read", "unknown", "write"},- expected: CapabilityRead | CapabilityWrite,- },- {- name: "empty string ignored",- input: []string{""},- expected: 0,- },- {- name: "whitespace only ignored",- input: []string{" "},- expected: 0,- },-- // Order independence- {- name: "order admin-write-read",- input: []string{"admin", "write", "read"},- expected: CapabilityRead | CapabilityWrite | CapabilityAdmin,- },-- // Mixed case and whitespace combined- {- name: "mixed case and whitespace",- input: []string{" READ ", " Write", "ADMIN "},- expected: CapabilityRead | CapabilityWrite | CapabilityAdmin,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := parseCapabilityList(tt.input)- if got != tt.expected {- t.Errorf("parseCapabilityList(%v) = %d, want %d", tt.input, got, tt.expected)- }- })- }-}--func TestCapabilityNames(t *testing.T) {- tests := []struct {- name string- cap Capability- expected []string- }{- // Single capabilities- {- name: "read only",- cap: CapabilityRead,- expected: []string{"read"},- },- {- name: "write only",- cap: CapabilityWrite,- expected: []string{"write"},- },- {- name: "admin only",- cap: CapabilityAdmin,- expected: []string{"admin"},- },-- // Combined capabilities (order matters: read, write, admin)- {- name: "read and write",- cap: CapabilityRead | CapabilityWrite,- expected: []string{"read", "write"},- },- {- name: "read and admin",- cap: CapabilityRead | CapabilityAdmin,- expected: []string{"read", "admin"},- },- {- name: "write and admin",- cap: CapabilityWrite | CapabilityAdmin,- expected: []string{"write", "admin"},- },- {- name: "all three",- cap: CapabilityRead | CapabilityWrite | CapabilityAdmin,- expected: []string{"read", "write", "admin"},- },-- // Zero capability- {- name: "zero capability returns empty slice",- cap: 0,- expected: []string{},- },-- // Legacy all constant- {- name: "legacy all",- cap: capabilityLegacyAll,- expected: []string{"read", "write", "admin"},- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := capabilityNames(tt.cap)-- if len(got) != len(tt.expected) {- t.Errorf("capabilityNames(%d) returned %d items, want %d: got %v, want %v",- tt.cap, len(got), len(tt.expected), got, tt.expected)- return- }-- for i, name := range got {- if name != tt.expected[i] {- t.Errorf("capabilityNames(%d)[%d] = %q, want %q",- tt.cap, i, name, tt.expected[i])- }- }- })- }-}--// TestCapabilityRoundTrip verifies that parsing and naming are consistent-func TestCapabilityRoundTrip(t *testing.T) {- tests := []struct {- name string- input []string- expect []string- }{- {- name: "single read",- input: []string{"read"},- expect: []string{"read"},- },- {- name: "all capabilities",- input: []string{"read", "write", "admin"},- expect: []string{"read", "write", "admin"},- },- {- name: "reverse order normalizes",- input: []string{"admin", "write", "read"},- expect: []string{"read", "write", "admin"},- },- {- name: "duplicates removed",- input: []string{"read", "read", "write"},- expect: []string{"read", "write"},- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- cap := parseCapabilityList(tt.input)- names := capabilityNames(cap)-- if len(names) != len(tt.expect) {- t.Errorf("round trip %v -> %d -> %v, want %v",- tt.input, cap, names, tt.expect)- return- }-- for i, name := range names {- if name != tt.expect[i] {- t.Errorf("round trip result[%d] = %q, want %q",- i, name, tt.expect[i])- }- }- })- }-}--// TestCapabilityConstants verifies the bit positions are correct-func TestCapabilityConstants(t *testing.T) {- // Verify each capability is a single bit- if CapabilityRead != 1 {- t.Errorf("CapabilityRead = %d, want 1", CapabilityRead)- }- if CapabilityWrite != 2 {- t.Errorf("CapabilityWrite = %d, want 2", CapabilityWrite)- }- if CapabilityAdmin != 4 {- t.Errorf("CapabilityAdmin = %d, want 4", CapabilityAdmin)- }-- // Verify legacy all is the combination of all three- if capabilityLegacyAll != CapabilityRead|CapabilityWrite|CapabilityAdmin {- t.Errorf("capabilityLegacyAll = %d, want %d",- capabilityLegacyAll, CapabilityRead|CapabilityWrite|CapabilityAdmin)- }-}diff --git a/cmd/pulse-sensor-proxy/cleanup.go b/cmd/pulse-sensor-proxy/cleanup.godeleted file mode 100644index 197dcc35c3..0000000000--- a/cmd/pulse-sensor-proxy/cleanup.go+++ /dev/null@@ -1,88 +0,0 @@-package main--import (- "context"- "encoding/json"- "errors"- "fmt"- "os"- "path/filepath"- "time"-- "github.com/rs/zerolog"-)--const cleanupRequestFilename = "cleanup-request.json"--func (p *Proxy) cleanupRequestPath() (string, error) {- workDir := p.workDir- if workDir == "" {- workDir = defaultWorkDir()- }-- if workDir == "" {- return "", errors.New("cleanup working directory not configured")- }-- return filepath.Join(workDir, cleanupRequestFilename), nil-}--func (p *Proxy) handleRequestCleanup(ctx context.Context, req *RPCRequest, logger zerolog.Logger) (interface{}, error) {- cleanupPath, err := p.cleanupRequestPath()- if err != nil {- return nil, err- }-- dir := filepath.Dir(cleanupPath)- if err := os.MkdirAll(dir, 0o750); err != nil {- return nil, fmt.Errorf("ensure cleanup directory: %w", err)- }-- payload := map[string]any{- "requestedAt": time.Now().UTC().Format(time.RFC3339),- }- if req != nil && req.Params != nil {- if host, ok := req.Params["host"].(string); ok && host != "" {- payload["host"] = host- }- if reason, ok := req.Params["reason"].(string); ok && reason != "" {- payload["reason"] = reason- }- }-- data, err := json.Marshal(payload)- if err != nil {- return nil, fmt.Errorf("encode cleanup payload: %w", err)- }-- tmpFile, err := os.CreateTemp(dir, "cleanup-request-*.tmp")- if err != nil {- return nil, fmt.Errorf("prepare cleanup signal: %w", err)- }- tmpName := tmpFile.Name()- if _, err := tmpFile.Write(append(data, '\n')); err != nil {- tmpFile.Close()- os.Remove(tmpName)- return nil, fmt.Errorf("write cleanup payload: %w", err)- }- if err := tmpFile.Chmod(0o600); err != nil {- logger.Warn().Err(err).Str("path", tmpName).Msg("Failed to set cleanup payload permissions")- }- if err := tmpFile.Close(); err != nil {- os.Remove(tmpName)- return nil, fmt.Errorf("close cleanup payload: %w", err)- }-- // Replace any existing request atomically so systemd path units trigger on change.- if err := os.Rename(tmpName, cleanupPath); err != nil {- os.Remove(tmpName)- return nil, fmt.Errorf("activate cleanup payload: %w", err)- }-- logger.Info().- Str("path", cleanupPath).- Interface("payload", payload).- Msg("Cleanup request signalled")-- return map[string]any{"queued": true}, nil-}diff --git a/cmd/pulse-sensor-proxy/cleanup_test.go b/cmd/pulse-sensor-proxy/cleanup_test.godeleted file mode 100644index d6241ca413..0000000000--- a/cmd/pulse-sensor-proxy/cleanup_test.go+++ /dev/null@@ -1,171 +0,0 @@-package main--import (- "context"- "encoding/json"- "os"- "path/filepath"- "runtime"- "testing"- "time"-- "github.com/rs/zerolog"-)--func TestProxy_cleanupRequestPath_UsesConfiguredWorkDir(t *testing.T) {- p := &Proxy{workDir: "/tmp/pulse-sensor-proxy-test"}- got, err := p.cleanupRequestPath()- if err != nil {- t.Fatalf("cleanupRequestPath: %v", err)- }- want := filepath.Join(p.workDir, cleanupRequestFilename)- if got != want {- t.Fatalf("path = %q, want %q", got, want)- }-}--func TestProxy_handleRequestCleanup_WritesValidPayloadAndReplacesExisting(t *testing.T) {- workDir := t.TempDir()- p := &Proxy{workDir: workDir}- logger := zerolog.Nop()-- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)- defer cancel()-- resp, err := p.handleRequestCleanup(ctx, &RPCRequest{- Method: RPCRequestCleanup,- Params: map[string]interface{}{- "host": "pve-1",- "reason": "testing",- },- }, logger)- if err != nil {- t.Fatalf("handleRequestCleanup: %v", err)- }- respMap, ok := resp.(map[string]any)- if !ok {- t.Fatalf("expected map response, got %#v", resp)- }- queued, ok := respMap["queued"].(bool)- if !ok || !queued {- t.Fatalf("expected queued=true response, got %#v", resp)- }-- path, err := p.cleanupRequestPath()- if err != nil {- t.Fatalf("cleanupRequestPath: %v", err)- }-- readPayload := func() map[string]any {- t.Helper()- data, err := os.ReadFile(path)- if err != nil {- t.Fatalf("ReadFile(%s): %v", path, err)- }- var payload map[string]any- if err := json.Unmarshal(data, &payload); err != nil {- t.Fatalf("unmarshal payload: %v", err)- }- return payload- }-- payload := readPayload()- if payload["host"] != "pve-1" {- t.Fatalf("payload host = %#v, want %q", payload["host"], "pve-1")- }- if payload["reason"] != "testing" {- t.Fatalf("payload reason = %#v, want %q", payload["reason"], "testing")- }- if _, ok := payload["requestedAt"].(string); !ok {- t.Fatalf("payload requestedAt missing or not string: %#v", payload["requestedAt"])- }- if ts, ok := payload["requestedAt"].(string); ok {- if _, err := time.Parse(time.RFC3339, ts); err != nil {- t.Fatalf("requestedAt not RFC3339: %q: %v", ts, err)- }- }-- if runtime.GOOS != "windows" {- fi, err := os.Stat(path)- if err != nil {- t.Fatalf("Stat(%s): %v", path, err)- }- if fi.Mode().Perm() != 0o600 {- t.Fatalf("payload file mode = %v, want %v", fi.Mode().Perm(), os.FileMode(0o600))- }- }-- resp, err = p.handleRequestCleanup(ctx, &RPCRequest{- Method: RPCRequestCleanup,- Params: map[string]interface{}{- "host": "pve-1",- "reason": "testing-2",- },- }, logger)- if err != nil {- t.Fatalf("handleRequestCleanup (2): %v", err)- }- respMap, ok = resp.(map[string]any)- if !ok {- t.Fatalf("expected map response (2), got %#v", resp)- }- queued, ok = respMap["queued"].(bool)- if !ok || !queued {- t.Fatalf("expected queued=true response (2), got %#v", resp)- }-- payload2 := readPayload()- if payload2["reason"] != "testing-2" {- t.Fatalf("payload reason after replace = %#v, want %q", payload2["reason"], "testing-2")- }-}--func TestProxy_handleRequestCleanup_NilRequest(t *testing.T) {- p := &Proxy{workDir: t.TempDir()}- _, err := p.handleRequestCleanup(context.Background(), nil, zerolog.Nop())- if err != nil {- t.Fatalf("handleRequestCleanup: %v", err)- }-}--func TestProxy_handleRequestCleanup_MkdirFailure(t *testing.T) {- tmpDir := t.TempDir()- filePath := filepath.Join(tmpDir, "file")- if err := os.WriteFile(filePath, []byte("data"), 0644); err != nil {- t.Fatal(err)- }-- p := &Proxy{workDir: filepath.Join(filePath, "subdir")}- _, err := p.handleRequestCleanup(context.Background(), nil, zerolog.Nop())- if err == nil {- t.Error("expected error due to MkdirAll failure")- }-}--func TestProxy_handleRequestCleanup_ParamsEdgeCases(t *testing.T) {- workDir := t.TempDir()- p := &Proxy{workDir: workDir}- logger := zerolog.Nop()-- // Empty host/reason params- _, err := p.handleRequestCleanup(context.Background(), &RPCRequest{- Params: map[string]interface{}{- "host": "",- "reason": "",- },- }, logger)- if err != nil {- t.Fatal(err)- }-- // Non-string params- _, err = p.handleRequestCleanup(context.Background(), &RPCRequest{- Params: map[string]interface{}{- "host": 123,- "reason": true,- },- }, logger)- if err != nil {- t.Fatal(err)- }-}diff --git a/cmd/pulse-sensor-proxy/config.example.yaml b/cmd/pulse-sensor-proxy/config.example.yamldeleted file mode 100644index 6ebb193695..0000000000--- a/cmd/pulse-sensor-proxy/config.example.yaml+++ /dev/null@@ -1,55 +0,0 @@-# Pulse Sensor Proxy Configuration-# This file is optional. Defaults are safe for most installs; use it when you-# need to override CIDR allow lists, HTTP settings, or rate limits.--# Network configuration-# The installer auto-detects host CIDRs if this is empty.-allowed_source_subnets:- - "127.0.0.1/32"- - "192.168.0.0/24"--# Peer authorization-# Preferred capability-based format (legacy UID/GID lists still work)-allowed_peers:- - uid: 0- capabilities: [read, write, admin] # Host root retains full control- - uid: 100999- capabilities: [read] # Container peer limited to read-only RPCs-allowed_peer_uids: []-allowed_peer_gids: []--# ID-mapped root + namespaced users (LXC)-allow_idmapped_root: true-allowed_idmap_users:- - root--# Logging and limits-log_level: info-metrics_address: "default" # 127.0.0.1:9127 unless set otherwise-read_timeout: 5s-write_timeout: 10s-max_ssh_output_bytes: 1048576 # 1 MiB-require_proxmox_hostkeys: false # Only trust hosts in PVE known_hosts when true--# Allow list persistence (managed by installer/control-plane/CLI)-allowed_nodes_file: "/etc/pulse-sensor-proxy/allowed_nodes.yaml"-strict_node_validation: false # Set true to require allow list entries--# Rate limiting (per calling UID)-rate_limit:- per_peer_interval_ms: 1000 # 1 request per second- per_peer_burst: 5 # Allow burst of 5--# HTTPS mode (for remote nodes)-http_enabled: false-http_listen_addr: "0.0.0.0:8443" # Explicitly IPv4; use [::]:8443 for IPv6-http_tls_cert: "/etc/pulse-sensor-proxy/tls/server.crt"-http_tls_key: "/etc/pulse-sensor-proxy/tls/server.key"-http_auth_token: "" # Populated by installer; keep secret--# Control-plane sync (keeps allowed_nodes.yaml updated automatically)-pulse_control_plane:- url: "https://pulse.example.com:7655"- token_file: "/etc/pulse-sensor-proxy/.pulse-control-token"- refresh_interval: 60- insecure_skip_verify: falsediff --git a/cmd/pulse-sensor-proxy/config.go b/cmd/pulse-sensor-proxy/config.godeleted file mode 100644index d4275fc7ad..0000000000--- a/cmd/pulse-sensor-proxy/config.go+++ /dev/null@@ -1,612 +0,0 @@-package main--import (- "bufio"- "bytes"- "fmt"- "net"- "os"- "regexp"- "strconv"- "strings"- "time"-- "github.com/rs/zerolog/log"- "gopkg.in/yaml.v3"-)--// RateLimitConfig holds rate limiting configuration-type RateLimitConfig struct {- PerPeerIntervalMs int `yaml:"per_peer_interval_ms"` // Milliseconds between requests per peer- PerPeerBurst int `yaml:"per_peer_burst"` // Number of requests allowed in a burst-}--// Config holds proxy configuration-type Config struct {- AllowedSourceSubnets []string `yaml:"allowed_source_subnets"`- MetricsAddress string `yaml:"metrics_address"`- LogLevel string `yaml:"log_level"`- AllowedNodes []string `yaml:"allowed_nodes"`- AllowedNodesFile string `yaml:"allowed_nodes_file"`- StrictNodeValidation bool `yaml:"strict_node_validation"`- ReadTimeout time.Duration `yaml:"read_timeout"`- WriteTimeout time.Duration `yaml:"write_timeout"`- MaxSSHOutputBytes int64 `yaml:"max_ssh_output_bytes"`- RequireProxmoxHostkeys bool `yaml:"require_proxmox_hostkeys"`- AllowedPeers []PeerConfig `yaml:"allowed_peers"`-- AllowIDMappedRoot bool `yaml:"allow_idmapped_root"`- AllowedPeerUIDs []uint32 `yaml:"allowed_peer_uids"`- AllowedPeerGIDs []uint32 `yaml:"allowed_peer_gids"`- AllowedIDMapUsers []string `yaml:"allowed_idmap_users"`-- RateLimit *RateLimitConfig `yaml:"rate_limit,omitempty"`-- // HTTP mode configuration- HTTPEnabled bool `yaml:"http_enabled"` // Enable HTTP server mode- HTTPListenAddr string `yaml:"http_listen_addr"` // Address to listen on (e.g., ":8443")- HTTPTLSCertFile string `yaml:"http_tls_cert"` // Path to TLS certificate- HTTPTLSKeyFile string `yaml:"http_tls_key"` // Path to TLS private key- HTTPAuthToken string `yaml:"http_auth_token"` // Bearer token for authentication-- PulseControlPlane *ControlPlaneConfig `yaml:"pulse_control_plane"`-}--type ControlPlaneConfig struct {- URL string `yaml:"url"`- TokenFile string `yaml:"token_file"`- RefreshIntervalSec int `yaml:"refresh_interval"` // seconds- InsecureSkipVerify bool `yaml:"insecure_skip_verify"`-}--const defaultAllowedNodesFile = "/etc/pulse-sensor-proxy/allowed_nodes.yaml"--// PeerConfig represents a peer entry with capabilities.-type PeerConfig struct {- UID uint32 `yaml:"uid"`- Capabilities []string `yaml:"capabilities"`-}--// loadConfig loads configuration from file and environment variables-func loadConfig(configPath string) (*Config, error) {- cfg := &Config{- AllowIDMappedRoot: true,- AllowedIDMapUsers: []string{"root"},- LogLevel: "info", // Default log level- ReadTimeout: 5 * time.Second,- WriteTimeout: 10 * time.Second,- MaxSSHOutputBytes: 1 * 1024 * 1024, // 1 MiB- }-- // Try to load config file if it exists- if configPath != "" {- if _, err := os.Stat(configPath); err == nil {- data, err := os.ReadFile(configPath)- if err != nil {- return nil, fmt.Errorf("failed to read config file: %w", err)- }-- if sanitized, newData := sanitizeDuplicateAllowedNodesBlocks(configPath, data); sanitized {- data = newData- }-- if err := yaml.Unmarshal(data, cfg); err != nil {- return nil, fmt.Errorf("failed to parse config file: %w", err)- }-- log.Info().- Str("config_file", configPath).- Int("subnet_count", len(cfg.AllowedSourceSubnets)).- Msg("Loaded configuration from file")- }- }-- // Read timeout override- if envReadTimeout := os.Getenv("PULSE_SENSOR_PROXY_READ_TIMEOUT"); envReadTimeout != "" {- if parsed, err := time.ParseDuration(strings.TrimSpace(envReadTimeout)); err != nil {- log.Warn().Str("value", envReadTimeout).Err(err).Msg("Invalid PULSE_SENSOR_PROXY_READ_TIMEOUT value, ignoring")- } else {- cfg.ReadTimeout = parsed- log.Info().Dur("read_timeout", cfg.ReadTimeout).Msg("Configured read timeout from environment")- }- }-- // Write timeout override- if envWriteTimeout := os.Getenv("PULSE_SENSOR_PROXY_WRITE_TIMEOUT"); envWriteTimeout != "" {- if parsed, err := time.ParseDuration(strings.TrimSpace(envWriteTimeout)); err != nil {- log.Warn().Str("value", envWriteTimeout).Err(err).Msg("Invalid PULSE_SENSOR_PROXY_WRITE_TIMEOUT value, ignoring")- } else {- cfg.WriteTimeout = parsed- log.Info().Dur("write_timeout", cfg.WriteTimeout).Msg("Configured write timeout from environment")- }- }-- // Append from environment variable if set- if envSubnets := os.Getenv("PULSE_SENSOR_PROXY_ALLOWED_SUBNETS"); envSubnets != "" {- envList := strings.Split(envSubnets, ",")- cfg.AllowedSourceSubnets = append(cfg.AllowedSourceSubnets, envList...)- log.Info().- Int("env_subnet_count", len(envList)).- Msg("Appended subnets from environment variable")- }-- // Ensure timeouts have sane defaults- if cfg.ReadTimeout <= 0 {- log.Warn().Dur("configured_value", cfg.ReadTimeout).Msg("Read timeout must be positive; using default 5s")- cfg.ReadTimeout = 5 * time.Second- }- if cfg.WriteTimeout <= 0 {- log.Warn().Dur("configured_value", cfg.WriteTimeout).Msg("Write timeout must be positive; using default 10s")- cfg.WriteTimeout = 10 * time.Second- }- if cfg.MaxSSHOutputBytes <= 0 {- log.Warn().Int64("configured_value", cfg.MaxSSHOutputBytes).Msg("max_ssh_output_bytes must be positive; using default 1MiB")- cfg.MaxSSHOutputBytes = 1 * 1024 * 1024- }-- // Allow ID-mapped root override- if envAllowIDMap := os.Getenv("PULSE_SENSOR_PROXY_ALLOW_IDMAPPED_ROOT"); envAllowIDMap != "" {- parsed, err := parseBool(envAllowIDMap)- if err != nil {- log.Warn().- Str("value", envAllowIDMap).- Err(err).- Msg("Invalid PULSE_SENSOR_PROXY_ALLOW_IDMAPPED_ROOT value, ignoring")- } else {- cfg.AllowIDMappedRoot = parsed- log.Info().- Bool("allow_idmapped_root", parsed).- Msg("Configured allow_idmapped_root from environment variable")- }- }-- // Allowed ID map users override- if envIDMapUsers := os.Getenv("PULSE_SENSOR_PROXY_ALLOWED_IDMAP_USERS"); envIDMapUsers != "" {- envList := splitAndTrim(envIDMapUsers)- if len(envList) > 0 {- cfg.AllowedIDMapUsers = envList- log.Info().- Strs("allowed_idmap_users", cfg.AllowedIDMapUsers).- Msg("Configured allowed ID map users from environment")- }- }-- // Allowed peer UID overrides- if envUIDs := os.Getenv("PULSE_SENSOR_PROXY_ALLOWED_PEER_UIDS"); envUIDs != "" {- parsed, err := parseUint32List(envUIDs)- if err != nil {- log.Warn().- Str("value", envUIDs).- Err(err).- Msg("Invalid PULSE_SENSOR_PROXY_ALLOWED_PEER_UIDS value, ignoring")- } else {- cfg.AllowedPeerUIDs = append(cfg.AllowedPeerUIDs, parsed...)- log.Info().- Int("env_uid_count", len(parsed)).- Msg("Appended allowed peer UIDs from environment")- }- }-- // Allowed peer GID overrides- if envGIDs := os.Getenv("PULSE_SENSOR_PROXY_ALLOWED_PEER_GIDS"); envGIDs != "" {- parsed, err := parseUint32List(envGIDs)- if err != nil {- log.Warn().- Str("value", envGIDs).- Err(err).- Msg("Invalid PULSE_SENSOR_PROXY_ALLOWED_PEER_GIDS value, ignoring")- } else {- cfg.AllowedPeerGIDs = append(cfg.AllowedPeerGIDs, parsed...)- log.Info().- Int("env_gid_count", len(parsed)).- Msg("Appended allowed peer GIDs from environment")- }- }-- // Allowed node overrides- if envNodes := os.Getenv("PULSE_SENSOR_PROXY_ALLOWED_NODES"); envNodes != "" {- envList := splitAndTrim(envNodes)- if len(envList) > 0 {- cfg.AllowedNodes = append(cfg.AllowedNodes, envList...)- log.Info().- Int("env_allowed_nodes", len(envList)).- Msg("Appended allowed nodes from environment")- }- }-- if cfg.AllowedNodesFile == "" {- if _, err := os.Stat(defaultAllowedNodesFile); err == nil {- cfg.AllowedNodesFile = defaultAllowedNodesFile- }- }-- if cfg.AllowedNodesFile != "" {- if fileNodes, err := loadAllowedNodesFile(cfg.AllowedNodesFile); err != nil {- log.Warn().- Err(err).- Str("allowed_nodes_file", cfg.AllowedNodesFile).- Msg("Failed to load allowed nodes file")- } else if len(fileNodes) > 0 {- cfg.AllowedNodes = append(cfg.AllowedNodes, fileNodes...)- log.Info().- Str("allowed_nodes_file", cfg.AllowedNodesFile).- Int("allowed_node_count", len(fileNodes)).- Msg("Loaded allowed nodes from file")- }- }-- cfg.AllowedNodes = normalizeNodes(cfg.AllowedNodes)-- // Strict node validation override- if envStrict := os.Getenv("PULSE_SENSOR_PROXY_STRICT_NODE_VALIDATION"); envStrict != "" {- parsed, err := parseBool(envStrict)- if err != nil {- log.Warn().- Str("value", envStrict).- Err(err).- Msg("Invalid PULSE_SENSOR_PROXY_STRICT_NODE_VALIDATION value, ignoring")- } else {- cfg.StrictNodeValidation = parsed- log.Info().- Bool("strict_node_validation", parsed).- Msg("Configured strict node validation from environment")- }- }-- // SSH output limit override- if envMaxSSH := os.Getenv("PULSE_SENSOR_PROXY_MAX_SSH_OUTPUT_BYTES"); envMaxSSH != "" {- if parsed, err := strconv.ParseInt(strings.TrimSpace(envMaxSSH), 10, 64); err != nil {- log.Warn().Str("value", envMaxSSH).Err(err).Msg("Invalid PULSE_SENSOR_PROXY_MAX_SSH_OUTPUT_BYTES value, ignoring")- } else {- cfg.MaxSSHOutputBytes = parsed- log.Info().Int64("max_ssh_output_bytes", cfg.MaxSSHOutputBytes).Msg("Configured max SSH output bytes from environment")- }- }-- // Require Proxmox host keys override- if envReq := os.Getenv("PULSE_SENSOR_PROXY_REQUIRE_PROXMOX_HOSTKEYS"); envReq != "" {- if parsed, err := parseBool(envReq); err != nil {- log.Warn().Str("value", envReq).Err(err).Msg("Invalid PULSE_SENSOR_PROXY_REQUIRE_PROXMOX_HOSTKEYS value, ignoring")- } else {- cfg.RequireProxmoxHostkeys = parsed- log.Info().Bool("require_proxmox_hostkeys", parsed).Msg("Configured Proxmox host key requirement from environment")- }- }-- // Metrics address from environment variable- if envMetrics := os.Getenv("PULSE_SENSOR_PROXY_METRICS_ADDR"); envMetrics != "" {- cfg.MetricsAddress = envMetrics- log.Info().Str("metrics_addr", envMetrics).Msg("Metrics address set from environment")- }-- // Default metrics address if not configured- if cfg.MetricsAddress == "" {- cfg.MetricsAddress = "default" // Will use defaultMetricsAddr- }-- // Parse and validate all subnets- if len(cfg.AllowedSourceSubnets) > 0 {- normalized, err := parseAllowedSubnets(cfg.AllowedSourceSubnets)- if err != nil {- return nil, fmt.Errorf("invalid subnet configuration: %w", err)- }- cfg.AllowedSourceSubnets = normalized- log.Info().- Strs("allowed_subnets", cfg.AllowedSourceSubnets).- Msg("Validated and normalized subnet configuration")- } else {- // Auto-detect if no configuration provided- detected := detectHostCIDRs()- if len(detected) == 0 {- log.Warn().Msg("No allowed_source_subnets configured and no host addresses detected")- } else {- cfg.AllowedSourceSubnets = detected- log.Warn().- Strs("auto_detected_subnets", detected).- Msg("No allowed_source_subnets configured; using detected host addresses (recommended to configure explicitly)")- }- }-- // Log rate limit configuration if provided- if cfg.RateLimit != nil {- log.Info().- Int("per_peer_interval_ms", cfg.RateLimit.PerPeerIntervalMs).- Int("per_peer_burst", cfg.RateLimit.PerPeerBurst).- Msg("Rate limit configuration loaded from config file")- }-- // Log level from environment variable- if envLogLevel := os.Getenv("PULSE_SENSOR_PROXY_LOG_LEVEL"); envLogLevel != "" {- cfg.LogLevel = strings.ToLower(strings.TrimSpace(envLogLevel))- log.Info().Str("log_level", cfg.LogLevel).Msg("Log level set from environment")- }-- // HTTP mode configuration from environment variables- if envHTTPEnabled := os.Getenv("PULSE_SENSOR_PROXY_HTTP_ENABLED"); envHTTPEnabled != "" {- if parsed, err := parseBool(envHTTPEnabled); err != nil {- log.Warn().Str("value", envHTTPEnabled).Err(err).Msg("Invalid PULSE_SENSOR_PROXY_HTTP_ENABLED value, ignoring")- } else {- cfg.HTTPEnabled = parsed- log.Info().Bool("http_enabled", parsed).Msg("HTTP mode enabled from environment")- }- }-- if envHTTPAddr := os.Getenv("PULSE_SENSOR_PROXY_HTTP_ADDR"); envHTTPAddr != "" {- cfg.HTTPListenAddr = strings.TrimSpace(envHTTPAddr)- log.Info().Str("http_addr", cfg.HTTPListenAddr).Msg("HTTP listen address set from environment")- }-- if envHTTPCert := os.Getenv("PULSE_SENSOR_PROXY_HTTP_TLS_CERT"); envHTTPCert != "" {- cfg.HTTPTLSCertFile = strings.TrimSpace(envHTTPCert)- log.Info().Str("tls_cert", cfg.HTTPTLSCertFile).Msg("HTTP TLS cert path set from environment")- }-- if envHTTPKey := os.Getenv("PULSE_SENSOR_PROXY_HTTP_TLS_KEY"); envHTTPKey != "" {- cfg.HTTPTLSKeyFile = strings.TrimSpace(envHTTPKey)- log.Info().Str("tls_key", cfg.HTTPTLSKeyFile).Msg("HTTP TLS key path set from environment")- }-- if envHTTPToken := os.Getenv("PULSE_SENSOR_PROXY_HTTP_AUTH_TOKEN"); envHTTPToken != "" {- cfg.HTTPAuthToken = strings.TrimSpace(envHTTPToken)- log.Info().Msg("HTTP auth token set from environment")- }-- // Validate HTTP configuration if enabled- if cfg.HTTPEnabled {- if cfg.HTTPListenAddr == "" {- // Use 0.0.0.0:8443 explicitly for IPv4 binding.- // Using just ":8443" can result in IPv6-only binding on systems- // with net.ipv6.bindv6only=1 (e.g., some Proxmox 8 configurations).- cfg.HTTPListenAddr = "0.0.0.0:8443"- log.Info().Str("http_addr", cfg.HTTPListenAddr).Msg("Using default HTTP listen address")- }- if cfg.HTTPAuthToken == "" {- return nil, fmt.Errorf("http_enabled=true requires http_auth_token to be configured")- }- if cfg.HTTPTLSCertFile == "" || cfg.HTTPTLSKeyFile == "" {- return nil, fmt.Errorf("http_enabled=true requires both http_tls_cert and http_tls_key")- }- }-- if cfg.PulseControlPlane != nil {- if cfg.PulseControlPlane.TokenFile == "" {- cfg.PulseControlPlane.TokenFile = defaultControlPlaneTokenPath- }- if cfg.PulseControlPlane.RefreshIntervalSec <= 0 {- cfg.PulseControlPlane.RefreshIntervalSec = defaultControlPlaneRefreshSecs- }- }-- return cfg, nil-}--// parseBool returns boolean value for various truthy/falsy strings-func parseBool(raw string) (bool, error) {- switch strings.ToLower(strings.TrimSpace(raw)) {- case "1", "true", "yes", "on":- return true, nil- case "0", "false", "no", "off":- return false, nil- default:- return false, fmt.Errorf("invalid boolean value: %s", raw)- }-}--// parseUint32List parses comma-separated uint32 list-func parseUint32List(raw string) ([]uint32, error) {- var parsed []uint32- parts := splitAndTrim(raw)- for _, part := range parts {- if part == "" {- continue- }- val, err := strconv.ParseUint(part, 10, 32)- if err != nil {- return nil, fmt.Errorf("invalid uint32 %q: %w", part, err)- }- parsed = append(parsed, uint32(val))- }- return parsed, nil-}--// splitAndTrim splits a comma-separated string and trims whitespace-func splitAndTrim(raw string) []string {- parts := strings.Split(raw, ",")- var result []string- for _, part := range parts {- trimmed := strings.TrimSpace(part)- if trimmed != "" {- result = append(result, trimmed)- }- }- return result-}--func normalizeNodes(nodes []string) []string {- seen := make(map[string]struct{})- var result []string- for _, node := range nodes {- trimmed := strings.TrimSpace(node)- if trimmed == "" {- continue- }- key := strings.ToLower(trimmed)- if _, exists := seen[key]; exists {- continue- }- seen[key] = struct{}{}- result = append(result, trimmed)- }- return result-}--func loadAllowedNodesFile(path string) ([]string, error) {- data, err := os.ReadFile(path)- if err != nil {- return nil, err- }-- type wrapper struct {- AllowedNodes []string `yaml:"allowed_nodes"`- }-- var w wrapper- if err := yaml.Unmarshal(data, &w); err == nil && len(w.AllowedNodes) > 0 {- return normalizeNodes(w.AllowedNodes), nil- }-- var list []string- if err := yaml.Unmarshal(data, &list); err == nil && len(list) > 0 {- return normalizeNodes(list), nil- }-- scanner := bufio.NewScanner(bytes.NewReader(data))- var plain []string- for scanner.Scan() {- line := strings.TrimSpace(scanner.Text())- if line == "" || strings.HasPrefix(line, "#") {- continue- }- if strings.HasPrefix(line, "-") {- line = strings.TrimSpace(strings.TrimPrefix(line, "-"))- }- if line != "" {- plain = append(plain, line)- }- }- if err := scanner.Err(); err != nil {- return normalizeNodes(plain), err- }- return normalizeNodes(plain), nil-}--// detectHostCIDRs detects local host IP addresses as /32 (IPv4) or /128 (IPv6) CIDRs-func detectHostCIDRs() []string {- var cidrs []string-- ifaces, err := net.Interfaces()- if err != nil {- log.Warn().Err(err).Msg("Failed to enumerate network interfaces")- return cidrs- }-- for _, iface := range ifaces {- // Skip down or loopback interfaces- if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {- continue- }-- addrs, err := iface.Addrs()- if err != nil {- log.Warn().Str("iface", iface.Name).Err(err).Msg("Address lookup failed")- continue- }-- for _, addr := range addrs {- ipNet, ok := addr.(*net.IPNet)- if !ok {- continue- }-- ip := ipNet.IP- // Skip loopback and link-local addresses- if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {- continue- }-- // Add as /32 for IPv4, /128 for IPv6- if ip.To4() != nil {- cidrs = append(cidrs, ip.String()+"/32")- } else if ip.To16() != nil {- cidrs = append(cidrs, ip.String()+"/128")- }- }- }-- return cidrs-}--var allowedNodesBlockPattern = regexp.MustCompile(`(?m)(?:^[ \t]*#.*\n)*^[ \t]*allowed_nodes:\n(?:^[ \t]+-.*\n?)+`)--func sanitizeDuplicateAllowedNodesBlocks(path string, data []byte) (bool, []byte) {- matches := allowedNodesBlockPattern.FindAllIndex(data, -1)- if len(matches) <= 1 {- return false, data- }-- var buf bytes.Buffer- last := 0- for idx, match := range matches {- start, end := match[0], match[1]- if idx == 0 {- buf.Write(data[last:end])- } else {- buf.Write(data[last:start])- }- last = end- }- buf.Write(data[last:])-- cleaned := buf.Bytes()-- // Phase 2: DO NOT write the file back - that would create an uncoordinated writer- // The sanitizer only fixes the in-memory copy for this startup- // Admins should run `pulse-sensor-proxy config migrate-to-file` to fix the file atomically- if path != "" {- log.Warn().- Str("config_file", path).- Int("removed_duplicate_blocks", len(matches)-1).- Msg("CONFIG SANITIZED (in-memory only) – duplicate allowed_nodes blocks detected; run 'pulse-sensor-proxy config migrate-to-file' to fix the file permanently")- } else {- log.Warn().- Int("removed_duplicate_blocks", len(matches)-1).- Msg("CONFIG SANITIZED – duplicate allowed_nodes blocks detected in-memory – this should not happen with Phase 2 config CLI")- }-- return true, cleaned-}--// parseAllowedSubnets validates and normalizes subnet specifications-func parseAllowedSubnets(cfg []string) ([]string, error) {- seen := make(map[string]struct{})- var normalized []string-- for _, raw := range cfg {- entry := strings.TrimSpace(raw)- if entry == "" {- continue- }-- // Try parsing as CIDR- if _, _, err := net.ParseCIDR(entry); err == nil {- if _, exists := seen[entry]; !exists {- seen[entry] = struct{}{}- normalized = append(normalized, entry)- }- continue- }-- // Try parsing as single IP- if ip := net.ParseIP(entry); ip != nil {- norm := entry + "/32"- if ip.To4() == nil {- norm = entry + "/128"- }- if _, exists := seen[norm]; !exists {- seen[norm] = struct{}{}- normalized = append(normalized, norm)- }- continue- }-- // Invalid format- return nil, fmt.Errorf("invalid subnet or address: %s", entry)- }-- return normalized, nil-}--const (- defaultControlPlaneTokenPath = "/etc/pulse-sensor-proxy/.pulse-control-token"- defaultControlPlaneRefreshSecs = 60-)diff --git a/cmd/pulse-sensor-proxy/config_cmd.go b/cmd/pulse-sensor-proxy/config_cmd.godeleted file mode 100644index d90bf1e8fd..0000000000--- a/cmd/pulse-sensor-proxy/config_cmd.go+++ /dev/null@@ -1,639 +0,0 @@-package main--import (- "fmt"- "os"- "path/filepath"-- "github.com/spf13/cobra"- "golang.org/x/sys/unix"- "gopkg.in/yaml.v3"-)--var (- // Config command flags- configPathFlag string- allowedNodesPathFlag string- mergeNodesFlag []string- replaceMode bool-- // New flags for extended commands- controlPlaneURL string- controlPlaneToken string- controlPlaneRefresh int-- httpEnabled bool- httpAddr string- httpAuthToken string- httpTLSCert string- httpTLSKey string-)--var configCmd = &cobra.Command{- Use: "config",- Short: "Manage sensor proxy configuration",- Long: `Atomic configuration management for pulse-sensor-proxy`,-}--var validateCmd = &cobra.Command{- Use: "validate",- Short: "Validate configuration files",- Long: `Parse and validate config.yaml and allowed_nodes.yaml files`,- RunE: func(cmd *cobra.Command, args []string) error {- cfgPath := configPathFlag- if cfgPath == "" {- cfgPath = defaultConfigPath- }-- // Use loadConfig to parse config properly and get the actual allowed_nodes_file path- cfg, err := loadConfig(cfgPath)- if err != nil {- fmt.Fprintf(os.Stderr, "Config validation failed: %v\n", err)- return err- }-- // Determine allowed_nodes path from config (honors allowed_nodes_file setting)- allowedNodesPath := allowedNodesPathFlag- if allowedNodesPath == "" {- if cfg.AllowedNodesFile != "" {- allowedNodesPath = cfg.AllowedNodesFile- } else {- // Default fallback- allowedNodesPath = filepath.Join(filepath.Dir(cfgPath), "allowed_nodes.yaml")- }- }-- // Check if allowed_nodes.yaml exists and validate it- // Empty lists are allowed (admin may clear for security or cluster relies on IPC validation)- if _, err := os.Stat(allowedNodesPath); err == nil {- if err := validateAllowedNodesFile(allowedNodesPath); err != nil {- fmt.Fprintf(os.Stderr, "Allowed nodes validation failed: %v\n", err)- return err- }- }-- fmt.Println("Configuration valid")- return nil- },-}--var setAllowedNodesCmd = &cobra.Command{- Use: "set-allowed-nodes",- Short: "Atomically update allowed_nodes.yaml",- Long: `Merge or replace allowed nodes with atomic writes and file locking.--Examples:- # Merge new nodes into existing list- pulse-sensor-proxy config set-allowed-nodes --merge 192.168.0.1 --merge node1.local-- # Replace entire list- pulse-sensor-proxy config set-allowed-nodes --replace --merge 192.168.0.1 --merge 192.168.0.2-`,- RunE: func(cmd *cobra.Command, args []string) error {- allowedNodesPath := allowedNodesPathFlag- if allowedNodesPath == "" {- // Default to /etc/pulse-sensor-proxy/allowed_nodes.yaml- allowedNodesPath = "/etc/pulse-sensor-proxy/allowed_nodes.yaml"- }-- // Allow zero nodes when using --replace (admin may want to clear the list)- if len(mergeNodesFlag) == 0 && !replaceMode {- return fmt.Errorf("no nodes specified (use --merge flag, or --replace to clear)")- }-- if err := setAllowedNodes(allowedNodesPath, mergeNodesFlag, replaceMode); err != nil {- fmt.Fprintf(os.Stderr, "Failed to update allowed nodes: %v\n", err)- return err- }-- if replaceMode {- fmt.Printf("Replaced allowed nodes with %d entries\n", len(mergeNodesFlag))- } else {- fmt.Printf("Merged %d nodes into allowed nodes list\n", len(mergeNodesFlag))- }- return nil- },-}--var migrateToFileCmd = &cobra.Command{- Use: "migrate-to-file",- Short: "Migrate inline allowed_nodes to file-based configuration",- Long: `Atomically migrates inline allowed_nodes block from config.yaml to allowed_nodes.yaml.--This command:-- Extracts nodes from inline allowed_nodes block in config.yaml-- Removes the inline block from config.yaml-- Ensures allowed_nodes_file is set in config.yaml-- Writes nodes to allowed_nodes.yaml-- All operations are atomic with file locking--Safe to run multiple times (idempotent).-`,- RunE: func(cmd *cobra.Command, args []string) error {- cfgPath := configPathFlag- if cfgPath == "" {- cfgPath = defaultConfigPath- }-- allowedNodesPath := allowedNodesPathFlag- if allowedNodesPath == "" {- allowedNodesPath = filepath.Join(filepath.Dir(cfgPath), "allowed_nodes.yaml")- }-- migrated, err := migrateInlineToFile(cfgPath, allowedNodesPath)- if err != nil {- fmt.Fprintf(os.Stderr, "Migration failed: %v\n", err)- return err- }-- if migrated {- fmt.Println("Migration complete: inline allowed_nodes moved to file")- }- // Silent success when nothing to migrate (idempotent)- return nil- },-}--var addSubnetCmd = &cobra.Command{- Use: "add-subnet [subnet]",- Short: "Add an allowed source subnet",- Args: cobra.ExactArgs(1),- RunE: func(cmd *cobra.Command, args []string) error {- subnet := args[0]- cfgPath := configPathFlag- if cfgPath == "" {- cfgPath = defaultConfigPath- }-- return updateConfigMap(cfgPath, func(config map[string]interface{}) error {- var subnets []string- if existing, ok := config["allowed_source_subnets"]; ok {- if list, ok := existing.([]interface{}); ok {- for _, item := range list {- if s, ok := item.(string); ok {- subnets = append(subnets, s)- }- }- }- }-- // Check if already exists- for _, s := range subnets {- if s == subnet {- return nil // Already exists- }- }-- subnets = append(subnets, subnet)- config["allowed_source_subnets"] = subnets- return nil- })- },-}--var setControlPlaneCmd = &cobra.Command{- Use: "set-control-plane",- Short: "Configure Pulse control plane connection",- RunE: func(cmd *cobra.Command, args []string) error {- cfgPath := configPathFlag- if cfgPath == "" {- cfgPath = defaultConfigPath- }-- return updateConfigMap(cfgPath, func(config map[string]interface{}) error {- cp := make(map[string]interface{})- if existing, ok := config["pulse_control_plane"]; ok {- if m, ok := existing.(map[string]interface{}); ok {- cp = m- }- }-- if controlPlaneURL != "" {- cp["url"] = controlPlaneURL- }- if controlPlaneToken != "" {- cp["token_file"] = controlPlaneToken- }- if controlPlaneRefresh > 0 {- cp["refresh_interval"] = controlPlaneRefresh- }-- config["pulse_control_plane"] = cp- return nil- })- },-}--var setHTTPCmd = &cobra.Command{- Use: "set-http",- Short: "Configure HTTP mode settings",- RunE: func(cmd *cobra.Command, args []string) error {- cfgPath := configPathFlag- if cfgPath == "" {- cfgPath = defaultConfigPath- }-- return updateConfigMap(cfgPath, func(config map[string]interface{}) error {- if cmd.Flags().Changed("enabled") {- config["http_enabled"] = httpEnabled- }- if httpAddr != "" {- config["http_listen_addr"] = httpAddr- }- if httpAuthToken != "" {- config["http_auth_token"] = httpAuthToken- }- if httpTLSCert != "" {- config["http_tls_cert"] = httpTLSCert- }- if httpTLSKey != "" {- config["http_tls_key"] = httpTLSKey- }- return nil- })- },-}--func init() {- // Add subcommands to config command- configCmd.AddCommand(validateCmd)- configCmd.AddCommand(setAllowedNodesCmd)- configCmd.AddCommand(migrateToFileCmd)- configCmd.AddCommand(addSubnetCmd)- configCmd.AddCommand(setControlPlaneCmd)- configCmd.AddCommand(setHTTPCmd)-- // Validate command flags- validateCmd.Flags().StringVar(&configPathFlag, "config", "", "Path to config.yaml (default: /etc/pulse-sensor-proxy/config.yaml)")- validateCmd.Flags().StringVar(&allowedNodesPathFlag, "allowed-nodes", "", "Path to allowed_nodes.yaml (default: same dir as config)")-- // Set-allowed-nodes command flags- setAllowedNodesCmd.Flags().StringVar(&allowedNodesPathFlag, "allowed-nodes", "", "Path to allowed_nodes.yaml (default: /etc/pulse-sensor-proxy/allowed_nodes.yaml)")- setAllowedNodesCmd.Flags().StringSliceVar(&mergeNodesFlag, "merge", []string{}, "Node to merge (can be specified multiple times)")- setAllowedNodesCmd.Flags().BoolVar(&replaceMode, "replace", false, "Replace entire list instead of merging")-- // Migrate-to-file command flags- migrateToFileCmd.Flags().StringVar(&configPathFlag, "config", "", "Path to config.yaml (default: /etc/pulse-sensor-proxy/config.yaml)")- migrateToFileCmd.Flags().StringVar(&allowedNodesPathFlag, "allowed-nodes", "", "Path to allowed_nodes.yaml (default: same dir as config)")-- // Add-subnet command flags- addSubnetCmd.Flags().StringVar(&configPathFlag, "config", "", "Path to config.yaml")-- // Set-control-plane command flags- setControlPlaneCmd.Flags().StringVar(&configPathFlag, "config", "", "Path to config.yaml")- setControlPlaneCmd.Flags().StringVar(&controlPlaneURL, "url", "", "Control plane URL")- setControlPlaneCmd.Flags().StringVar(&controlPlaneToken, "token-file", "", "Path to token file")- setControlPlaneCmd.Flags().IntVar(&controlPlaneRefresh, "refresh", 0, "Refresh interval in seconds")-- // Set-http command flags- setHTTPCmd.Flags().StringVar(&configPathFlag, "config", "", "Path to config.yaml")- setHTTPCmd.Flags().BoolVar(&httpEnabled, "enabled", false, "Enable HTTP mode")- setHTTPCmd.Flags().StringVar(&httpAddr, "listen-addr", "", "HTTP listen address")- setHTTPCmd.Flags().StringVar(&httpAuthToken, "auth-token", "", "HTTP auth token")- setHTTPCmd.Flags().StringVar(&httpTLSCert, "tls-cert", "", "TLS certificate path")- setHTTPCmd.Flags().StringVar(&httpTLSKey, "tls-key", "", "TLS key path")-- // Add config command to root- rootCmd.AddCommand(configCmd)-}--// updateConfigMap safely updates the config file using a map representation-func updateConfigMap(path string, updateFn func(map[string]interface{}) error) error {- lockPath := path + ".lock"- return withLockedFile(lockPath, func(f *os.File) error {- // Read current config- data, err := os.ReadFile(path)- if err != nil {- if os.IsNotExist(err) {- data = []byte("{}\n")- } else {- return fmt.Errorf("failed to read config: %w", err)- }- }-- // Sanitize duplicate blocks before parsing- _, data = sanitizeDuplicateAllowedNodesBlocks(path, data)-- var config map[string]interface{}- if err := yaml.Unmarshal(data, &config); err != nil {- return fmt.Errorf("failed to parse config: %w", err)- }-- if config == nil {- config = make(map[string]interface{})- }-- // Apply updates- if err := updateFn(config); err != nil {- return err- }-- // Write back- newData, err := yaml.Marshal(config)- if err != nil {- return fmt.Errorf("failed to marshal config: %w", err)- }-- // Preserve header comment if possible (simple heuristic)- header := "# Managed by pulse-sensor-proxy config CLI\n"- finalData := []byte(header + string(newData))-- return atomicWriteFile(path, finalData, 0644)- })-}--// validateAllowedNodesFile parses and validates the allowed_nodes.yaml file-func validateAllowedNodesFile(path string) error {- data, err := os.ReadFile(path)- if err != nil {- return fmt.Errorf("failed to read allowed_nodes file: %w", err)- }-- // Parse YAML - can be either a dict with allowed_nodes key or a list- var result interface{}- if err := yaml.Unmarshal(data, &result); err != nil {- return fmt.Errorf("failed to parse allowed_nodes YAML: %w", err)- }-- // Extract nodes (empty list is valid - admin may clear for security)- // Clusters can also rely on IPC-based validation instead of static allowlists- var nodes []string- switch v := result.(type) {- case map[string]interface{}:- if nodeList, ok := v["allowed_nodes"]; ok {- if list, ok := nodeList.([]interface{}); ok {- for _, item := range list {- if s, ok := item.(string); ok && s != "" {- nodes = append(nodes, s)- }- }- }- }- case []interface{}:- for _, item := range v {- if s, ok := item.(string); ok && s != "" {- nodes = append(nodes, s)- }- }- case nil:- // Empty file is valid- return nil- }-- // Empty list is allowed - don't enforce minimum- return nil-}--// setAllowedNodes atomically updates the allowed_nodes.yaml file with file locking-func setAllowedNodes(path string, newNodes []string, replace bool) error {- // Create directory if it doesn't exist- dir := filepath.Dir(path)- if err := os.MkdirAll(dir, 0755); err != nil {- return fmt.Errorf("failed to create config directory: %w", err)- }-- // Use a separate lock file that persists across renames- lockPath := path + ".lock"- return withLockedFile(lockPath, func(f *os.File) error {- var existing []string-- // Read existing nodes if not in replace mode- if !replace {- if data, err := os.ReadFile(path); err == nil {- existing = extractNodesFromYAML(data)- }- }-- // Merge and deduplicate- merged := normalizeNodes(append(existing, newNodes...))-- // Allow empty lists (admin may want to clear the file)- // Serialize to YAML- output := map[string]interface{}{- "allowed_nodes": merged,- }- data, err := yaml.Marshal(output)- if err != nil {- return fmt.Errorf("failed to marshal YAML: %w", err)- }-- // Add header comment- header := "# Managed by pulse-sensor-proxy config CLI\n# Do not edit manually while service is running\n"- finalData := []byte(header + string(data))-- // Write atomically while holding lock- return atomicWriteFile(path, finalData, 0644)- })-}--// withLockedFile opens a lock file with exclusive locking and runs a callback-//-// IMPORTANT: If future commands need to modify multiple files, use consistent lock ordering-// to avoid deadlocks (e.g., always lock config.yaml.lock before allowed_nodes.yaml.lock)-func withLockedFile(lockPath string, fn func(f *os.File) error) error {- // Open or create the lock file (never deleted, persists across renames)- // Use 0600 to prevent unprivileged users from holding LOCK_EX and DoS'ing the installer- f, err := os.OpenFile(lockPath, os.O_RDWR|os.O_CREATE, 0600)- if err != nil {- return fmt.Errorf("failed to open lock file: %w", err)- }- defer f.Close()-- // Ensure correct permissions even if file already exists with broader perms- if err := f.Chmod(0600); err != nil {- return fmt.Errorf("failed to set lock file permissions: %w", err)- }-- // Acquire exclusive lock- if err := unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {- return fmt.Errorf("failed to acquire file lock: %w", err)- }- defer unix.Flock(int(f.Fd()), unix.LOCK_UN) //nolint:errcheck-- // Run callback while holding lock- return fn(f)-}--// atomicWriteFile writes data to a file atomically using temp file + rename-func atomicWriteFile(path string, data []byte, perm os.FileMode) error {- dir := filepath.Dir(path)-- // Create temp file in same directory- tmp, err := os.CreateTemp(dir, ".tmp-*")- if err != nil {- return fmt.Errorf("failed to create temp file: %w", err)- }- tmpPath := tmp.Name()-- // Clean up temp file on error- defer func() {- if tmpPath != "" {- os.Remove(tmpPath)- }- }()-- // Write data- if _, err := tmp.Write(data); err != nil {- tmp.Close()- return fmt.Errorf("failed to write temp file: %w", err)- }-- // Sync to disk- if err := tmp.Sync(); err != nil {- tmp.Close()- return fmt.Errorf("failed to sync temp file: %w", err)- }-- // Close temp file- if err := tmp.Close(); err != nil {- return fmt.Errorf("failed to close temp file: %w", err)- }-- // Set permissions- if err := os.Chmod(tmpPath, perm); err != nil {- return fmt.Errorf("failed to set permissions: %w", err)- }-- // Atomic rename- if err := os.Rename(tmpPath, path); err != nil {- return fmt.Errorf("failed to rename temp file: %w", err)- }-- // Mark temp file as successfully moved (don't delete in defer)- tmpPath = ""-- // Sync directory to ensure rename is persisted- dirFile, err := os.Open(dir)- if err == nil {- dirFile.Sync() //nolint:errcheck- dirFile.Close()- }-- return nil-}--// extractNodesFromYAML extracts node list from YAML data-func extractNodesFromYAML(data []byte) []string {- var result interface{}- if err := yaml.Unmarshal(data, &result); err != nil {- return nil- }-- var nodes []string- switch v := result.(type) {- case map[string]interface{}:- if nodeList, ok := v["allowed_nodes"]; ok {- if list, ok := nodeList.([]interface{}); ok {- for _, item := range list {- if s, ok := item.(string); ok && s != "" {- nodes = append(nodes, s)- }- }- }- }- case []interface{}:- for _, item := range v {- if s, ok := item.(string); ok && s != "" {- nodes = append(nodes, s)- }- }- }-- return nodes-}--// migrateInlineToFile atomically migrates inline allowed_nodes from config.yaml to allowed_nodes.yaml-// Returns (true, nil) if migration was performed, (false, nil) if nothing to migrate, or (false, err) on error.-func migrateInlineToFile(configPath, allowedNodesPath string) (bool, error) {- configLockPath := configPath + ".lock"- allowedNodesLockPath := allowedNodesPath + ".lock"-- var migrated bool-- // Lock both files in consistent order to prevent deadlocks- // Always lock config.yaml before allowed_nodes.yaml- err := withLockedFile(configLockPath, func(configLock *os.File) error {- return withLockedFile(allowedNodesLockPath, func(allowedNodesLock *os.File) error {- // Read current config- configData, err := os.ReadFile(configPath)- if err != nil {- return fmt.Errorf("failed to read config: %w", err)- }-- // Sanitize duplicate blocks before parsing- _, configData = sanitizeDuplicateAllowedNodesBlocks(configPath, configData)-- // Parse config to extract inline nodes- var config map[string]interface{}- if err := yaml.Unmarshal(configData, &config); err != nil {- return fmt.Errorf("failed to parse config: %w", err)- }-- // Check if inline allowed_nodes exists - this determines if migration is needed- _, hasInlineNodes := config["allowed_nodes"]- _, hasFileRef := config["allowed_nodes_file"]-- // If already using file mode and no inline nodes, nothing to migrate- if !hasInlineNodes && hasFileRef {- return nil- }-- // Extract inline nodes (if any)- var inlineNodes []string- if allowedNodes, ok := config["allowed_nodes"]; ok {- if nodeList, ok := allowedNodes.([]interface{}); ok {- for _, node := range nodeList {- if s, ok := node.(string); ok && s != "" {- inlineNodes = append(inlineNodes, s)- }- }- }- }-- // Mark that migration is being performed- migrated = hasInlineNodes-- // Remove inline allowed_nodes block from config- delete(config, "allowed_nodes")-- // Ensure allowed_nodes_file is set- if _, exists := config["allowed_nodes_file"]; !exists {- config["allowed_nodes_file"] = allowedNodesPath- }-- // Write updated config atomically- newConfigData, err := yaml.Marshal(config)- if err != nil {- return fmt.Errorf("failed to marshal config: %w", err)- }-- if err := atomicWriteFile(configPath, newConfigData, 0644); err != nil {- return fmt.Errorf("failed to write config: %w", err)- }-- // Merge inline nodes with existing file nodes (if any)- var existingNodes []string- if data, err := os.ReadFile(allowedNodesPath); err == nil {- existingNodes = extractNodesFromYAML(data)- }-- // Combine and deduplicate- allNodes := normalizeNodes(append(existingNodes, inlineNodes...))-- // Write allowed_nodes.yaml atomically- output := map[string]interface{}{- "allowed_nodes": allNodes,- }- allowedNodesData, err := yaml.Marshal(output)- if err != nil {- return fmt.Errorf("failed to marshal allowed_nodes: %w", err)- }-- header := "# Managed by pulse-sensor-proxy config CLI\n# Do not edit manually while service is running\n"- finalData := []byte(header + string(allowedNodesData))-- return atomicWriteFile(allowedNodesPath, finalData, 0644)- })- })- return migrated, err-}diff --git a/cmd/pulse-sensor-proxy/config_cmd_test.go b/cmd/pulse-sensor-proxy/config_cmd_test.godeleted file mode 100644index 348e30c67b..0000000000--- a/cmd/pulse-sensor-proxy/config_cmd_test.go+++ /dev/null@@ -1,198 +0,0 @@-package main--import (- "os"- "path/filepath"- "strings"- "testing"-)--func TestAtomicWriteFile(t *testing.T) {- tmpDir := t.TempDir()- file := filepath.Join(tmpDir, "test.txt")- data := []byte("hello world")-- err := atomicWriteFile(file, data, 0644)- if err != nil {- t.Fatalf("atomicWriteFile failed: %v", err)- }-- read, err := os.ReadFile(file)- if err != nil {- t.Fatalf("read failed: %v", err)- }- if string(read) != "hello world" {- t.Errorf("content mismatch: got %s", read)- }-}--func TestValidateAllowedNodesFile(t *testing.T) {- tmpDir := t.TempDir()-- tests := []struct {- name string- content string- wantErr bool- }{- {- name: "valid dict",- content: `-allowed_nodes:- - node1- - node2-`,- wantErr: false,- },- {- name: "valid list",- content: `-- node1-- node2-`,- wantErr: false,- },- {- name: "empty file",- content: "",- wantErr: false,- },- {- name: "empty dict",- content: "allowed_nodes: []",- wantErr: false,- },- {- name: "invalid yaml",- content: ": invalid",- wantErr: true,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- file := filepath.Join(tmpDir, tt.name+".yaml")- err := os.WriteFile(file, []byte(tt.content), 0644)- if err != nil {- t.Fatalf("setup failed: %v", err)- }-- err = validateAllowedNodesFile(file)- if (err != nil) != tt.wantErr {- t.Errorf("validateAllowedNodesFile() error = %v, wantErr %v", err, tt.wantErr)- }- })- }-}--func TestSetAllowedNodes(t *testing.T) {- tmpDir := t.TempDir()- file := filepath.Join(tmpDir, "allowed_nodes.yaml")-- // Initial set- err := setAllowedNodes(file, []string{"node1"}, false)- if err != nil {- t.Fatalf("setAllowedNodes failed: %v", err)- }-- checkContent := func(expected []string) {- data, err := os.ReadFile(file)- if err != nil {- t.Fatalf("read failed: %v", err)- }- // Simple check for presence- content := string(data)- for _, e := range expected {- if !strings.Contains(content, e) {- t.Errorf("expected %s in %s", e, content)- }- }- }-- checkContent([]string{"node1"})-- // Merge- err = setAllowedNodes(file, []string{"node2"}, false)- if err != nil {- t.Fatalf("merge failed: %v", err)- }- checkContent([]string{"node1", "node2"})-- // Replace- err = setAllowedNodes(file, []string{"node3"}, true)- if err != nil {- t.Fatalf("replace failed: %v", err)- }- // node1, node2 should be gone- // Actual verification- data, _ := os.ReadFile(file)- nodesInFile := extractNodesFromYAML(data)- if len(nodesInFile) != 1 || nodesInFile[0] != "node3" {- t.Errorf("expected [node3], got %v", nodesInFile)- }-}--func TestUpdateConfigMap(t *testing.T) {- tmpDir := t.TempDir()- file := filepath.Join(tmpDir, "config.yaml")-- os.WriteFile(file, []byte("key: value\n"), 0644)-- err := updateConfigMap(file, func(m map[string]interface{}) error {- m["new_key"] = "new_value"- return nil- })- if err != nil {- t.Fatalf("updateConfigMap failed: %v", err)- }-- data, _ := os.ReadFile(file)- if !strings.Contains(string(data), "new_key: new_value") {- t.Errorf("update failed, content: %s", string(data))- }-}--func TestMigrateInlineToFile(t *testing.T) {- tmpDir := t.TempDir()- configFile := filepath.Join(tmpDir, "config.yaml")- nodesFile := filepath.Join(tmpDir, "allowed_nodes.yaml")-- // Scenario 1: No inline nodes, migration not needed- os.WriteFile(configFile, []byte("allowed_nodes_file: "+nodesFile+"\n"), 0644)- migrated, err := migrateInlineToFile(configFile, nodesFile)- if err != nil {- t.Fatalf("migrate failed: %v", err)- }- if migrated {- t.Error("expected migrated=false")- }-- // Scenario 2: Inline nodes present- configContent := `-allowed_nodes:- - inline1- - inline2-`- os.WriteFile(configFile, []byte(configContent), 0644)-- migrated, err = migrateInlineToFile(configFile, nodesFile)- if err != nil {- t.Fatalf("migrate failed: %v", err)- }- if !migrated {- t.Error("expected migrated=true")- }-- // Check config file has no allowed_nodes and has allowed_nodes_file- data, _ := os.ReadFile(configFile)- strData := string(data)- if strings.Contains(strData, "allowed_nodes:") && !strings.Contains(strData, "allowed_nodes_file:") {- t.Error("config not updated correctly")- }-- // Check nodes file- nodesData, _ := os.ReadFile(nodesFile)- nodes := extractNodesFromYAML(nodesData)- if len(nodes) != 2 {- t.Errorf("expected 2 nodes, got %d", len(nodes))- }-}diff --git a/cmd/pulse-sensor-proxy/config_test.go b/cmd/pulse-sensor-proxy/config_test.godeleted file mode 100644index 11e94fd1f4..0000000000--- a/cmd/pulse-sensor-proxy/config_test.go+++ /dev/null@@ -1,468 +0,0 @@-package main--import (- "os"- "path/filepath"- "strings"- "testing"- "time"-)--func TestSanitizeDuplicateAllowedNodesBlocks_RemovesExtraBlocks(t *testing.T) {- raw := `-allowed_nodes:- - delly- - minipc--# Cluster nodes (auto-discovered during installation)-# These nodes are allowed to request temperature data when cluster IPC validation is unavailable-allowed_nodes:- - delly- - minipc- - extra-`-- sanitized, out := sanitizeDuplicateAllowedNodesBlocks("", []byte(raw))- if !sanitized {- t.Fatalf("expected sanitization to occur")- }-- result := string(out)- if strings.Count(result, "allowed_nodes:") != 1 {- t.Fatalf("expected only one allowed_nodes block, got %q", result)- }- if strings.Contains(result, "extra") {- t.Fatalf("duplicate entries should be removed, got %q", result)- }- if strings.Contains(result, "Cluster nodes (auto-discovered during installation)") {- t.Fatalf("duplicate comment block should be removed")- }-}--func TestSanitizeDuplicateAllowedNodesBlocks_NoChangeWhenUnique(t *testing.T) {- raw := `-metrics_address: 127.0.0.1:9127-allowed_nodes:- - delly-`- sanitized, out := sanitizeDuplicateAllowedNodesBlocks("", []byte(raw))- if sanitized {- t.Fatalf("unexpected sanitization for unique config")- }- if string(out) != raw {- t.Fatalf("expected config to remain unchanged")- }-}--func TestSanitizeDuplicateAllowedNodesBlocks_WithCommentBlocks(t *testing.T) {- raw := `-allowed_source_subnets:- - 192.168.1.0/24--# Cluster nodes (auto-discovered during installation)-# These nodes are allowed to request temperature data when cluster IPC validation is unavailable-allowed_nodes:- - delly- - minipc--# Cluster nodes (auto-discovered during installation)-# These nodes are allowed to request temperature data when cluster IPC validation is unavailable-allowed_nodes:- - delly- - minipc-`-- sanitized, out := sanitizeDuplicateAllowedNodesBlocks("", []byte(raw))- if !sanitized {- t.Fatalf("expected sanitizer to run for duplicate comment blocks")- }-- result := string(out)- if strings.Count(result, "allowed_nodes:") != 1 {- t.Fatalf("expected a single allowed_nodes block, got %q", result)- }- if strings.Count(result, "# Cluster nodes") != 1 {- t.Fatalf("expected duplicate comments to collapse, got %q", result)- }-}--func TestParseBool(t *testing.T) {- tests := []struct {- name string- input string- expected bool- wantErr bool- }{- // Truthy values- {"true lowercase", "true", true, false},- {"TRUE uppercase", "TRUE", true, false},- {"True mixed", "True", true, false},- {"1", "1", true, false},- {"yes", "yes", true, false},- {"YES", "YES", true, false},- {"on", "on", true, false},- {"ON", "ON", true, false},-- // Falsy values- {"false lowercase", "false", false, false},- {"FALSE uppercase", "FALSE", false, false},- {"False mixed", "False", false, false},- {"0", "0", false, false},- {"no", "no", false, false},- {"NO", "NO", false, false},- {"off", "off", false, false},- {"OFF", "OFF", false, false},-- // Whitespace handling- {"true with leading space", " true", true, false},- {"false with trailing space", "false ", false, false},- {"yes with surrounding spaces", " yes ", true, false},-- // Invalid values- {"invalid string", "maybe", false, true},- {"empty string", "", false, true},- {"numeric 2", "2", false, true},- {"random word", "enabled", false, true},- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result, err := parseBool(tc.input)- if tc.wantErr {- if err == nil {- t.Errorf("parseBool(%q) expected error, got nil", tc.input)- }- return- }- if err != nil {- t.Errorf("parseBool(%q) unexpected error: %v", tc.input, err)- return- }- if result != tc.expected {- t.Errorf("parseBool(%q) = %v, want %v", tc.input, result, tc.expected)- }- })- }-}--func TestParseUint32List(t *testing.T) {- tests := []struct {- name string- input string- expected []uint32- wantErr bool- }{- {"single value", "1000", []uint32{1000}, false},- {"multiple values", "1000,2000,3000", []uint32{1000, 2000, 3000}, false},- {"with spaces", "1000, 2000, 3000", []uint32{1000, 2000, 3000}, false},- {"empty string", "", nil, false},- {"only spaces", " ", nil, false},- {"zero value", "0", []uint32{0}, false},- {"max uint32", "4294967295", []uint32{4294967295}, false},- {"with empty parts", "1000,,2000", []uint32{1000, 2000}, false},- {"negative value", "-1", nil, true},- {"overflow uint32", "4294967296", nil, true},- {"non-numeric", "abc", nil, true},- {"mixed valid invalid", "1000,abc", nil, true},- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result, err := parseUint32List(tc.input)- if tc.wantErr {- if err == nil {- t.Errorf("parseUint32List(%q) expected error, got nil", tc.input)- }- return- }- if err != nil {- t.Errorf("parseUint32List(%q) unexpected error: %v", tc.input, err)- return- }- if len(result) != len(tc.expected) {- t.Errorf("parseUint32List(%q) length = %d, want %d", tc.input, len(result), len(tc.expected))- return- }- for i, v := range result {- if v != tc.expected[i] {- t.Errorf("parseUint32List(%q)[%d] = %d, want %d", tc.input, i, v, tc.expected[i])- }- }- })- }-}--func TestSplitAndTrim(t *testing.T) {- tests := []struct {- name string- input string- expected []string- }{- {"simple comma separated", "a,b,c", []string{"a", "b", "c"}},- {"with spaces", "a, b, c", []string{"a", "b", "c"}},- {"with leading/trailing spaces", " a , b , c ", []string{"a", "b", "c"}},- {"empty string", "", nil},- {"single value", "single", []string{"single"}},- {"empty parts filtered", "a,,b", []string{"a", "b"}},- {"only spaces between commas", "a, ,b", []string{"a", "b"}},- {"all empty parts", ",,", nil},- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := splitAndTrim(tc.input)- if len(result) != len(tc.expected) {- t.Errorf("splitAndTrim(%q) length = %d, want %d", tc.input, len(result), len(tc.expected))- return- }- for i, v := range result {- if v != tc.expected[i] {- t.Errorf("splitAndTrim(%q)[%d] = %q, want %q", tc.input, i, v, tc.expected[i])- }- }- })- }-}--func TestNormalizeNodes(t *testing.T) {- tests := []struct {- name string- input []string- expected []string- }{- {"simple list", []string{"node1", "node2"}, []string{"node1", "node2"}},- {"with whitespace", []string{" node1 ", "node2"}, []string{"node1", "node2"}},- {"deduplicates case-insensitive", []string{"Node1", "NODE1", "node1"}, []string{"Node1"}},- {"preserves original case", []string{"MyNode", "mynode"}, []string{"MyNode"}},- {"filters empty strings", []string{"node1", "", "node2"}, []string{"node1", "node2"}},- {"filters whitespace-only", []string{"node1", " ", "node2"}, []string{"node1", "node2"}},- {"empty input", []string{}, nil},- {"nil input", nil, nil},- {"mixed duplicates", []string{"a", "B", "a", "b", "C"}, []string{"a", "B", "C"}},- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := normalizeNodes(tc.input)- if len(result) != len(tc.expected) {- t.Errorf("normalizeNodes(%v) length = %d, want %d", tc.input, len(result), len(tc.expected))- return- }- for i, v := range result {- if v != tc.expected[i] {- t.Errorf("normalizeNodes(%v)[%d] = %q, want %q", tc.input, i, v, tc.expected[i])- }- }- })- }-}--func TestParseAllowedSubnets(t *testing.T) {- tests := []struct {- name string- input []string- expected []string- wantErr bool- }{- // Valid CIDRs- {"single IPv4 CIDR", []string{"192.168.1.0/24"}, []string{"192.168.1.0/24"}, false},- {"multiple IPv4 CIDRs", []string{"192.168.1.0/24", "10.0.0.0/8"}, []string{"192.168.1.0/24", "10.0.0.0/8"}, false},- {"IPv6 CIDR", []string{"2001:db8::/32"}, []string{"2001:db8::/32"}, false},-- // Single IPs converted to CIDRs- {"single IPv4 converted", []string{"192.168.1.100"}, []string{"192.168.1.100/32"}, false},- {"single IPv6 converted", []string{"2001:db8::1"}, []string{"2001:db8::1/128"}, false},-- // Whitespace handling- {"with whitespace", []string{" 192.168.1.0/24 "}, []string{"192.168.1.0/24"}, false},- {"empty entries filtered", []string{"192.168.1.0/24", "", "10.0.0.0/8"}, []string{"192.168.1.0/24", "10.0.0.0/8"}, false},-- // Deduplication- {"deduplicates exact", []string{"192.168.1.0/24", "192.168.1.0/24"}, []string{"192.168.1.0/24"}, false},- {"deduplicates converted", []string{"192.168.1.100", "192.168.1.100"}, []string{"192.168.1.100/32"}, false},-- // Invalid inputs- {"invalid format", []string{"not-a-subnet"}, nil, true},- {"invalid CIDR", []string{"192.168.1.0/33"}, nil, true},- {"partial valid", []string{"192.168.1.0/24", "invalid"}, nil, true},-- // Empty input- {"empty input", []string{}, nil, false},- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result, err := parseAllowedSubnets(tc.input)- if tc.wantErr {- if err == nil {- t.Errorf("parseAllowedSubnets(%v) expected error, got nil", tc.input)- }- return- }- if err != nil {- t.Errorf("parseAllowedSubnets(%v) unexpected error: %v", tc.input, err)- return- }- if len(result) != len(tc.expected) {- t.Errorf("parseAllowedSubnets(%v) length = %d, want %d; result = %v", tc.input, len(result), len(tc.expected), result)- return- }- for i, v := range result {- if v != tc.expected[i] {- t.Errorf("parseAllowedSubnets(%v)[%d] = %q, want %q", tc.input, i, v, tc.expected[i])- }- }- })- }-}--func TestLoadConfig_Basic(t *testing.T) {- // Non-existent file should just use defaults- cfg, err := loadConfig("/non/existent/config.yaml")- if err != nil {- t.Fatal(err)- }- if cfg.LogLevel != "info" {- t.Errorf("expected default log level info, got %s", cfg.LogLevel)- }-}--func TestLoadConfig_EnvOverrides(t *testing.T) {- t.Setenv("PULSE_SENSOR_PROXY_LOG_LEVEL", "debug")- t.Setenv("PULSE_SENSOR_PROXY_READ_TIMEOUT", "10s")- t.Setenv("PULSE_SENSOR_PROXY_WRITE_TIMEOUT", "20s")- t.Setenv("PULSE_SENSOR_PROXY_ALLOWED_SUBNETS", "10.0.0.0/24,192.168.1.1")- t.Setenv("PULSE_SENSOR_PROXY_MAX_SSH_OUTPUT_BYTES", "2097152")- t.Setenv("PULSE_SENSOR_PROXY_ALLOW_IDMAPPED_ROOT", "false")- t.Setenv("PULSE_SENSOR_PROXY_ALLOWED_IDMAP_USERS", "root,admin")- t.Setenv("PULSE_SENSOR_PROXY_ALLOWED_PEER_UIDS", "1000,1001")- t.Setenv("PULSE_SENSOR_PROXY_ALLOWED_PEER_GIDS", "1000,1001")- t.Setenv("PULSE_SENSOR_PROXY_ALLOWED_NODES", "node1,node2")- t.Setenv("PULSE_SENSOR_PROXY_STRICT_NODE_VALIDATION", "true")- t.Setenv("PULSE_SENSOR_PROXY_REQUIRE_PROXMOX_HOSTKEYS", "true")- t.Setenv("PULSE_SENSOR_PROXY_METRICS_ADDR", "127.0.0.1:9999")-- cfg, err := loadConfig("")- if err != nil {- t.Fatal(err)- }- if cfg.LogLevel != "debug" {- t.Errorf("expected debug log level, got %s", cfg.LogLevel)- }- if cfg.ReadTimeout != 10*time.Second {- t.Errorf("expected 10s read timeout, got %v", cfg.ReadTimeout)- }- if cfg.WriteTimeout != 20*time.Second {- t.Errorf("expected 20s write timeout, got %v", cfg.WriteTimeout)- }- if cfg.MaxSSHOutputBytes != 2097152 {- t.Errorf("expected 2MB max SSH output, got %d", cfg.MaxSSHOutputBytes)- }- if cfg.AllowIDMappedRoot {- t.Error("expected allow_idmapped_root false")- }- if len(cfg.AllowedPeerUIDs) != 2 {- t.Errorf("expected 2 UIDs, got %d", len(cfg.AllowedPeerUIDs))- }- if cfg.MetricsAddress != "127.0.0.1:9999" {- t.Errorf("expected metrics addr 127.0.0.1:9999, got %s", cfg.MetricsAddress)- }-}--func TestLoadAllowedNodesFile(t *testing.T) {- tmpDir := t.TempDir()-- // YAML list format- yamlList := filepath.Join(tmpDir, "list.yaml")- os.WriteFile(yamlList, []byte("- node1\n- node2\n"), 0644)- nodes, err := loadAllowedNodesFile(yamlList)- if err != nil {- t.Fatal(err)- }- if len(nodes) != 2 {- t.Errorf("expected 2 nodes, got %d", len(nodes))- }-- // YAML map format- yamlMap := filepath.Join(tmpDir, "map.yaml")- os.WriteFile(yamlMap, []byte("allowed_nodes:\n - node3\n"), 0644)- nodes, err = loadAllowedNodesFile(yamlMap)- if err != nil {- t.Fatal(err)- }- if len(nodes) != 1 || nodes[0] != "node3" {- t.Errorf("unexpected nodes: %v", nodes)- }-- // Plain text format- plainText := filepath.Join(tmpDir, "plain.txt")- os.WriteFile(plainText, []byte("node4\n# comment\n- node5\n"), 0644)- nodes, err = loadAllowedNodesFile(plainText)- if err != nil {- t.Fatal(err)- }- if len(nodes) != 2 || nodes[1] != "node5" {- t.Errorf("unexpected nodes: %v", nodes)- }-}--func TestLoadConfig_HTTP_Validation(t *testing.T) {- t.Setenv("PULSE_SENSOR_PROXY_HTTP_ENABLED", "true")- t.Setenv("PULSE_SENSOR_PROXY_HTTP_ADDR", ":8443")- t.Setenv("PULSE_SENSOR_PROXY_HTTP_TLS_CERT", "/tmp/cert")- t.Setenv("PULSE_SENSOR_PROXY_HTTP_TLS_KEY", "/tmp/key")- t.Setenv("PULSE_SENSOR_PROXY_HTTP_AUTH_TOKEN", "token")-- cfg, err := loadConfig("")- if err != nil {- t.Fatal(err)- }- if cfg.HTTPListenAddr != ":8443" {- t.Errorf("expected addr :8443, got %s", cfg.HTTPListenAddr)- }-- // Test missing token- t.Setenv("PULSE_SENSOR_PROXY_HTTP_AUTH_TOKEN", "")- _, err = loadConfig("")- if err == nil {- t.Error("expected error for missing HTTP token")- }-- // Test missing cert- t.Setenv("PULSE_SENSOR_PROXY_HTTP_AUTH_TOKEN", "token")- t.Setenv("PULSE_SENSOR_PROXY_HTTP_TLS_CERT", "")- _, err = loadConfig("")- if err == nil {- t.Error("expected error for missing TLS cert")- }-}--func TestDetectHostCIDRs(t *testing.T) {- cidrs := detectHostCIDRs()- // Should at least have some IPs if running in a container with network- if len(cidrs) == 0 {- t.Log("detectHostCIDRs returned no CIDRs (might be expected if no non-loopback IPs)")- }- for _, cidr := range cidrs {- if !strings.Contains(cidr, "/") {- t.Errorf("invalid CIDR: %s", cidr)- }- }-}--func TestLoadConfig_TimeoutValidation(t *testing.T) {- t.Setenv("PULSE_SENSOR_PROXY_READ_TIMEOUT", "0s")- t.Setenv("PULSE_SENSOR_PROXY_WRITE_TIMEOUT", "0s")- t.Setenv("PULSE_SENSOR_PROXY_MAX_SSH_OUTPUT_BYTES", "0")-- cfg, err := loadConfig("")- if err != nil {- t.Fatal(err)- }- if cfg.ReadTimeout <= 0 {- t.Error("expected positive read timeout default")- }- if cfg.WriteTimeout <= 0 {- t.Error("expected positive write timeout default")- }-}diff --git a/cmd/pulse-sensor-proxy/http_server.go b/cmd/pulse-sensor-proxy/http_server.godeleted file mode 100644index e3163d3f90..0000000000--- a/cmd/pulse-sensor-proxy/http_server.go+++ /dev/null@@ -1,394 +0,0 @@-package main--import (- "context"- "crypto/subtle"- "crypto/tls"- "encoding/json"- "fmt"- "net"- "net/http"- "strings"- "time"-- "github.com/rs/zerolog/log"-)--// HTTPServer provides HTTP/HTTPS access to temperature data-type HTTPServer struct {- proxy *Proxy- server *http.Server- config *Config-}--// NewHTTPServer creates a new HTTP server for the proxy-func NewHTTPServer(proxy *Proxy, config *Config) *HTTPServer {- return &HTTPServer{- proxy: proxy,- config: config,- }-}--// Start starts the HTTP server with TLS-func (h *HTTPServer) Start() error {- if !h.config.HTTPEnabled {- return nil- }-- // Validate TLS certificate and key exist- if h.config.HTTPTLSCertFile == "" || h.config.HTTPTLSKeyFile == "" {- return fmt.Errorf("TLS cert and key required for HTTP mode")- }-- mux := http.NewServeMux()-- // Register endpoints- mux.HandleFunc("/temps", h.handleTemperature)- mux.HandleFunc("/health", h.handleHealth)-- // Create TLS config with modern security settings- tlsConfig := &tls.Config{- MinVersion: tls.VersionTLS12,- CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},- PreferServerCipherSuites: true,- // Force HTTP/1.1 because the Pulse backend HTTP client currently expects classic TLS/HTTP semantics.- // HTTP/2 responses from the proxy caused intermittent hangs/timeouts in the backend client,- // so we explicitly disable ALPN advertising h2 for now.- NextProtos: []string{"http/1.1"},- CipherSuites: []uint16{- tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,- tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,- tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,- tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,- },- }-- h.server = &http.Server{- Addr: h.config.HTTPListenAddr,- Handler: h.sourceIPMiddleware(h.rateLimitMiddleware(h.authMiddleware(mux))),- TLSConfig: tlsConfig,- ReadTimeout: h.config.ReadTimeout,- WriteTimeout: h.config.WriteTimeout,- IdleTimeout: 120 * time.Second,- MaxHeaderBytes: 1 << 20, // 1 MB- // Disable HTTP/2 upgrade paths until the backend client stack is hardened for it.- TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),- }-- // Determine network type based on address format- // Use tcp4 for IPv4 addresses to force IPv4-only binding on dual-stack systems- // Some systems (e.g., Proxmox 8 with net.ipv6.bindv6only=1) otherwise bind IPv6-only- network := "tcp"- addr := h.config.HTTPListenAddr- if strings.HasPrefix(addr, "0.0.0.0:") || (len(addr) > 0 && addr[0] >= '0' && addr[0] <= '9' && !strings.Contains(addr, "[")) {- // IPv4 address (starts with digit and no bracket)- network = "tcp4"- } else if strings.HasPrefix(addr, "[") {- // IPv6 address (starts with bracket)- network = "tcp6"- }-- log.Info().- Str("addr", addr).- Str("network", network).- Str("cert", h.config.HTTPTLSCertFile).- Msg("Starting HTTPS server")-- // Create listener explicitly with the correct network type- // This ensures IPv4 addresses bind to IPv4-only sockets- ln, err := net.Listen(network, addr)- if err != nil {- return fmt.Errorf("failed to create listener: %w", err)- }-- go func() {- if err := h.server.ServeTLS(ln, h.config.HTTPTLSCertFile, h.config.HTTPTLSKeyFile); err != nil && err != http.ErrServerClosed {- log.Error().Err(err).Msg("HTTPS server failed")- }- }()-- return nil-}--// Stop gracefully shuts down the HTTP server-func (h *HTTPServer) Stop(ctx context.Context) error {- if h.server == nil {- return nil- }- log.Info().Msg("Shutting down HTTPS server")- return h.server.Shutdown(ctx)-}--// authMiddleware validates Bearer token authentication-func (h *HTTPServer) authMiddleware(next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- // Extract Authorization header- authHeader := r.Header.Get("Authorization")- if authHeader == "" {- h.sendJSONError(w, http.StatusUnauthorized, "missing authorization header")- if h.proxy.audit != nil {- h.proxy.audit.LogHTTPRequest(r.RemoteAddr, r.Method, r.URL.Path, http.StatusUnauthorized, "missing_auth_header")- }- return- }-- // Check Bearer token format- parts := strings.SplitN(authHeader, " ", 2)- if len(parts) != 2 || parts[0] != "Bearer" {- h.sendJSONError(w, http.StatusUnauthorized, "invalid authorization format")- if h.proxy.audit != nil {- h.proxy.audit.LogHTTPRequest(r.RemoteAddr, r.Method, r.URL.Path, http.StatusUnauthorized, "invalid_auth_format")- }- return- }-- // Constant-time token comparison to prevent timing attacks- providedToken := parts[1]- if subtle.ConstantTimeCompare([]byte(providedToken), []byte(h.config.HTTPAuthToken)) != 1 {- h.sendJSONError(w, http.StatusUnauthorized, "invalid token")- if h.proxy.audit != nil {- h.proxy.audit.LogHTTPRequest(r.RemoteAddr, r.Method, r.URL.Path, http.StatusUnauthorized, "invalid_token")- }- return- }-- // Token valid, proceed to next handler- next.ServeHTTP(w, r)- })-}--// sourceIPMiddleware enforces allowed_source_subnets restrictions-func (h *HTTPServer) sourceIPMiddleware(next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- // Extract client IP- clientIP, _, err := net.SplitHostPort(r.RemoteAddr)- if err != nil {- clientIP = r.RemoteAddr- }-- // Parse client IP- ip := net.ParseIP(clientIP)- if ip == nil {- log.Warn().Str("remote_addr", r.RemoteAddr).Msg("Failed to parse client IP")- h.sendJSONError(w, http.StatusForbidden, "invalid source IP")- if h.proxy.audit != nil {- h.proxy.audit.LogHTTPRequest(r.RemoteAddr, r.Method, r.URL.Path, http.StatusForbidden, "invalid_source_ip")- }- return- }-- // Check if IP is in allowed subnets- allowed := false- for _, subnetStr := range h.config.AllowedSourceSubnets {- _, subnet, err := net.ParseCIDR(subnetStr)- if err != nil {- continue- }- if subnet.Contains(ip) {- allowed = true- break- }- }-- if !allowed {- log.Warn().- Str("client_ip", clientIP).- Str("path", r.URL.Path).- Msg("HTTP request from unauthorized source IP")- h.sendJSONError(w, http.StatusForbidden, "source IP not allowed")- if h.proxy.audit != nil {- h.proxy.audit.LogHTTPRequest(r.RemoteAddr, r.Method, r.URL.Path, http.StatusForbidden, "source_ip_not_allowed")- }- return- }-- // IP is allowed, proceed to next handler- next.ServeHTTP(w, r)- })-}--// rateLimitMiddleware applies rate limiting per client IP-func (h *HTTPServer) rateLimitMiddleware(next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- // Extract client IP- clientIP, _, err := net.SplitHostPort(r.RemoteAddr)- if err != nil {- clientIP = r.RemoteAddr- }-- // Create synthetic peer credentials for rate limiting- // Use IP hash as UID for HTTP clients- peerCred := &peerCredentials{- uid: hashIPToUID(clientIP),- gid: 0,- pid: 0,- }-- if h.proxy.rateLimiter == nil {- h.sendJSONError(w, http.StatusServiceUnavailable, "rate limiter not available")- return- }-- // Check rate limit- peer := h.proxy.rateLimiter.identifyPeer(peerCred)- peerLabel := peer.String()- releaseLimiter, limitReason, allowed := h.proxy.rateLimiter.allow(peer)- if !allowed {- log.Warn().- Str("client_ip", clientIP).- Str("reason", limitReason).- Msg("HTTP rate limit exceeded")- if h.proxy.audit != nil {- h.proxy.audit.LogHTTPRequest(r.RemoteAddr, r.Method, r.URL.Path, http.StatusTooManyRequests, "rate_limit_"+limitReason)- }- h.sendJSONError(w, http.StatusTooManyRequests, "rate limit exceeded")- return- }- defer func() {- if releaseLimiter != nil {- releaseLimiter()- }- }()-- // Apply penalty if handler returns error- releaseFn := releaseLimiter- applyPenalty := func(reason string) {- if releaseFn != nil {- releaseFn()- releaseFn = nil- }- h.proxy.rateLimiter.penalize(peerLabel, reason)- }-- // Wrap response writer to detect errors- wrappedWriter := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}- next.ServeHTTP(wrappedWriter, r)-- // Apply penalty for errors- if wrappedWriter.statusCode >= 400 && wrappedWriter.statusCode != http.StatusTooManyRequests {- applyPenalty("http_error")- }- })-}--// handleTemperature handles GET /temps?node=<nodename>-func (h *HTTPServer) handleTemperature(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- h.sendJSONError(w, http.StatusMethodNotAllowed, "method not allowed")- return- }-- // Extract node parameter- nodeName := r.URL.Query().Get("node")- if nodeName == "" {- h.sendJSONError(w, http.StatusBadRequest, "missing 'node' query parameter")- return- }-- // Validate node name- nodeName = strings.TrimSpace(nodeName)- if err := validateNodeName(nodeName); err != nil {- h.sendJSONError(w, http.StatusBadRequest, "invalid node name format")- return- }-- // Validate node against allowlist- ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)- defer cancel()-- if h.proxy.nodeValidator != nil {- if err := h.proxy.nodeValidator.Validate(ctx, nodeName); err != nil {- log.Warn().Err(err).Str("node", nodeName).Msg("Node validation failed")- h.sendJSONError(w, http.StatusForbidden, "node not allowed")- return- }- }-- // Acquire per-node concurrency lock (context-aware to prevent goroutine leaks)- releaseNode, err := h.proxy.nodeGate.acquireContext(ctx, nodeName)- if err != nil {- log.Warn().Err(err).Str("node", nodeName).Msg("Request cancelled while waiting for node lock")- h.sendJSONError(w, http.StatusServiceUnavailable, "request cancelled while waiting for node")- return- }- defer releaseNode()-- // Fetch temperature data via SSH with context timeout- // Use a shorter timeout than the HTTP client to ensure we respond before client timeout- sshCtx, cancel := context.WithTimeout(ctx, 15*time.Second)- defer cancel()-- log.Debug().Str("node", nodeName).Msg("Fetching temperature via SSH (HTTP request)")- tempData, err := h.proxy.getTemperatureViaSSH(sshCtx, nodeName)- if err != nil {- log.Warn().Err(err).Str("node", nodeName).Msg("Failed to get temperatures via SSH")- h.sendJSONError(w, http.StatusInternalServerError, fmt.Sprintf("failed to get temperatures: %v", err))- return- }-- // Return temperature data as JSON- response := map[string]interface{}{- "node": nodeName,- "temperature": tempData,- }-- log.Info().Str("node", nodeName).Msg("Temperature data fetched successfully via HTTP")- h.sendJSON(w, http.StatusOK, response)-- if h.proxy.audit != nil {- h.proxy.audit.LogHTTPRequest(r.RemoteAddr, r.Method, r.URL.Path, http.StatusOK, "temperature_success")- }-}--// handleHealth handles GET /health-func (h *HTTPServer) handleHealth(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- h.sendJSONError(w, http.StatusMethodNotAllowed, "method not allowed")- return- }-- response := map[string]interface{}{- "status": "ok",- "version": Version,- }-- h.sendJSON(w, http.StatusOK, response)-}--// sendJSON sends a JSON response-func (h *HTTPServer) sendJSON(w http.ResponseWriter, statusCode int, data interface{}) {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(statusCode)- if err := json.NewEncoder(w).Encode(data); err != nil {- log.Error().Err(err).Msg("Failed to encode JSON response")- }-}--// sendJSONError sends a JSON error response-func (h *HTTPServer) sendJSONError(w http.ResponseWriter, statusCode int, message string) {- h.sendJSON(w, statusCode, map[string]interface{}{- "error": message,- })-}--// hashIPToUID creates a deterministic UID from an IP address for rate limiting-func hashIPToUID(ip string) uint32 {- // Simple hash function: sum of byte values- var hash uint32- for i := 0; i < len(ip); i++ {- hash = hash*31 + uint32(ip[i])- }- // Ensure it's in a reasonable range for UID- return 100000 + (hash % 900000)-}--// responseWriter wraps http.ResponseWriter to capture status code-type responseWriter struct {- http.ResponseWriter- statusCode int-}--func (rw *responseWriter) WriteHeader(code int) {- rw.statusCode = code- rw.ResponseWriter.WriteHeader(code)-}diff --git a/cmd/pulse-sensor-proxy/http_server_test.go b/cmd/pulse-sensor-proxy/http_server_test.godeleted file mode 100644index 12acf39763..0000000000--- a/cmd/pulse-sensor-proxy/http_server_test.go+++ /dev/null@@ -1,309 +0,0 @@-package main--import (- "context"- "encoding/json"- "fmt"- "net/http"- "net/http/httptest"- "os"- "os/exec"- "path/filepath"- "strings"- "testing"- "time"-- "github.com/rcourtman/pulse-go-rewrite/internal/ssh/knownhosts"-)--func TestHTTPServer_Health(t *testing.T) {- proxy := &Proxy{}- config := &Config{- HTTPEnabled: true,- HTTPAuthToken: "secret-token",- }- server := NewHTTPServer(proxy, config)-- // Test valid health check- req := httptest.NewRequest(http.MethodGet, "/health", nil)- req.Header.Set("Authorization", "Bearer secret-token")- w := httptest.NewRecorder()-- // Apply middleware stack manually or construct the handler chain- handler := server.authMiddleware(http.HandlerFunc(server.handleHealth))- handler.ServeHTTP(w, req)-- if w.Code != http.StatusOK {- t.Errorf("expected status 200, got %d", w.Code)- }-- var resp map[string]interface{}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatal(err)- }- if resp["status"] != "ok" {- t.Errorf("expected status ok, got %v", resp["status"])- }-- // Test invalid method- req = httptest.NewRequest(http.MethodPost, "/health", nil)- req.Header.Set("Authorization", "Bearer secret-token")- w = httptest.NewRecorder()- handler.ServeHTTP(w, req)-- if w.Code != http.StatusMethodNotAllowed {- t.Errorf("expected status 405, got %d", w.Code)- }-}--func TestHTTPServer_AuthMiddleware(t *testing.T) {- proxy := &Proxy{- audit: newAuditLogger(os.DevNull), // avoid nil panic- }- config := &Config{- HTTPAuthToken: "secret",- }- server := NewHTTPServer(proxy, config)-- next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- })- handler := server.authMiddleware(next)-- tests := []struct {- name string- authHeader string- wantCode int- }{- {"MissingHeader", "", http.StatusUnauthorized},- {"InvalidFormat", "Basic user:pass", http.StatusUnauthorized},- {"InvalidToken", "Bearer wrong", http.StatusUnauthorized},- {"ValidToken", "Bearer secret", http.StatusOK},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- req := httptest.NewRequest("GET", "/", nil)- if tt.authHeader != "" {- req.Header.Set("Authorization", tt.authHeader)- }- w := httptest.NewRecorder()- handler.ServeHTTP(w, req)-- if w.Code != tt.wantCode {- t.Errorf("expected code %d, got %d", tt.wantCode, w.Code)- }- })- }-}--func TestHTTPServer_Temperature(t *testing.T) {- // Mock SSH execution- origExec := execCommandFunc- origExecContext := execCommandContextFunc- defer func() {- execCommandFunc = origExec- execCommandContextFunc = origExecContext- }()- mockFn := func(name string, arg ...string) *exec.Cmd {- args := strings.Join(arg, " ")- if strings.Contains(args, "ssh") {- // Return mock sensor JSON- return mockExecCommand(`{"coretemp-isa-0000":{"Package id 0":{"temp1_input": 50.0}}}`)- }- return mockExecCommand("")- }- execCommandFunc = mockFn- execCommandContextFunc = func(ctx context.Context, name string, arg ...string) *exec.Cmd {- return mockFn(name, arg...)- }-- // Mock keyscan to avoid trying actual network keyscan- // But p.getTemperatureViaSSH depends on p.knownHosts being set.-- tmpDir := t.TempDir()- km, _ := knownhosts.NewManager(filepath.Join(tmpDir, "known_hosts"), knownhosts.WithKeyscanFunc(func(ctx context.Context, host string, port int, timeout time.Duration) ([]byte, error) {- return []byte(fmt.Sprintf("%s ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKqy\n", host)), nil- }))- os.WriteFile(filepath.Join(tmpDir, "id_ed25519"), []byte("priv"), 0600)-- proxy := &Proxy{- sshKeyPath: tmpDir,- knownHosts: km,- metrics: NewProxyMetrics("test"),- maxSSHOutputBytes: 1024,- nodeGate: newNodeGate(),- config: &Config{}, // Init config to avoid panic in getTemperatureViaSSH if accessed?- }- // Init node validator- proxy.nodeValidator, _ = newNodeValidator(&Config{}, proxy.metrics)-- config := &Config{- HTTPAuthToken: "secret",- }- server := NewHTTPServer(proxy, config)-- // Test valid request- req := httptest.NewRequest("GET", "/temps?node=valid-node", nil)- w := httptest.NewRecorder()- server.handleTemperature(w, req)-- if w.Code != http.StatusOK {- t.Errorf("expected status 200, got %d body: %s", w.Code, w.Body.String())- }- if !strings.Contains(w.Body.String(), "50.0") {- t.Errorf("expected temp 50.0 in response, got: %s", w.Body.String())- }-- // Test missing node- req = httptest.NewRequest("GET", "/temps", nil)- w = httptest.NewRecorder()- server.handleTemperature(w, req)- if w.Code != http.StatusBadRequest {- t.Errorf("expected 400 for missing node, got %d", w.Code)- }-- // Test invalid node name- req = httptest.NewRequest("GET", "/temps?node=-invalid-", nil)- w = httptest.NewRecorder()- server.handleTemperature(w, req)- if w.Code != http.StatusBadRequest {- t.Errorf("expected 400 for invalid node name, got %d", w.Code)- }-- // Test SSH failure- failMock := func(name string, arg ...string) *exec.Cmd {- args := strings.Join(arg, " ")- if strings.Contains(args, "ssh") {- return errorExecCommand("ssh failed")- }- // Also fail local fallback- if name == "sensors" {- return errorExecCommand("sensors failed")- }- return mockExecCommand("")- }- execCommandFunc = failMock- execCommandContextFunc = func(ctx context.Context, name string, arg ...string) *exec.Cmd {- return failMock(name, arg...)- }- // Need to mock getTemperatureLocal failing too.-- req = httptest.NewRequest("GET", "/temps?node=fail-node", nil)- w = httptest.NewRecorder()- server.handleTemperature(w, req)-- if w.Code != http.StatusInternalServerError {- t.Errorf("expected 500 for ssh failure, got %d", w.Code)- }-}--func TestHTTPServer_SourceIPMiddleware(t *testing.T) {- proxy := &Proxy{- audit: newAuditLogger(os.DevNull),- }- config := &Config{- AllowedSourceSubnets: []string{"192.168.1.0/24", "10.0.0.1/32"},- }- server := NewHTTPServer(proxy, config)-- next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- })- handler := server.sourceIPMiddleware(next)-- tests := []struct {- name string- remoteIP string- wantCode int- }{- {"AllowedSubnet", "192.168.1.10:1234", http.StatusOK},- {"AllowedSingle", "10.0.0.1:5678", http.StatusOK},- {"DeniedIP", "1.2.3.4:1234", http.StatusForbidden},- {"InvalidIP", "invalid-ip", http.StatusForbidden},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- req := httptest.NewRequest("GET", "/", nil)- req.RemoteAddr = tt.remoteIP- w := httptest.NewRecorder()- handler.ServeHTTP(w, req)-- if w.Code != tt.wantCode {- t.Errorf("expected code %d for %s, got %d", tt.wantCode, tt.remoteIP, w.Code)- }- })- }-}--func TestHTTPServer_StartValidation(t *testing.T) {- server := NewHTTPServer(&Proxy{}, &Config{HTTPEnabled: true})- // Missing certs- if err := server.Start(); err == nil {- t.Error("expected error when starting without certs")- }-- server = NewHTTPServer(&Proxy{}, &Config{HTTPEnabled: false})- if err := server.Start(); err != nil {- t.Error("expected no error when HTTP disabled")- }-}--func TestHTTPServer_RateLimiter(t *testing.T) {- proxy := &Proxy{- metrics: NewProxyMetrics("test"),- }- // proxy.rateLimiter must be initialized- proxy.rateLimiter = newRateLimiter(proxy.metrics, nil, nil, nil)-- config := &Config{}- server := NewHTTPServer(proxy, config)-- next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- })- handler := server.rateLimitMiddleware(next)-- req := httptest.NewRequest("GET", "/", nil)- req.RemoteAddr = "1.2.3.4:1234"- w := httptest.NewRecorder()-- handler.ServeHTTP(w, req)- if w.Code != http.StatusOK {- t.Errorf("expected 200, got %d", w.Code)- }-}--func TestHashIPToUID(t *testing.T) {- uid1 := hashIPToUID("192.168.1.1")- uid2 := hashIPToUID("192.168.1.1")- uid3 := hashIPToUID("10.0.0.1")-- if uid1 != uid2 {- t.Error("expected deterministic hash")- }- if uid1 == uid3 {- t.Error("expected different hash for different IPs")- }-}--func TestHTTPServer_Stop(t *testing.T) {- server := NewHTTPServer(&Proxy{}, &Config{})- if err := server.Stop(context.Background()); err != nil {- t.Errorf("Stop failed: %v", err)- }- // Test nil server- s2 := &HTTPServer{}- if err := s2.Stop(context.Background()); err != nil {- t.Errorf("Stop failed for nil server: %v", err)- }-}--func TestResponseWriter(t *testing.T) {- rw := &responseWriter{ResponseWriter: httptest.NewRecorder()}- rw.WriteHeader(http.StatusTeapot)- if rw.statusCode != http.StatusTeapot {- t.Errorf("expected status %d, got %d", http.StatusTeapot, rw.statusCode)- }-}diff --git a/cmd/pulse-sensor-proxy/main.go b/cmd/pulse-sensor-proxy/main.godeleted file mode 100644index 385b309407..0000000000--- a/cmd/pulse-sensor-proxy/main.go+++ /dev/null@@ -1,1235 +0,0 @@-package main--import (- "bufio"- "bytes"- "context"- "crypto/tls"- "encoding/json"- "errors"- "fmt"- "io"- "net"- "net/http"- "os"- "os/signal"- "os/user"- "path/filepath"- "strconv"- "strings"- "syscall"- "time"-- "github.com/rcourtman/pulse-go-rewrite/internal/ssh/knownhosts"- "github.com/rcourtman/pulse-go-rewrite/internal/system"- "github.com/rs/zerolog"- "github.com/rs/zerolog/log"- "github.com/spf13/cobra"- "golang.org/x/sys/unix"-)--// Version information (set at build time with -ldflags)-var (- Version = "dev"- BuildTime = "unknown"- GitCommit = "unknown"-)--const (- defaultSocketPath = "/run/pulse-sensor-proxy/pulse-sensor-proxy.sock"- defaultSSHKeyPath = "/var/lib/pulse-sensor-proxy/ssh"- defaultConfigPath = "/etc/pulse-sensor-proxy/config.yaml"- defaultAuditLogPath = "/var/log/pulse/sensor-proxy/audit.log"- maxRequestBytes = 16 * 1024 // 16 KiB max request size- defaultRunAsUser = "pulse-sensor-proxy"-)--func defaultWorkDir() string {- return "/var/lib/pulse-sensor-proxy"-}--var (- configPath string-)--var rootCmd = &cobra.Command{- Use: "pulse-sensor-proxy",- Short: "Pulse Sensor Proxy - Secure sensor data bridge for containerized Pulse",- Long: `Sensor monitoring proxy that keeps SSH keys on the host and exposes sensor data via unix socket`,- Version: Version,- Run: func(cmd *cobra.Command, args []string) {- runProxy()- },-}--// Variable for testing - can be overridden to mock credential extraction-var extractPeerCredentials = defaultExtractPeerCredentials--// Variables for testing system calls-var (- osGeteuid = os.Geteuid- unixSetgroups = unix.Setgroups- unixSetgid = unix.Setgid- unixSetuid = unix.Setuid-)--// Variable for mocking resolveUserSpec-var (- resolveUserSpecFunc = resolveUserSpec- netListen = net.Listen-)--var versionCmd = &cobra.Command{- Use: "version",- Short: "Print version information",- Run: func(cmd *cobra.Command, args []string) {- fmt.Printf("pulse-sensor-proxy %s\n", Version)- if BuildTime != "unknown" {- fmt.Printf("Built: %s\n", BuildTime)- }- if GitCommit != "unknown" {- fmt.Printf("Commit: %s\n", GitCommit)- }- },-}--var keysCmd = &cobra.Command{- Use: "keys",- Short: "Print SSH public keys",- Run: func(cmd *cobra.Command, args []string) {- sshDir := os.Getenv("PULSE_SENSOR_PROXY_SSH_DIR")- if sshDir == "" {- sshDir = defaultSSHKeyPath- }-- pubKeyPath := filepath.Join(sshDir, "id_ed25519.pub")- pubKeyBytes, err := os.ReadFile(pubKeyPath)- if err != nil {- // Try to find the key in the working directory as fallback- if wd, wdErr := os.Getwd(); wdErr == nil {- localPath := filepath.Join(wd, "id_ed25519.pub")- if localBytes, localErr := os.ReadFile(localPath); localErr == nil {- pubKeyBytes = localBytes- } else {- fmt.Fprintf(os.Stderr, "Failed to read public key from %s: %v\n", pubKeyPath, err)- os.Exit(1)- }- } else {- fmt.Fprintf(os.Stderr, "Failed to read public key from %s: %v\n", pubKeyPath, err)- os.Exit(1)- }- }- pubKey := strings.TrimSpace(string(pubKeyBytes))-- fmt.Printf("Proxy Public Key: %s\n", pubKey)- fmt.Printf("Sensors Public Key: %s\n", pubKey)- },-}--func init() {- rootCmd.AddCommand(versionCmd)- rootCmd.AddCommand(keysCmd)- rootCmd.PersistentFlags().StringVar(&configPath, "config", "", "Path to configuration file (default: /etc/pulse-sensor-proxy/config.yaml)")-}--func main() {- if err := rootCmd.Execute(); err != nil {- fmt.Fprintf(os.Stderr, "Error: %v\n", err)- os.Exit(1)- }-}--// parseLogLevel converts a string log level to zerolog.Level-func parseLogLevel(levelStr string) zerolog.Level {- switch strings.ToLower(strings.TrimSpace(levelStr)) {- case "trace":- return zerolog.TraceLevel- case "debug":- return zerolog.DebugLevel- case "info":- return zerolog.InfoLevel- case "warn", "warning":- return zerolog.WarnLevel- case "error":- return zerolog.ErrorLevel- case "fatal":- return zerolog.FatalLevel- case "panic":- return zerolog.PanicLevel- case "disabled", "none":- return zerolog.Disabled- default:- log.Warn().Str("level", levelStr).Msg("Unknown log level, defaulting to info")- return zerolog.InfoLevel- }-}--type userSpec struct {- name string- uid int- gid int- groups []int- home string-}--func dropPrivileges(username string) (*userSpec, error) {- if username == "" {- return nil, nil- }-- if osGeteuid() != 0 {- return nil, nil- }-- spec, err := resolveUserSpecFunc(username)- if err != nil {- return nil, err- }-- if len(spec.groups) == 0 {- spec.groups = []int{spec.gid}- }-- if err := unixSetgroups(spec.groups); err != nil {- return nil, fmt.Errorf("setgroups: %w", err)- }- if err := unixSetgid(spec.gid); err != nil {- return nil, fmt.Errorf("setgid: %w", err)- }- if err := unixSetuid(spec.uid); err != nil {- return nil, fmt.Errorf("setuid: %w", err)- }-- if spec.home != "" {- _ = os.Setenv("HOME", spec.home)- }- if spec.name != "" {- _ = os.Setenv("USER", spec.name)- _ = os.Setenv("LOGNAME", spec.name)- }-- return spec, nil-}--func resolveUserSpec(username string) (*userSpec, error) {- u, err := user.Lookup(username)- if err == nil {- uid, err := strconv.Atoi(u.Uid)- if err != nil {- return nil, fmt.Errorf("parse uid %q: %w", u.Uid, err)- }- gid, err := strconv.Atoi(u.Gid)- if err != nil {- return nil, fmt.Errorf("parse gid %q: %w", u.Gid, err)- }-- var groups []int- if gids, err := u.GroupIds(); err == nil {- for _, g := range gids {- if gidVal, convErr := strconv.Atoi(g); convErr == nil {- groups = append(groups, gidVal)- }- }- }-- if len(groups) == 0 {- groups = []int{gid}- }-- return &userSpec{- name: u.Username,- uid: uid,- gid: gid,- groups: groups,- home: u.HomeDir,- }, nil- }-- fallbackSpec, fallbackErr := lookupUserFromPasswd(username)- if fallbackErr == nil {- return fallbackSpec, nil- }-- return nil, fmt.Errorf("lookup user %q failed: %v (fallback: %w)", username, err, fallbackErr)-}--// Variable for testing-var passwdPath = "/etc/passwd"--func lookupUserFromPasswd(username string) (*userSpec, error) {- f, err := os.Open(passwdPath)- if err != nil {- return nil, fmt.Errorf("open %s: %w", passwdPath, err)- }- defer f.Close()-- scanner := bufio.NewScanner(f)- for scanner.Scan() {- line := scanner.Text()- if strings.HasPrefix(line, "#") {- continue- }-- fields := strings.Split(line, ":")- if len(fields) < 7 {- continue- }- if fields[0] != username {- continue- }-- uid, err := strconv.Atoi(fields[2])- if err != nil {- return nil, fmt.Errorf("parse uid %q: %w", fields[2], err)- }- gid, err := strconv.Atoi(fields[3])- if err != nil {- return nil, fmt.Errorf("parse gid %q: %w", fields[3], err)- }-- return &userSpec{- name: fields[0],- uid: uid,- gid: gid,- groups: []int{gid},- home: fields[5],- }, nil- }-- if err := scanner.Err(); err != nil {- return nil, fmt.Errorf("scan /etc/passwd: %w", err)- }-- return nil, fmt.Errorf("user %q not found in /etc/passwd", username)-}--// Proxy manages the temperature monitoring proxy-type Proxy struct {- socketPath string- sshKeyPath string- workDir string- knownHosts knownhosts.Manager- listener net.Listener- rateLimiter *rateLimiter- nodeGate *nodeGate- router map[string]handlerFunc- config *Config- metrics *ProxyMetrics- audit *auditLogger- nodeValidator *nodeValidator- readTimeout time.Duration- writeTimeout time.Duration- maxSSHOutputBytes int64- controlPlaneCfg *ControlPlaneConfig- controlPlaneToken string- controlPlaneCancel context.CancelFunc-- allowedPeerUIDs map[uint32]struct{}- allowedPeerGIDs map[uint32]struct{}- peerCapabilities map[uint32]Capability- idMappedUIDRanges []idRange- idMappedGIDRanges []idRange-}--type contextKey int--const (- contextKeyPeerCapabilities contextKey = iota + 1-)--func withPeerCapabilities(ctx context.Context, caps Capability) context.Context {- return context.WithValue(ctx, contextKeyPeerCapabilities, caps)-}--func peerCapabilitiesFromContext(ctx context.Context) Capability {- if ctx == nil {- return 0- }- if value := ctx.Value(contextKeyPeerCapabilities); value != nil {- if caps, ok := value.(Capability); ok {- return caps- }- }- return 0-}--// RPC request types-const (- RPCEnsureClusterKeys = "ensure_cluster_keys"- RPCRegisterNodes = "register_nodes"- RPCGetTemperature = "get_temperature"- RPCGetStatus = "get_status"- RPCRequestCleanup = "request_cleanup"-)--// Privileged RPC methods that require host-level access (not accessible from containers)-var privilegedMethods = map[string]bool{- RPCEnsureClusterKeys: true, // SSH key distribution- RPCRegisterNodes: true, // Node registration- RPCRequestCleanup: true, // Cleanup operations-}--// RPCRequest represents a request from Pulse-type RPCRequest struct {- CorrelationID string `json:"correlation_id,omitempty"`- Method string `json:"method"`- Params map[string]interface{} `json:"params"`-}--// RPCResponse represents a response to Pulse-type RPCResponse struct {- CorrelationID string `json:"correlation_id,omitempty"`- Success bool `json:"success"`- Data interface{} `json:"data,omitempty"`- Error string `json:"error,omitempty"`-}--// handlerFunc is the signature for RPC method handlers-type handlerFunc func(ctx context.Context, req *RPCRequest, logger zerolog.Logger) (interface{}, error)--func runProxy() {- // Initialize logger with default level (will be configured after loading config)- zerolog.TimeFieldFormat = zerolog.TimeFormatUnix- log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})-- socketPath := os.Getenv("PULSE_SENSOR_PROXY_SOCKET")- if socketPath == "" {- socketPath = defaultSocketPath- }-- sshKeyPath := os.Getenv("PULSE_SENSOR_PROXY_SSH_DIR")- if sshKeyPath == "" {- sshKeyPath = defaultSSHKeyPath- }-- // Load configuration- // Priority: --config flag > PULSE_SENSOR_PROXY_CONFIG env > default path- cfgPath := configPath // from flag- if cfgPath == "" {- cfgPath = os.Getenv("PULSE_SENSOR_PROXY_CONFIG")- }- if cfgPath == "" {- cfgPath = defaultConfigPath- }-- cfg, err := loadConfig(cfgPath)- if err != nil {- log.Fatal().Err(err).Msg("Failed to load configuration")- }-- // Apply configured log level- level := parseLogLevel(cfg.LogLevel)- zerolog.SetGlobalLevel(level)-- runAsUser := os.Getenv("PULSE_SENSOR_PROXY_USER")- if runAsUser == "" {- runAsUser = defaultRunAsUser- }-- if spec, err := dropPrivileges(runAsUser); err != nil {- log.Fatal().Err(err).Str("user", runAsUser).Msg("Failed to drop privileges")- } else if spec != nil {- log.Info().- Str("user", spec.name).- Int("uid", spec.uid).- Int("gid", spec.gid).- Msg("Running as unprivileged user")- }-- auditPath := os.Getenv("PULSE_SENSOR_PROXY_AUDIT_LOG")- if auditPath == "" {- auditPath = defaultAuditLogPath- }-- // Initialize audit logger with automatic fallback to stderr if file is unavailable- auditLogger := newAuditLogger(auditPath)- defer auditLogger.Close()-- // Initialize metrics- metrics := NewProxyMetrics(Version)-- nodeValidator, err := newNodeValidator(cfg, metrics)- if err != nil {- log.Fatal().Err(err).Msg("Failed to initialize node validator")- }-- log.Info().- Str("socket", socketPath).- Str("ssh_key_dir", sshKeyPath).- Str("config_path", cfgPath).- Str("audit_log", auditPath).- Str("log_level", cfg.LogLevel).- Str("version", Version).- Msg("Starting pulse-sensor-proxy")-- // Warn if running inside a container - this is an unsupported configuration- // Container environments cannot complete SSH workflows, causing [preauth] log floods- if system.InContainer() && os.Getenv("PULSE_SENSOR_PROXY_SUPPRESS_CONTAINER_WARNING") != "true" {- log.Warn().Msg("pulse-sensor-proxy is running inside a container - this is unsupported and will cause SSH [preauth] log floods. Install on the Proxmox host instead. See docs/TEMPERATURE_MONITORING.md for setup instructions. Set PULSE_SENSOR_PROXY_SUPPRESS_CONTAINER_WARNING=true to suppress this warning.")- }-- knownHostsManager, err := knownhosts.NewManager(filepath.Join(sshKeyPath, "known_hosts"))- if err != nil {- log.Fatal().Err(err).Msg("Failed to initialize known hosts manager")- }-- proxy := &Proxy{- socketPath: socketPath,- sshKeyPath: sshKeyPath,- knownHosts: knownHostsManager,- nodeGate: newNodeGate(),- config: cfg,- metrics: metrics,- audit: auditLogger,- nodeValidator: nodeValidator,- readTimeout: cfg.ReadTimeout,- writeTimeout: cfg.WriteTimeout,- maxSSHOutputBytes: cfg.MaxSSHOutputBytes,- controlPlaneCfg: cfg.PulseControlPlane,- }-- if wd, err := os.Getwd(); err == nil {- proxy.workDir = wd- } else {- log.Warn().Err(err).Msg("Failed to determine working directory; using default")- proxy.workDir = defaultWorkDir()- }-- if err := proxy.initAuthRules(); err != nil {- log.Fatal().Err(err).Msg("Failed to initialize authentication rules")- }-- proxy.rateLimiter = newRateLimiter(metrics, cfg.RateLimit, proxy.idMappedUIDRanges, proxy.idMappedGIDRanges)-- // Register RPC method handlers- proxy.router = map[string]handlerFunc{- RPCGetStatus: proxy.handleGetStatusV2,- RPCEnsureClusterKeys: proxy.handleEnsureClusterKeysV2,- RPCRegisterNodes: proxy.handleRegisterNodesV2,- RPCGetTemperature: proxy.handleGetTemperatureV2,- RPCRequestCleanup: proxy.handleRequestCleanup,- }-- if err := proxy.Start(); err != nil {- log.Fatal().Err(err).Msg("Failed to start proxy")- }- proxy.startControlPlaneSync()-- // Start HTTP server if enabled- var httpServer *HTTPServer- if cfg.HTTPEnabled {- httpServer = NewHTTPServer(proxy, cfg)- if err := httpServer.Start(); err != nil {- log.Fatal().Err(err).Msg("Failed to start HTTP server")- }- }-- // Start metrics server- if err := metrics.Start(cfg.MetricsAddress); err != nil {- log.Fatal().Err(err).Msg("Failed to start metrics server")- }-- // Setup signal handlers- sigChan := make(chan os.Signal, 1)- signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)-- <-sigChan- log.Info().Msg("Shutting down proxy...")-- // Shutdown HTTP server if running- if httpServer != nil {- shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)- defer cancel()- if err := httpServer.Stop(shutdownCtx); err != nil {- log.Error().Err(err).Msg("Error shutting down HTTP server")- }- }-- proxy.Stop()- if proxy.rateLimiter != nil {- proxy.rateLimiter.shutdown()- }- metrics.Shutdown(context.Background())- log.Info().Msg("Proxy stopped")-}--// Start initializes and starts the proxy-func (p *Proxy) Start() error {- // Create SSH key directory if it doesn't exist- if err := os.MkdirAll(p.sshKeyPath, 0700); err != nil {- return fmt.Errorf("failed to create SSH key directory: %w", err)- }-- // Ensure SSH keypair exists- if err := p.ensureSSHKeypair(); err != nil {- return fmt.Errorf("failed to ensure SSH keypair: %w", err)- }-- // Remove existing socket if it exists- if err := os.RemoveAll(p.socketPath); err != nil {- return fmt.Errorf("failed to remove existing socket: %w", err)- }-- // Create socket directory if needed- socketDir := filepath.Dir(p.socketPath)- if err := os.MkdirAll(socketDir, 0755); err != nil {- return fmt.Errorf("failed to create socket directory: %w", err)- }-- // Create unix socket listener- listener, err := netListen("unix", p.socketPath)- if err != nil {- return fmt.Errorf("failed to create unix socket: %w", err)- }- p.listener = listener-- // Set liberal socket permissions; SO_PEERCRED enforces auth- if err := os.Chmod(p.socketPath, 0666); err != nil {- log.Warn().Err(err).Msg("Failed to set socket permissions")- }-- log.Info().Str("socket", p.socketPath).Msg("Unix socket ready")-- // Start accepting connections- go p.acceptConnections()-- return nil-}--// Stop shuts down the proxy-func (p *Proxy) Stop() {- if p.controlPlaneCancel != nil {- p.controlPlaneCancel()- }- if p.listener != nil {- p.listener.Close()- os.Remove(p.socketPath)- }-}--func (p *Proxy) startControlPlaneSync() {- if p.controlPlaneCfg == nil || strings.TrimSpace(p.controlPlaneCfg.URL) == "" {- return- }-- tokenBytes, err := os.ReadFile(p.controlPlaneCfg.TokenFile)- if err != nil {- log.Warn().Err(err).Str("token_file", p.controlPlaneCfg.TokenFile).Msg("Control plane token unavailable; skipping sync")- return- }- token := strings.TrimSpace(string(tokenBytes))- if token == "" {- log.Warn().Str("token_file", p.controlPlaneCfg.TokenFile).Msg("Control plane token is empty; skipping sync")- return- }-- ctx, cancel := context.WithCancel(context.Background())- p.controlPlaneToken = token- p.controlPlaneCancel = cancel- go p.controlPlaneLoop(ctx)- log.Info().- Str("url", p.controlPlaneCfg.URL).- Int("refresh_interval", p.controlPlaneCfg.RefreshIntervalSec).- Msg("Control plane synchronization enabled")-}--func (p *Proxy) controlPlaneLoop(ctx context.Context) {- refresh := time.Duration(p.controlPlaneCfg.RefreshIntervalSec) * time.Second- if refresh <= 0 {- refresh = time.Duration(defaultControlPlaneRefreshSecs) * time.Second- }-- client := &http.Client{Timeout: 10 * time.Second}- if p.controlPlaneCfg.InsecureSkipVerify {- client.Transport = &http.Transport{- TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec- }- }-- for {- if err := p.fetchAuthorizedNodes(client); err != nil {- log.Warn().Err(err).Msg("Control plane sync failed")- }-- select {- case <-ctx.Done():- return- case <-time.After(refresh):- }- }-}--func (p *Proxy) fetchAuthorizedNodes(client *http.Client) error {- cfg := p.controlPlaneCfg- if cfg == nil {- return nil- }-- req, err := http.NewRequest(http.MethodGet, strings.TrimRight(cfg.URL, "/")+"/api/temperature-proxy/authorized-nodes", nil)- if err != nil {- return err- }- req.Header.Set("X-Proxy-Token", p.controlPlaneToken)-- resp, err := client.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))- return fmt.Errorf("control plane responded %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))- }-- var payload struct {- Nodes []struct {- Name string `json:"name"`- IP string `json:"ip"`- } `json:"nodes"`- Hash string `json:"hash"`- RefreshInterval int `json:"refresh_interval"`- GeneratedAt time.Time `json:"generated_at"`- }-- if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {- return fmt.Errorf("decode authorized-nodes response: %w", err)- }-- if payload.RefreshInterval > 0 && cfg.RefreshIntervalSec != payload.RefreshInterval {- cfg.RefreshIntervalSec = payload.RefreshInterval- }-- var entries []string- for _, node := range payload.Nodes {- if node.Name != "" {- entries = append(entries, node.Name)- }- if node.IP != "" {- entries = append(entries, node.IP)- }- }-- if len(entries) == 0 {- return errors.New("authorized-nodes response empty")- }-- p.nodeValidator.UpdateAllowlist(entries)- return nil-}--// acceptConnections handles incoming socket connections-func (p *Proxy) acceptConnections() {- for {- conn, err := p.listener.Accept()- if err != nil {- // Check if listener was closed- if opErr, ok := err.(*net.OpError); ok && opErr.Err.Error() == "use of closed network connection" {- return- }- log.Error().Err(err).Msg("Failed to accept connection")- continue- }-- go p.handleConnection(conn)- }-}--// handleConnection processes a single RPC request with full validation and throttling-func (p *Proxy) handleConnection(conn net.Conn) {- defer conn.Close()-- remoteAddr := conn.RemoteAddr().String()-- // Track concurrent requests- p.metrics.queueDepth.Inc()- defer p.metrics.queueDepth.Dec()-- // Start timing for latency metrics- startTime := time.Now()-- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)- defer cancel()-- // Enforce read deadline to prevent hung connections- readDeadline := p.readTimeout- if readDeadline <= 0 {- readDeadline = 5 * time.Second- }- if err := conn.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {- log.Warn().Err(err).Msg("Failed to set read deadline")- }-- // Extract and verify peer credentials- cred, err := extractPeerCredentials(conn)- if err != nil {- log.Warn().Err(err).Msg("Peer credentials unavailable")- if p.audit != nil {- p.audit.LogConnectionDenied("", nil, remoteAddr, "peer_credentials_unavailable")- }- p.sendErrorV2(conn, "unauthorized", "")- return- }-- peerCaps, err := p.authorizePeer(cred)- if err != nil {- log.Warn().- Err(err).- Uint32("uid", cred.uid).- Uint32("gid", cred.gid).- Msg("Peer authorization failed")- if p.audit != nil {- p.audit.LogConnectionDenied("", cred, remoteAddr, err.Error())- }- p.sendErrorV2(conn, "unauthorized", "")- return- }-- if p.audit != nil {- p.audit.LogConnectionAccepted("", cred, remoteAddr)- }-- if p.rateLimiter == nil {- log.Error().Msg("Rate limiter not initialized; rejecting connection")- p.sendErrorV2(conn, "service unavailable", "")- return- }-- // Check rate limit and concurrency- peer := p.rateLimiter.identifyPeer(cred)- peerLabel := peer.String()- releaseLimiter, limitReason, allowed := p.rateLimiter.allow(peer)- if !allowed {- log.Warn().- Uint32("uid", cred.uid).- Uint32("pid", cred.pid).- Str("reason", limitReason).- Msg("Rate limit exceeded")- if p.audit != nil {- p.audit.LogRateLimitHit("", cred, remoteAddr, limitReason)- }- p.sendErrorV2(conn, "rate limit exceeded", "")- return- }- releaseFn := releaseLimiter- defer func() {- if releaseFn != nil {- releaseFn()- }- }()- applyPenalty := func(reason string) {- if releaseFn != nil {- releaseFn()- releaseFn = nil- }- p.rateLimiter.penalize(peerLabel, reason)- }-- // Read request using newline-delimited framing- limited := &io.LimitedReader{R: conn, N: maxRequestBytes}- reader := bufio.NewReader(limited)-- line, err := reader.ReadBytes('\n')- if err != nil {- if netErr, ok := err.(net.Error); ok && netErr.Timeout() {- log.Warn().- Err(err).- Str("remote", remoteAddr).- Msg("Read timeout waiting for client request - slow client or attack")- if p.metrics != nil {- p.metrics.recordReadTimeout()- }- if p.audit != nil {- p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "read_timeout")- }- p.sendErrorV2(conn, "read timeout", "")- applyPenalty("read_timeout")- return- }- if errors.Is(err, bufio.ErrBufferFull) || limited.N <= 0 {- if p.audit != nil {- p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "payload_too_large")- }- p.sendErrorV2(conn, "payload too large", "")- applyPenalty("payload_too_large")- return- }- if errors.Is(err, io.EOF) {- if p.audit != nil {- p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "empty_request")- }- p.sendErrorV2(conn, "empty request", "")- applyPenalty("empty_request")- return- }- if p.audit != nil {- p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "read_error")- }- p.sendErrorV2(conn, "failed to read request", "")- applyPenalty("read_error")- return- }-- // Clear read deadline now that request payload has been received- if err := conn.SetReadDeadline(time.Time{}); err != nil {- log.Warn().Err(err).Msg("Failed to clear read deadline after request read")- }-- // Trim whitespace and validate- line = bytes.TrimSpace(line)- if len(line) == 0 {- if p.audit != nil {- p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "empty_request")- }- p.sendErrorV2(conn, "empty request", "")- applyPenalty("empty_request")- return- }-- // Parse JSON- var req RPCRequest- if err := json.Unmarshal(line, &req); err != nil {- if p.audit != nil {- p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "invalid_json")- }- p.sendErrorV2(conn, "invalid request format", "")- applyPenalty("invalid_json")- return- }-- // Sanitize correlation ID- req.CorrelationID = sanitizeCorrelationID(req.CorrelationID)-- // Create contextual logger- logger := log.With().- Str("corr_id", req.CorrelationID).- Uint32("uid", cred.uid).- Uint32("pid", cred.pid).- Str("method", req.Method).- Logger()-- // Prepare response- resp := RPCResponse{- CorrelationID: req.CorrelationID,- Success: false,- }-- // Find handler- handler := p.router[req.Method]- if handler == nil {- if p.audit != nil {- p.audit.LogValidationFailure(req.CorrelationID, cred, remoteAddr, req.Method, nil, "unknown_method")- }- resp.Error = "unknown method"- logger.Warn().Msg("Unknown method")- p.sendResponse(conn, resp, p.writeTimeout)- applyPenalty("unknown_method")- return- }-- // Check if method requires host-level privileges- if privilegedMethods[req.Method] {- if !peerCaps.Has(CapabilityAdmin) {- resp.Error = "method requires admin capability"- log.Warn().- Str("method", req.Method).- Uint32("uid", cred.uid).- Uint32("gid", cred.gid).- Uint32("pid", cred.pid).- Str("corr_id", req.CorrelationID).- Msg("SECURITY: peer lacking admin capability attempted privileged method - access denied")- if p.audit != nil {- p.audit.LogValidationFailure(req.CorrelationID, cred, remoteAddr, req.Method, nil, "capability_denied")- }- p.sendResponse(conn, resp, p.writeTimeout)- p.metrics.rpcRequests.WithLabelValues(req.Method, "unauthorized").Inc()- applyPenalty("capability_denied")- return- }- }-- if p.audit != nil {- p.audit.LogCommandStart(req.CorrelationID, cred, remoteAddr, "", req.Method, nil)- }-- // Annotate context with peer capabilities before executing handler- ctx = withPeerCapabilities(ctx, peerCaps)-- // Execute handler- result, err := handler(ctx, &req, logger)- duration := time.Since(startTime)- if err != nil {- if p.audit != nil {- p.audit.LogCommandResult(req.CorrelationID, cred, remoteAddr, "", req.Method, nil, 1, duration, "", "", err)- }- resp.Error = err.Error()- logger.Warn().Err(err).Msg("Handler failed")- p.sendResponse(conn, resp, p.writeTimeout)- // Record failed request- p.metrics.rpcRequests.WithLabelValues(req.Method, "error").Inc()- p.metrics.rpcLatency.WithLabelValues(req.Method).Observe(time.Since(startTime).Seconds())- return- }-- // Success- resp.Success = true- resp.Data = result- if p.audit != nil {- p.audit.LogCommandResult(req.CorrelationID, cred, remoteAddr, "", req.Method, nil, 0, duration, "", "", nil)- }- logger.Info().Msg("Request completed")-- p.sendResponse(conn, resp, p.writeTimeout)-- // Record successful request- p.metrics.rpcRequests.WithLabelValues(req.Method, "success").Inc()- p.metrics.rpcLatency.WithLabelValues(req.Method).Observe(time.Since(startTime).Seconds())-}--// sendErrorV2 sends an error response with correlation ID-func (p *Proxy) sendErrorV2(conn net.Conn, message, correlationID string) {- resp := RPCResponse{- CorrelationID: correlationID,- Success: false,- Error: message,- }- p.sendResponse(conn, resp, p.writeTimeout)-}--// sendResponse sends an RPC response-func (p *Proxy) sendResponse(conn net.Conn, resp RPCResponse, writeTimeout time.Duration) {- // Clear read deadline before writing- if err := conn.SetReadDeadline(time.Time{}); err != nil {- log.Warn().Err(err).Msg("Failed to clear read deadline")- }-- if writeTimeout <= 0 {- writeTimeout = 10 * time.Second- }-- if err := conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {- log.Warn().Err(err).Dur("write_timeout", writeTimeout).Msg("Failed to set write deadline")- }-- encoder := json.NewEncoder(conn)- if err := encoder.Encode(resp); err != nil {- if netErr, ok := err.(net.Error); ok && netErr.Timeout() {- log.Warn().Err(err).Msg("Write timeout while sending RPC response")- if p.metrics != nil {- p.metrics.recordWriteTimeout()- }- } else {- log.Error().Err(err).Msg("Failed to encode RPC response")- }- }-}--// ensureSSHKeypair generates SSH keypair if it doesn't exist-func (p *Proxy) ensureSSHKeypair() error {- privKeyPath := filepath.Join(p.sshKeyPath, "id_ed25519")- pubKeyPath := filepath.Join(p.sshKeyPath, "id_ed25519.pub")-- // Check if keypair already exists- if _, err := os.Stat(privKeyPath); err == nil {- if _, err := os.Stat(pubKeyPath); err == nil {- log.Info().Msg("SSH keypair already exists")- return nil- }- }-- log.Info().Msg("Generating new SSH keypair")-- // Generate ed25519 keypair using ssh-keygen- cmd := fmt.Sprintf("ssh-keygen -t ed25519 -f %s -N '' -C 'pulse-sensor-proxy'", privKeyPath)- if output, err := execCommand(cmd); err != nil {- return fmt.Errorf("failed to generate SSH keypair: %w (output: %s)", err, output)- }-- log.Info().Str("path", privKeyPath).Msg("SSH keypair generated")- return nil-}--// V2 handlers with context and structured logging--// handleGetStatusV2 returns proxy status with context support-func (p *Proxy) handleGetStatusV2(ctx context.Context, req *RPCRequest, logger zerolog.Logger) (interface{}, error) {- pubKeyPath := filepath.Join(p.sshKeyPath, "id_ed25519.pub")- pubKey, err := os.ReadFile(pubKeyPath)- if err != nil {- return nil, fmt.Errorf("failed to read public key: %w", err)- }-- logger.Info().Msg("Status request served")- response := map[string]interface{}{- "version": Version,- "public_key": string(pubKey),- "ssh_dir": p.sshKeyPath,- }-- if caps := peerCapabilitiesFromContext(ctx); caps != 0 {- if names := capabilityNames(caps); len(names) > 0 {- response["capabilities"] = names- }- }-- return response, nil-}--// handleEnsureClusterKeysV2 discovers cluster nodes and pushes SSH keys with validation-func (p *Proxy) handleEnsureClusterKeysV2(ctx context.Context, req *RPCRequest, logger zerolog.Logger) (interface{}, error) {- // Check if we're on a Proxmox host- if !isProxmoxHost() {- return nil, fmt.Errorf("not running on Proxmox host - cannot discover cluster")- }-- // Check for optional key_dir parameter (for key rotation)- keyDir := p.sshKeyPath // default- if keyDirParam, ok := req.Params["key_dir"]; ok {- if keyDirStr, ok := keyDirParam.(string); ok && keyDirStr != "" {- keyDir = keyDirStr- logger.Info().Str("key_dir", keyDir).Msg("Using custom key directory for rotation")- }- }-- // Discover cluster nodes- nodes, err := discoverClusterNodes()- if err != nil {- return nil, fmt.Errorf("failed to discover cluster: %w", err)- }-- logger.Info().Strs("nodes", nodes).Msg("Discovered cluster nodes")-- // Push SSH key to each node- results := make(map[string]interface{})- successCount := 0- for _, node := range nodes {- // Validate node name- if err := validateNodeName(node); err != nil {- logger.Warn().Str("node", node).Msg("Invalid node name format")- results[node] = map[string]interface{}{- "success": false,- "error": "invalid node name",- }- continue- }-- logger.Info().Str("node", node).Str("key_dir", keyDir).Msg("Pushing SSH key to node")- if err := p.pushSSHKeyFrom(node, keyDir); err != nil {- logger.Error().Err(err).Str("node", node).Msg("Failed to push SSH key")- results[node] = map[string]interface{}{- "success": false,- "error": err.Error(),- }- } else {- logger.Info().Str("node", node).Msg("SSH key pushed successfully")- results[node] = map[string]interface{}{- "success": true,- }- successCount++- }- }-- return map[string]interface{}{- "nodes": nodes,- "results": results,- "success_count": successCount,- "total_count": len(nodes),- }, nil-}--// handleRegisterNodesV2 returns discovered nodes with validation-func (p *Proxy) handleRegisterNodesV2(ctx context.Context, req *RPCRequest, logger zerolog.Logger) (interface{}, error) {- // Check if we're on a Proxmox host- if !isProxmoxHost() {- return nil, fmt.Errorf("not running on Proxmox host")- }-- // Discover cluster nodes- nodes, err := discoverClusterNodes()- if err != nil {- return nil, fmt.Errorf("failed to discover nodes: %w", err)- }-- // Test SSH connectivity to each node- nodeStatus := make([]map[string]interface{}, 0, len(nodes))- for _, node := range nodes {- status := map[string]interface{}{- "name": node,- }-- // Validate node name- if err := validateNodeName(node); err != nil {- status["ssh_ready"] = false- status["error"] = "invalid node name"- nodeStatus = append(nodeStatus, status)- continue- }-- if err := p.testSSHConnection(node); err != nil {- status["ssh_ready"] = false- status["error"] = err.Error()- } else {- status["ssh_ready"] = true- }-- nodeStatus = append(nodeStatus, status)- }-- logger.Info().Int("node_count", len(nodeStatus)).Msg("Node discovery completed")- return map[string]interface{}{- "nodes": nodeStatus,- }, nil-}--// handleGetTemperatureV2 fetches temperature data with concurrency control and validation-func (p *Proxy) handleGetTemperatureV2(ctx context.Context, req *RPCRequest, logger zerolog.Logger) (interface{}, error) {- // Extract node parameter- nodeParam, ok := req.Params["node"]- if !ok {- return nil, fmt.Errorf("missing 'node' parameter")- }-- node, ok := nodeParam.(string)- if !ok {- return nil, fmt.Errorf("'node' parameter must be a string")- }-- // Trim and validate node name- node = strings.TrimSpace(node)- if err := validateNodeName(node); err != nil {- logger.Warn().Str("node", node).Msg("Invalid node name format")- return nil, fmt.Errorf("invalid node name")- }-- if p.nodeValidator != nil {- if err := p.nodeValidator.Validate(ctx, node); err != nil {- logger.Warn().Err(err).Str("node", node).Msg("Node validation failed")- return nil, err- }- }-- // Acquire per-node concurrency lock (context-aware to prevent goroutine leaks)- releaseNode, err := p.nodeGate.acquireContext(ctx, node)- if err != nil {- logger.Warn().Err(err).Str("node", node).Msg("Request cancelled while waiting for node lock")- return nil, fmt.Errorf("request cancelled while waiting for node")- }- defer releaseNode()-- logger.Debug().Str("node", node).Msg("Fetching temperature via SSH")-- // Fetch temperature data with timeout- sshCtx, cancel := context.WithTimeout(ctx, 15*time.Second)- defer cancel()- tempData, err := p.getTemperatureViaSSH(sshCtx, node)- if err != nil {- logger.Warn().Err(err).Str("node", node).Msg("Failed to get temperatures")- return nil, fmt.Errorf("failed to get temperatures: %w", err)- }-- logger.Info().Str("node", node).Msg("Temperature data fetched successfully")- return map[string]interface{}{- "node": node,- "temperature": tempData,- }, nil-}diff --git a/cmd/pulse-sensor-proxy/main_test.go b/cmd/pulse-sensor-proxy/main_test.godeleted file mode 100644index f0cf44f9d0..0000000000--- a/cmd/pulse-sensor-proxy/main_test.go+++ /dev/null@@ -1,440 +0,0 @@-package main--import (- "context"- "encoding/json"- "fmt"- "net"- "net/http"- "net/http/httptest"- "os"- "os/exec"- "os/user"- "path/filepath"- "runtime"- "strconv"- "strings"- "testing"-- "github.com/rs/zerolog"-)--func TestParseLogLevel(t *testing.T) {- tests := []struct {- input string- want zerolog.Level- }{- {"trace", zerolog.TraceLevel},- {"debug", zerolog.DebugLevel},- {"DEBUG", zerolog.DebugLevel},- {"info", zerolog.InfoLevel},- {"warn", zerolog.WarnLevel},- {"warning", zerolog.WarnLevel},- {"error", zerolog.ErrorLevel},- {"fatal", zerolog.FatalLevel},- {"panic", zerolog.PanicLevel},- {"disabled", zerolog.Disabled},- {"none", zerolog.Disabled},- {"unknown", zerolog.InfoLevel},- {"", zerolog.InfoLevel},- }- for _, tt := range tests {- if got := parseLogLevel(tt.input); got != tt.want {- t.Errorf("parseLogLevel(%q) = %v, want %v", tt.input, got, tt.want)- }- }-}--func TestDropPrivileges(t *testing.T) {- // Save original functions- oldGeteuid := osGeteuid- oldResolve := resolveUserSpecFunc- oldSetgroups := unixSetgroups- oldSetgid := unixSetgid- oldSetuid := unixSetuid- defer func() {- osGeteuid = oldGeteuid- resolveUserSpecFunc = oldResolve- unixSetgroups = oldSetgroups- unixSetgid = oldSetgid- unixSetuid = oldSetuid- }()-- // Mock for root user- osGeteuid = func() int { return 0 }- resolveUserSpecFunc = func(u string) (*userSpec, error) {- return &userSpec{name: u, uid: 1000, gid: 1000, groups: []int{1000}}, nil- }- unixSetgroups = func(g []int) error { return nil }- unixSetgid = func(g int) error { return nil }- unixSetuid = func(u int) error { return nil }-- // Test success path- spec, err := dropPrivileges("testuser")- if err != nil {- t.Errorf("dropPrivileges failed: %v", err)- }- if spec == nil {- t.Fatal("expected spec, got nil")- }- if spec.uid != 1000 {- t.Errorf("expected uid 1000, got %d", spec.uid)- }-- // Test non-root (should return nil, nil)- osGeteuid = func() int { return 1000 }- spec, err = dropPrivileges("testuser")- if err != nil {- t.Errorf("unexpected error for non-root: %v", err)- }- if spec != nil {- t.Error("expected nil spec for non-root")- }-}--func TestResolveUserSpec_PasswdFallback(t *testing.T) {- // Mock passwd file- tmpDir := t.TempDir()- pPath, _ := os.CreateTemp(tmpDir, "passwd")- pPath.WriteString("testuser:x:1001:1001::/home/testuser:/bin/sh\n")- pPath.Close()-- origPath := passwdPath- defer func() { passwdPath = origPath }()- passwdPath = pPath.Name()-- // Test- spec, err := lookupUserFromPasswd("testuser")- if err != nil {- t.Fatalf("lookup failed: %v", err)- }- if spec.uid != 1001 || spec.gid != 1001 {- t.Errorf("mismatch: %+v", spec)- }-- // Test not found- _, err = lookupUserFromPasswd("nonexistent")- if err == nil {- t.Error("expected error for nonexistent user")- }-}--func TestResolveUserSpec(t *testing.T) {- // Mock lookupUserFromPasswd if we could, but resolveUserSpec calls user.Lookup first.- // We can test that it falls back to passwd if user.Lookup fails (which it might in test env).- // But lookupUserFromPasswd reads /etc/passwd path which is hardcoded.- // We can't mock os.Open easily without refactoring.-- // However, we can test with a known user if possible, or mock the fallback.- // Let's assume user.Lookup works for current user.- u, err := user.Current()- if err != nil {- t.Skip("cannot get current user")- }-- spec, err := resolveUserSpec(u.Username)- if err != nil {- t.Fatalf("resolveUserSpec failed: %v", err)- }-- expectedUid, _ := strconv.Atoi(u.Uid)- if spec.uid != expectedUid {- t.Errorf("expected uid %d, got %d", expectedUid, spec.uid)- }-}--func TestResolveUserSpec_Root(t *testing.T) {- // Test success path with existing user- // We use "root" as it should exist on almost all unix systems- // Check if we can look it up first- if _, err := exec.LookPath("id"); err != nil {- t.Skip("id command not found")- }- // Or just try resolving it- spec, err := resolveUserSpec("root")- if err != nil {- t.Skipf("root user resolution failed (maybe minimal env?): %v", err)- }-- if spec.name != "root" {- t.Errorf("expected name root, got %s", spec.name)- }- // UID 0 check- if spec.uid != 0 {- t.Logf("root uid is %d, not 0 (unusual but possible)", spec.uid)- }-}--func TestEnsureSSHKeypair(t *testing.T) {- tmpDir := t.TempDir()- proxy := &Proxy{sshKeyPath: tmpDir}-- // Mock exec for ssh-keygen- origExec := execCommandFunc- defer func() { execCommandFunc = origExec }()- execCommandFunc = func(name string, arg ...string) *exec.Cmd {- args := strings.Join(arg, " ")- if strings.Contains(args, "ssh-keygen") {- // Parse shell command to find -f- // cmd string is in arg[1] (after -c)- if len(arg) > 1 {- cmdStr := arg[1]- parts := strings.Fields(cmdStr)- for i, p := range parts {- if p == "-f" && i+1 < len(parts) {- path := parts[i+1]- os.WriteFile(path, []byte("priv"), 0600)- os.WriteFile(path+".pub", []byte("pub"), 0644)- }- }- }- return mockExecCommand("")- }- return mockExecCommand("")- }-- // First run: generate- if err := proxy.ensureSSHKeypair(); err != nil {- t.Fatalf("ensureSSHKeypair failed: %v", err)- }-- if _, err := os.Stat(filepath.Join(tmpDir, "id_ed25519")); err != nil {- t.Error("private key not created")- }-- // Second run: existing- // Restore exec to fail if called (should not be called)- execCommandFunc = func(name string, arg ...string) *exec.Cmd {- return errorExecCommand("should not be called")- }- if err := proxy.ensureSSHKeypair(); err != nil {- t.Fatalf("ensureSSHKeypair existing failed: %v", err)- }-}--type mockListener struct {- net.Listener- closed bool-}--func (m *mockListener) Close() error {- m.closed = true- return nil-}--func (m *mockListener) Accept() (net.Conn, error) {- // Block until closed- select {}-}--func (m *mockListener) Addr() net.Addr {- return &net.UnixAddr{Name: "/tmp/sock", Net: "unix"}-}--func TestProxy_StartStop(t *testing.T) {- tmpDir := t.TempDir()- sshDir := filepath.Join(tmpDir, "ssh")- socketPath := filepath.Join(tmpDir, "sock")-- // Mock net.Listen- origListen := netListen- defer func() { netListen = origListen }()- listenCalled := false- netListen = func(network, address string) (net.Listener, error) {- listenCalled = true- return &mockListener{}, nil- }-- // Mock exec for key gen- origExec := execCommandFunc- defer func() { execCommandFunc = origExec }()- execCommandFunc = func(name string, arg ...string) *exec.Cmd {- args := strings.Join(arg, " ")- if strings.Contains(args, "ssh-keygen") {- // Create dummy key files- for i, a := range arg {- if a == "-f" && i+1 < len(arg) {- os.MkdirAll(filepath.Dir(arg[i+1]), 0755)- os.WriteFile(arg[i+1], []byte("priv"), 0600)- os.WriteFile(arg[i+1]+".pub", []byte("pub"), 0644)- }- }- return mockExecCommand("")- }- return mockExecCommand("")- }-- proxy := &Proxy{- sshKeyPath: sshDir,- socketPath: socketPath,- metrics: NewProxyMetrics("test"),- }-- if err := proxy.Start(); err != nil {- t.Fatalf("Start failed: %v", err)- }-- if !listenCalled {- t.Error("net.Listen not called")- }-- // Check directories created- if _, err := os.Stat(sshDir); err != nil {- t.Error("ssh dir not created")- }-- // Stop- proxy.Stop()- // Should close listener -> our mock doesn't block Stop.-- // Check socket removed (Start code removes it first)- // But our mock listener doesn't create file.- // The Start() function calls os.RemoveAll(p.socketPath).-}--// Helpers for http_server_test.go which I might have deleted if they were in main_test.go-func mockExecCommand(output string) *exec.Cmd {- cs := []string{"-test.run=TestHelperProcess", "--", output}- cmd := exec.Command(os.Args[0], cs...)- cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1", "GO_HELPER_OUTPUT=" + output}- return cmd-}--func errorExecCommand(msg string) *exec.Cmd {- cs := []string{"-test.run=TestHelperProcess", "--", msg}- cmd := exec.Command(os.Args[0], cs...)- cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1", "GO_HELPER_ERROR=" + msg}- return cmd-}--func TestHelperProcess(t *testing.T) {- if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {- return- }-- if msg := os.Getenv("GO_HELPER_ERROR"); msg != "" {- fmt.Fprint(os.Stderr, msg)- os.Exit(1)- }-- output := os.Getenv("GO_HELPER_OUTPUT")- fmt.Fprint(os.Stdout, output)-- if codeStr := os.Getenv("GO_HELPER_EXIT_CODE"); codeStr != "" {- if code, err := strconv.Atoi(codeStr); err == nil {- os.Exit(code)- }- }- os.Exit(0)-}--func TestFetchAuthorizedNodes(t *testing.T) {- // Mock server- handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.Header.Get("X-Proxy-Token") != "token" {- http.Error(w, "unauthorized", http.StatusUnauthorized)- return- }-- resp := struct {- Nodes []struct {- Name string `json:"name"`- IP string `json:"ip"`- } `json:"nodes"`- Hash string `json:"hash"`- RefreshInterval int `json:"refresh_interval"`- }{- Nodes: []struct {- Name string `json:"name"`- IP string `json:"ip"`- }{- {Name: "node1", IP: "10.0.0.1"},- },- Hash: "abc",- RefreshInterval: 60,- }- json.NewEncoder(w).Encode(resp)- })- server := httptest.NewServer(handler)- defer server.Close()-- nv, _ := newNodeValidator(nil, nil)- proxy := &Proxy{- controlPlaneCfg: &ControlPlaneConfig{- URL: server.URL,- },- controlPlaneToken: "token",- nodeValidator: nv,- }-- // Need a client- client := server.Client()-- if err := proxy.fetchAuthorizedNodes(client); err != nil {- t.Fatalf("fetchAuthorizedNodes failed: %v", err)- }-- if proxy.controlPlaneCfg.RefreshIntervalSec != 60 {- t.Errorf("expected refresh interval 60, got %d", proxy.controlPlaneCfg.RefreshIntervalSec)- }-- // Need context for Validate- if err := proxy.nodeValidator.Validate(context.Background(), "node1"); err != nil {- t.Errorf("expected node1 to be valid: %v", err)- }-}--func TestDefaultExtractPeerCredentials_Real(t *testing.T) {- if runtime.GOOS != "linux" {- t.Skip("Skipping Linux-specific test")- }-- // Create unix socket- tmpDir := t.TempDir()- sockPath := filepath.Join(tmpDir, "test.sock")- l, err := net.Listen("unix", sockPath)- if err != nil {- t.Fatal(err)- }- defer l.Close()-- serverConnCh := make(chan net.Conn)-- // Accept in goroutine- go func() {- c, err := l.Accept()- if err != nil {- close(serverConnCh)- return- }- serverConnCh <- c- }()-- clientConn, err := net.Dial("unix", sockPath)- if err != nil {- t.Fatal(err)- }- defer clientConn.Close()-- serverConn := <-serverConnCh- if serverConn == nil {- t.Fatal("failed to accept connection")- }- defer serverConn.Close()-- creds, err := defaultExtractPeerCredentials(serverConn)- if err != nil {- t.Fatalf("defaultExtractPeerCredentials failed: %v", err)- }-- // Check against current process- if creds.uid != uint32(os.Getuid()) {- t.Errorf("expected uid %d, got %d", os.Getuid(), creds.uid)- }- if creds.gid != uint32(os.Getgid()) {- t.Errorf("expected gid %d, got %d", os.Getgid(), creds.gid)- }- if creds.pid != uint32(os.Getpid()) {- t.Errorf("expected pid %d, got %d", os.Getpid(), creds.pid)- }-}diff --git a/cmd/pulse-sensor-proxy/metrics.go b/cmd/pulse-sensor-proxy/metrics.godeleted file mode 100644index f5796e7171..0000000000--- a/cmd/pulse-sensor-proxy/metrics.go+++ /dev/null@@ -1,322 +0,0 @@-package main--import (- "context"- "net"- "net/http"- "strings"- "time"-- "github.com/prometheus/client_golang/prometheus"- "github.com/prometheus/client_golang/prometheus/promhttp"- "github.com/rs/zerolog/log"-)--const defaultMetricsAddr = "127.0.0.1:9127"--// ProxyMetrics holds Prometheus metrics for the proxy-type ProxyMetrics struct {- rpcRequests *prometheus.CounterVec- rpcLatency *prometheus.HistogramVec- sshRequests *prometheus.CounterVec- sshLatency *prometheus.HistogramVec- queueDepth prometheus.Gauge- rateLimitHits prometheus.Counter- limiterRejects *prometheus.CounterVec- globalConcurrency prometheus.Gauge- limiterPenalties *prometheus.CounterVec- limiterPeers prometheus.Gauge- nodeValidationFailures *prometheus.CounterVec- readTimeouts prometheus.Counter- writeTimeouts prometheus.Counter- hostKeyChanges *prometheus.CounterVec- sshOutputOversized *prometheus.CounterVec- buildInfo *prometheus.GaugeVec- server *http.Server- registry *prometheus.Registry-}--// NewProxyMetrics creates and registers all metrics-func NewProxyMetrics(version string) *ProxyMetrics {- reg := prometheus.NewRegistry()-- pm := &ProxyMetrics{- rpcRequests: prometheus.NewCounterVec(- prometheus.CounterOpts{- Name: "pulse_proxy_rpc_requests_total",- Help: "Total RPC requests handled by method and result.",- },- []string{"method", "result"},- ),- rpcLatency: prometheus.NewHistogramVec(- prometheus.HistogramOpts{- Name: "pulse_proxy_rpc_latency_seconds",- Help: "RPC handler latency.",- Buckets: []float64{0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 2.5, 5},- },- []string{"method"},- ),- sshRequests: prometheus.NewCounterVec(- prometheus.CounterOpts{- Name: "pulse_proxy_ssh_requests_total",- Help: "SSH command executions by node and result.",- },- []string{"node", "result"},- ),- sshLatency: prometheus.NewHistogramVec(- prometheus.HistogramOpts{- Name: "pulse_proxy_ssh_latency_seconds",- Help: "SSH command latency per node.",- Buckets: []float64{0.1, 0.5, 1, 2.5, 5, 10, 30},- },- []string{"node"},- ),- queueDepth: prometheus.NewGauge(- prometheus.GaugeOpts{- Name: "pulse_proxy_queue_depth",- Help: "Concurrent RPC requests being processed.",- },- ),- rateLimitHits: prometheus.NewCounter(- prometheus.CounterOpts{- Name: "pulse_proxy_rate_limit_hits_total",- Help: "Number of RPC requests rejected due to rate limiting.",- },- ),- limiterRejects: prometheus.NewCounterVec(- prometheus.CounterOpts{- Name: "pulse_proxy_limiter_rejections_total",- Help: "Limiter rejections by reason.",- },- []string{"reason", "peer"},- ),- globalConcurrency: prometheus.NewGauge(- prometheus.GaugeOpts{- Name: "pulse_proxy_global_concurrency_inflight",- Help: "Current global concurrency slots in use.",- },- ),- limiterPenalties: prometheus.NewCounterVec(- prometheus.CounterOpts{- Name: "pulse_proxy_limiter_penalties_total",- Help: "Penalty sleeps applied after validation failures.",- },- []string{"reason", "peer"},- ),- limiterPeers: prometheus.NewGauge(- prometheus.GaugeOpts{- Name: "pulse_proxy_limiter_active_peers",- Help: "Number of peers tracked by the rate limiter.",- },- ),- nodeValidationFailures: prometheus.NewCounterVec(- prometheus.CounterOpts{- Name: "pulse_proxy_node_validation_failures_total",- Help: "Node validation failures by reason.",- },- []string{"reason"},- ),- readTimeouts: prometheus.NewCounter(- prometheus.CounterOpts{- Name: "pulse_proxy_read_timeouts_total",- Help: "Number of socket read timeouts.",- },- ),- writeTimeouts: prometheus.NewCounter(- prometheus.CounterOpts{- Name: "pulse_proxy_write_timeouts_total",- Help: "Number of socket write timeouts.",- },- ),- hostKeyChanges: prometheus.NewCounterVec(- prometheus.CounterOpts{- Name: "pulse_proxy_hostkey_changes_total",- Help: "Detected SSH host key changes by node.",- },- []string{"node"},- ),- sshOutputOversized: prometheus.NewCounterVec(- prometheus.CounterOpts{- Name: "pulse_proxy_ssh_output_oversized_total",- Help: "Number of SSH responses rejected for exceeding size limits.",- },- []string{"node"},- ),- buildInfo: prometheus.NewGaugeVec(- prometheus.GaugeOpts{- Name: "pulse_proxy_build_info",- Help: "Proxy build metadata.",- },- []string{"version"},- ),- registry: reg,- }-- reg.MustRegister(- pm.rpcRequests,- pm.rpcLatency,- pm.sshRequests,- pm.sshLatency,- pm.queueDepth,- pm.rateLimitHits,- pm.limiterRejects,- pm.globalConcurrency,- pm.limiterPenalties,- pm.limiterPeers,- pm.nodeValidationFailures,- pm.readTimeouts,- pm.writeTimeouts,- pm.hostKeyChanges,- pm.sshOutputOversized,- pm.buildInfo,- )-- pm.buildInfo.WithLabelValues(version).Set(1)-- return pm-}--// Start starts the metrics HTTP server on the specified address-func (m *ProxyMetrics) Start(addr string) error {- if addr == "" || strings.ToLower(addr) == "disabled" {- log.Info().Msg("Metrics server disabled")- return nil- }-- if addr == "default" {- addr = defaultMetricsAddr- }-- mux := http.NewServeMux()- mux.Handle("/metrics", promhttp.HandlerFor(m.registry, promhttp.HandlerOpts{}))-- ln, err := net.Listen("tcp", addr)- if err != nil {- return err- }-- m.server = &http.Server{- Addr: addr,- Handler: mux,- ReadHeaderTimeout: 5 * time.Second,- }-- go func() {- if err := m.server.Serve(ln); err != nil && err != http.ErrServerClosed {- log.Error().Err(err).Str("addr", addr).Msg("Metrics server stopped unexpectedly")- }- }()-- log.Info().Str("addr", addr).Msg("Metrics server started")- return nil-}--// Shutdown gracefully shuts down the metrics server-func (m *ProxyMetrics) Shutdown(ctx context.Context) {- if m == nil || m.server == nil {- return- }- _ = m.server.Shutdown(ctx)-}--// sanitizeNodeLabel converts a node name into a safe Prometheus label value-func sanitizeNodeLabel(node string) string {- const maxLen = 63- safe := strings.Builder{}- safe.Grow(len(node))-- for _, r := range strings.ToLower(node) {- if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' {- safe.WriteRune(r)- } else {- safe.WriteRune('_')- }- }-- out := safe.String()- if len(out) > maxLen {- out = out[:maxLen]- }- if out == "" {- out = "unknown"- }-- return out-}--func (m *ProxyMetrics) recordLimiterReject(reason, peer string) {- if m == nil {- return- }- m.rateLimitHits.Inc()- m.limiterRejects.WithLabelValues(reason, peer).Inc()-}--func (m *ProxyMetrics) recordNodeValidationFailure(reason string) {- if m == nil {- return- }- m.nodeValidationFailures.WithLabelValues(reason).Inc()-}--func (m *ProxyMetrics) recordReadTimeout() {- if m == nil {- return- }- m.readTimeouts.Inc()-}--func (m *ProxyMetrics) recordWriteTimeout() {- if m == nil {- return- }- m.writeTimeouts.Inc()-}--func (m *ProxyMetrics) recordSSHOutputOversized(node string) {- if m == nil {- return- }- if node == "" {- node = "unknown"- }- m.sshOutputOversized.WithLabelValues(sanitizeNodeLabel(node)).Inc()-}--func (m *ProxyMetrics) recordHostKeyChange(node string) {- if m == nil {- return- }- if node == "" {- node = "unknown"- }- m.hostKeyChanges.WithLabelValues(sanitizeNodeLabel(node)).Inc()-}--func (m *ProxyMetrics) incGlobalConcurrency() {- if m == nil {- return- }- m.globalConcurrency.Inc()-}--func (m *ProxyMetrics) decGlobalConcurrency() {- if m == nil {- return- }- m.globalConcurrency.Dec()-}--func (m *ProxyMetrics) recordPenalty(reason, peer string) {- if m == nil {- return- }- m.limiterPenalties.WithLabelValues(reason, peer).Inc()-}--func (m *ProxyMetrics) setLimiterPeers(count int) {- if m == nil {- return- }- m.limiterPeers.Set(float64(count))-}diff --git a/cmd/pulse-sensor-proxy/metrics_test.go b/cmd/pulse-sensor-proxy/metrics_test.godeleted file mode 100644index b9a55ba990..0000000000--- a/cmd/pulse-sensor-proxy/metrics_test.go+++ /dev/null@@ -1,287 +0,0 @@-package main--import (- "context"- "testing"-)--func TestSanitizeNodeLabel(t *testing.T) {- tests := []struct {- name string- input string- want string- }{- // Basic cases- {- name: "simple hostname",- input: "node1",- want: "node1",- },- {- name: "hostname with hyphen",- input: "node-1",- want: "node-1",- },- {- name: "hostname with underscore",- input: "node_1",- want: "node_1",- },- {- name: "hostname with dot",- input: "node.local",- want: "node.local",- },- {- name: "fqdn",- input: "node1.example.com",- want: "node1.example.com",- },-- // Case conversion- {- name: "uppercase converted to lowercase",- input: "Node1",- want: "node1",- },- {- name: "mixed case",- input: "MyNode-Server",- want: "mynode-server",- },- {- name: "all uppercase",- input: "PRODSERVER01",- want: "prodserver01",- },-- // Special character handling- {- name: "space replaced with underscore",- input: "node 1",- want: "node_1",- },- {- name: "colon replaced with underscore",- input: "node:1",- want: "node_1",- },- {- name: "at sign replaced with underscore",- input: "user@node",- want: "user_node",- },- {- name: "forward slash replaced",- input: "path/to/node",- want: "path_to_node",- },- {- name: "multiple special chars",- input: "node!@#$%^&*()+=[]{}|\\:;<>,?/~`",- want: "node___________________________",- },- {- name: "unicode replaced with underscore",- input: "节点1",- want: "__1",- },- {- name: "emoji replaced",- input: "server🔥hot",- want: "server_hot",- },-- // Length limits- {- name: "exactly 63 chars preserved",- input: "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0",- want: "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0",- },- {- name: "longer than 63 chars truncated",- input: "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789",- want: "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0",- },- {- name: "very long hostname truncated",- input: "this-is-a-very-long-hostname-that-exceeds-the-prometheus-label-value-limit-of-sixty-three-characters",- want: "this-is-a-very-long-hostname-that-exceeds-the-prometheus-label-",- },-- // Edge cases- {- name: "empty string returns unknown",- input: "",- want: "unknown",- },- {- name: "all special chars returns unknown",- input: "!@#$%",- want: "_____",- },- {- name: "single char",- input: "a",- want: "a",- },- {- name: "numbers only",- input: "12345",- want: "12345",- },- {- name: "hyphen start preserved",- input: "-node",- want: "-node",- },- {- name: "underscore start preserved",- input: "_node",- want: "_node",- },- {- name: "dot start preserved",- input: ".hidden",- want: ".hidden",- },-- // Realistic node names- {- name: "proxmox node style",- input: "pve-node1",- want: "pve-node1",- },- {- name: "ip address style",- input: "192.168.1.100",- want: "192.168.1.100",- },- {- name: "kubernetes node",- input: "k8s-worker-01.cluster.local",- want: "k8s-worker-01.cluster.local",- },- {- name: "docker container id prefix",- input: "abc123def456",- want: "abc123def456",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := sanitizeNodeLabel(tt.input)- if got != tt.want {- t.Errorf("sanitizeNodeLabel(%q) = %q, want %q", tt.input, got, tt.want)- }- })- }-}--func TestSanitizeNodeLabel_MaxLength(t *testing.T) {- // Test that all outputs are <= 63 chars- longInputs := []string{- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",- "very-long-hostname-with-many-hyphens-and-lots-of-segments-here",- "node123456789012345678901234567890123456789012345678901234567890",- }-- for _, input := range longInputs {- result := sanitizeNodeLabel(input)- if len(result) > 63 {- t.Errorf("sanitizeNodeLabel(%q) length = %d, want <= 63", input, len(result))- }- }-}--func TestSanitizeNodeLabel_NeverEmpty(t *testing.T) {- // Test that output is never empty- emptyishInputs := []string{- "",- " ",- }-- for _, input := range emptyishInputs {- result := sanitizeNodeLabel(input)- if result == "" {- t.Errorf("sanitizeNodeLabel(%q) returned empty string, should return 'unknown' or sanitized value", input)- }- }-}--func TestSanitizeNodeLabel_Idempotent(t *testing.T) {- // Applying sanitize twice should give same result as once- inputs := []string{- "node1",- "Node@Server",- "test.node.local",- "mixed-CASE_name.123",- }-- for _, input := range inputs {- once := sanitizeNodeLabel(input)- twice := sanitizeNodeLabel(once)- if once != twice {- t.Errorf("sanitizeNodeLabel is not idempotent: sanitizeNodeLabel(%q) = %q, sanitizeNodeLabel(%q) = %q",- input, once, once, twice)- }- }-}--func TestProxyMetrics(t *testing.T) {- m := NewProxyMetrics("1.0.0")-- // Test Start with disabled- if err := m.Start("disabled"); err != nil {- t.Fatal(err)- }-- // Test Start with empty- if err := m.Start(""); err != nil {- t.Fatal(err)- }-- // Test Start with actual address- if err := m.Start("127.0.0.1:0"); err != nil {- t.Errorf("failed to start on random port: %v", err)- } else {- m.Shutdown(context.Background())- }-- // Test recording methods- m.recordLimiterReject("reason", "peer")- m.recordNodeValidationFailure("reason")- m.recordReadTimeout()- m.recordWriteTimeout()- m.recordSSHOutputOversized("node")- m.recordSSHOutputOversized("") // Test empty node- m.recordHostKeyChange("node")- m.recordHostKeyChange("") // Test empty node- m.incGlobalConcurrency()- m.decGlobalConcurrency()- m.recordPenalty("reason", "peer")- m.setLimiterPeers(5)-- // Test recording with nil metrics- var nilMetrics *ProxyMetrics- nilMetrics.recordLimiterReject("r", "p")- nilMetrics.recordNodeValidationFailure("r")- nilMetrics.recordReadTimeout()- nilMetrics.recordWriteTimeout()- nilMetrics.recordSSHOutputOversized("n")- nilMetrics.recordHostKeyChange("n")- nilMetrics.incGlobalConcurrency()- nilMetrics.decGlobalConcurrency()- nilMetrics.recordPenalty("r", "p")- nilMetrics.setLimiterPeers(1)- nilMetrics.Shutdown(context.Background())-}--func TestProxyMetrics_StartError(t *testing.T) {- m := NewProxyMetrics("1.0.0")- // Invalid address- if err := m.Start("999.999.999.999:9999"); err == nil {- t.Error("expected error for invalid address")- }-}diff --git a/cmd/pulse-sensor-proxy/peer_creds_linux.go b/cmd/pulse-sensor-proxy/peer_creds_linux.godeleted file mode 100644index c94c1f4220..0000000000--- a/cmd/pulse-sensor-proxy/peer_creds_linux.go+++ /dev/null@@ -1,44 +0,0 @@-//go:build linux--package main--import (- "fmt"- "net"- "syscall"-- "github.com/rs/zerolog/log"-)--// defaultExtractPeerCredentials extracts peer credentials via SO_PEERCRED-func defaultExtractPeerCredentials(conn net.Conn) (*peerCredentials, error) {- unixConn, ok := conn.(*net.UnixConn)- if !ok {- return nil, fmt.Errorf("not a unix connection")- }-- file, err := unixConn.File()- if err != nil {- return nil, fmt.Errorf("failed to get file descriptor: %w", err)- }- defer file.Close()-- fd := int(file.Fd())-- cred, err := syscall.GetsockoptUcred(fd, syscall.SOL_SOCKET, syscall.SO_PEERCRED)- if err != nil {- return nil, fmt.Errorf("failed to get peer credentials: %w", err)- }-- log.Debug().- Int32("pid", cred.Pid).- Uint32("uid", cred.Uid).- Uint32("gid", cred.Gid).- Msg("Peer credentials")-- return &peerCredentials{- uid: cred.Uid,- pid: uint32(cred.Pid),- gid: cred.Gid,- }, nil-}diff --git a/cmd/pulse-sensor-proxy/peer_creds_stub.go b/cmd/pulse-sensor-proxy/peer_creds_stub.godeleted file mode 100644index 9cacf86b2f..0000000000--- a/cmd/pulse-sensor-proxy/peer_creds_stub.go+++ /dev/null@@ -1,32 +0,0 @@-//go:build !linux--package main--import (- "net"- "os"-- "github.com/rs/zerolog/log"-)--// defaultExtractPeerCredentials is a stub for non-Linux systems-func defaultExtractPeerCredentials(conn net.Conn) (*peerCredentials, error) {- // On non-Linux systems (like macOS dev), we can't easily get the peer credentials- // from the socket. For development purposes, we'll assume the connection- // comes from the current user.-- uid := uint32(os.Getuid())- gid := uint32(os.Getgid())- pid := uint32(os.Getpid())-- log.Debug().- Uint32("uid", uid).- Uint32("gid", gid).- Msg("Peer credentials (STUB: using current process credentials)")-- return &peerCredentials{- uid: uid,- pid: pid,- gid: gid,- }, nil-}diff --git a/cmd/pulse-sensor-proxy/rpc_test.go b/cmd/pulse-sensor-proxy/rpc_test.godeleted file mode 100644index 705763bf60..0000000000--- a/cmd/pulse-sensor-proxy/rpc_test.go+++ /dev/null@@ -1,336 +0,0 @@-package main--import (- "context"- "fmt"- "net"- "os"- "os/exec"- "path/filepath"- "strings"- "testing"-- "github.com/rs/zerolog"-)--type mockKnownHosts struct{}--func (m *mockKnownHosts) Ensure(ctx context.Context, host string) error { return nil }-func (m *mockKnownHosts) EnsureWithPort(ctx context.Context, host string, port int) error { return nil }-func (m *mockKnownHosts) EnsureWithEntries(ctx context.Context, host string, port int, entries [][]byte) error {- return nil-}-func (m *mockKnownHosts) Path() string { return "/tmp/known_hosts" }--func TestHandleGetStatusV2(t *testing.T) {- tmpDir := t.TempDir()- pubKeyPath := filepath.Join(tmpDir, "id_ed25519.pub")- os.WriteFile(pubKeyPath, []byte("ssh-ed25519 AAA..."), 0644)-- proxy := &Proxy{- sshKeyPath: tmpDir,- }-- req := &RPCRequest{}- logger := zerolog.New(os.Stderr)-- resp, err := proxy.handleGetStatusV2(context.Background(), req, logger)- if err != nil {- t.Fatalf("handleGetStatusV2 failed: %v", err)- }-- m, ok := resp.(map[string]interface{})- if !ok {- t.Fatalf("expected map response, got %T", resp)- }-- if m["version"] != Version {- t.Errorf("expected version %s, got %v", Version, m["version"])- }- if m["public_key"] != "ssh-ed25519 AAA..." {- t.Errorf("unexpected public key: %v", m["public_key"])- }-}--func TestHandleGetTemperatureV2(t *testing.T) {- // Mock execLookPath and execCommandFunc- origLookPath := execLookPath- origExec := execCommandFunc- origExecCtx := execCommandContextFunc- defer func() {- execLookPath = origLookPath- execCommandFunc = origExec- execCommandContextFunc = origExecCtx- }()-- execLookPath = func(file string) (string, error) {- return "/usr/bin/" + file, nil- }-- mockCmd := func(ctx context.Context, name string, arg ...string) *exec.Cmd {- args := strings.Join(arg, " ")- if name == "sh" && strings.Contains(args, "ssh") {- // Mock SSH output with sensor JSON- output := `{"cpu": {"temp1": {"temp1_input": 45.0}}}`- return mockExecCommand(output)- }- // For local node- if name == "sensors" {- output := `{"cpu": {"temp1": {"temp1_input": 45.0}}}`- return mockExecCommand(output)- }- return mockExecCommand("")- }-- execCommandFunc = func(name string, arg ...string) *exec.Cmd {- return mockCmd(context.Background(), name, arg...)- }- execCommandContextFunc = func(ctx context.Context, name string, arg ...string) *exec.Cmd {- return mockCmd(ctx, name, arg...)- }-- proxy := &Proxy{- config: &Config{- AllowedNodes: []string{"node1"},- },- metrics: NewProxyMetrics("test"),- nodeGate: newNodeGate(),- knownHosts: &mockKnownHosts{},- }-- logger := zerolog.New(os.Stderr)-- // Success case- req := &RPCRequest{- Params: map[string]interface{}{- "node": "node1",- },- }-- resp, err := proxy.handleGetTemperatureV2(context.Background(), req, logger)- if err != nil {- t.Fatalf("handleGetTemperatureV2 failed: %v", err)- }-- m, ok := resp.(map[string]interface{})- if !ok {- t.Fatalf("expected map response, got %T", resp)- }- respStr, ok := m["temperature"].(string)- if !ok {- t.Errorf("expected string temperature, got %T", m["temperature"])- }- if !strings.Contains(respStr, "45.0") {- t.Errorf("expected 45.0 in response, got %s", respStr)- }-- // Missing parameter- reqMissing := &RPCRequest{Params: map[string]interface{}{}}- _, err = proxy.handleGetTemperatureV2(context.Background(), reqMissing, logger)- if err == nil {- t.Error("expected error for missing node param")- }-- // Invalid node (bad format)- reqInvalid := &RPCRequest{- Params: map[string]interface{}{- "node": "invalid node!", // Space should make it invalid- },- }- _, err = proxy.handleGetTemperatureV2(context.Background(), reqInvalid, logger)- if err == nil {- t.Error("expected error for invalid node")- }-}--func TestHandleRegisterNodesV2(t *testing.T) {- // Mock pvecm- origLookPath := execLookPath- origExec := execCommandFunc- origExecCtx := execCommandContextFunc- defer func() {- execLookPath = origLookPath- execCommandFunc = origExec- execCommandContextFunc = origExecCtx- }()-- execLookPath = func(file string) (string, error) {- if file == "pvecm" {- return "/usr/sbin/pvecm", nil- }- return "", fmt.Errorf("not found")- }-- mockCmd := func(ctx context.Context, name string, arg ...string) *exec.Cmd {- args := strings.Join(arg, " ")- if name == "pvecm" && args == "status" {- // Mock pvecm status output- output := "\nCluster information\n-------------------\nName: cluster\nConfig Version: 1\nTransport: knet\nSecure auth: on\n\nQuorum information\n------------------\nDate: Sun Jan 1 00:00:00 2023\nQuorum provider: corosync_votequorum\nNodes: 1\nNode ID: 0x00000001\nRing ID: 1.1\nQuorate: Yes\n\nVotequorum information\n----------------------\nExpected votes: 1\nHighest expected: 1\nTotal votes: 1\nQuorum: 1\nFlags: Quorate \n\nMembership information\n----------------------\n Nodeid Votes Name\n0x00000001 1 10.0.0.1 (local)\n"- return mockExecCommand(output)- }-- // Mock SSH connection test- if name == "sh" && strings.Contains(args, "ssh") {- // Success- return mockExecCommand("")- }- return mockExecCommand("")- }-- execCommandFunc = func(name string, arg ...string) *exec.Cmd {- return mockCmd(context.Background(), name, arg...)- }- execCommandContextFunc = func(ctx context.Context, name string, arg ...string) *exec.Cmd {- return mockCmd(ctx, name, arg...)- }-- tmpDir := t.TempDir()- proxy := &Proxy{- sshKeyPath: tmpDir,- metrics: NewProxyMetrics("test"),- knownHosts: &mockKnownHosts{},- config: &Config{},- }-- logger := zerolog.New(os.Stderr)- req := &RPCRequest{}-- resp, err := proxy.handleRegisterNodesV2(context.Background(), req, logger)- if err != nil {- t.Fatalf("handleRegisterNodesV2 failed: %v", err)- }-- m, ok := resp.(map[string]interface{})- if !ok {- t.Fatalf("expected map response, got %T", resp)- }-- nodes, ok := m["nodes"].([]map[string]interface{})- if !ok {- t.Fatalf("expected nodes list, got %T", m["nodes"])- }-- if len(nodes) != 1 {- t.Errorf("expected 1 node, got %d", len(nodes))- }- if nodes[0]["name"] != "10.0.0.1" {- t.Errorf("expected node name 10.0.0.1, got %v", nodes[0]["name"])- }- if nodes[0]["ssh_ready"] != true {- t.Errorf("expected ssh_ready true, got %v, error: %v", nodes[0]["ssh_ready"], nodes[0]["error"])- }-}--func TestHandleConnection_InvalidJSON(t *testing.T) {- // Mock extractPeerCredentials- origExtract := extractPeerCredentials- defer func() { extractPeerCredentials = origExtract }()- extractPeerCredentials = func(conn net.Conn) (*peerCredentials, error) {- return &peerCredentials{uid: 1000, gid: 1000, pid: 123}, nil- }-- metrics := NewProxyMetrics("test")- proxy := &Proxy{- metrics: metrics,- config: &Config{- AllowedPeerUIDs: []uint32{1000},- RateLimit: &RateLimitConfig{- PerPeerIntervalMs: 1,- PerPeerBurst: 10,- },- },- allowedPeerUIDs: map[uint32]struct{}{1000: {}},- peerCapabilities: map[uint32]Capability{- 1000: 3, // LegacyAll- },- rateLimiter: newRateLimiter(metrics, &RateLimitConfig{- PerPeerIntervalMs: 1,- PerPeerBurst: 10,- }, nil, nil),- }-- client, server := net.Pipe()-- go func() {- defer client.Close()- client.Write([]byte("invalid json\n"))- }()-- // handleConnection handles the connection and returns- proxy.handleConnection(server)- server.Close()-}--func TestHandleEnsureClusterKeysV2(t *testing.T) {- // Mock pvecm and ssh- origLookPath := execLookPath- origExec := execCommandFunc- defer func() {- execLookPath = origLookPath- execCommandFunc = origExec- }()-- execLookPath = func(file string) (string, error) {- return "/usr/bin/" + file, nil- }-- execCommandFunc = func(name string, arg ...string) *exec.Cmd {- args := strings.Join(arg, " ")- if name == "pvecm" && args == "status" {- output := "\nCluster information\n-------------------\nName: cluster\nConfig Version: 1\nTransport: knet\nSecure auth: on\n\nQuorum information\n------------------\nDate: Sun Jan 1 00:00:00 2023\nQuorum provider: corosync_votequorum\nNodes: 1\nNode ID: 0x00000001\nRing ID: 1.1\nQuorate: Yes\n\nVotequorum information\n----------------------\nExpected votes: 1\nHighest expected: 1\nTotal votes: 1\nQuorum: 1\nFlags: Quorate \n\nMembership information\n----------------------\n Nodeid Votes Name\n0x00000001 1 10.0.0.1 (local)\n"- return mockExecCommand(output)- }-- if name == "sh" && strings.Contains(args, "ssh") {- // Check if key exists (grep) - return empty (not found) to trigger adding- if strings.Contains(args, "grep -F") {- return mockExecCommandWithExitCode("", 1) // 1 = not found- }- // ensureTempWrapper or key push- return mockExecCommand("")- }- return mockExecCommand("")- }-- tmpDir := t.TempDir()- // Create SSH keys in tmpDir (for push)- os.WriteFile(filepath.Join(tmpDir, "id_ed25519.pub"), []byte("ssh-ed25519 KEY"), 0644)-- proxy := &Proxy{- sshKeyPath: tmpDir,- metrics: NewProxyMetrics("test"),- knownHosts: &mockKnownHosts{},- config: &Config{- AllowedSourceSubnets: []string{"10.0.0.0/24"},- },- }-- logger := zerolog.New(os.Stderr)- req := &RPCRequest{}-- resp, err := proxy.handleEnsureClusterKeysV2(context.Background(), req, logger)- if err != nil {- t.Fatalf("handleEnsureClusterKeysV2 failed: %v", err)- }-- m, ok := resp.(map[string]interface{})- if !ok {- t.Fatalf("expected map response, got %T", resp)- }-- if m["success_count"] != 1 {- t.Errorf("expected 1 success, got %v", m["success_count"])- }-}--// mockExecCommandWithExitCode helper needed for grep fail-func mockExecCommandWithExitCode(output string, exitCode int) *exec.Cmd {- cs := []string{"-test.run=TestHelperProcess", "--", output}- cmd := exec.Command(os.Args[0], cs...)- cmd.Env = []string{- "GO_WANT_HELPER_PROCESS=1",- "GO_HELPER_OUTPUT=" + output,- fmt.Sprintf("GO_HELPER_EXIT_CODE=%d", exitCode),- }- return cmd-}diff --git a/cmd/pulse-sensor-proxy/ssh.go b/cmd/pulse-sensor-proxy/ssh.godeleted file mode 100644index bd8043d110..0000000000--- a/cmd/pulse-sensor-proxy/ssh.go+++ /dev/null@@ -1,1058 +0,0 @@-package main--import (- "bufio"- "bytes"- "context"- "errors"- "fmt"- "io"- "net"- "os"- "os/exec"- "path/filepath"- "strconv"- "strings"- "sync"- "time"-- "github.com/rcourtman/pulse-go-rewrite/internal/ssh/knownhosts"- "github.com/rs/zerolog/log"-)--// Variable for testing to mock net.Interfaces-var netInterfaces = net.Interfaces--// Variable for testing to mock exec.LookPath-var execLookPath = exec.LookPath--// Variable for testing to mock os.Hostname-// Variables for testing-var (- osHostname = os.Hostname- osStat = os.Stat-)--// Variable for testing to mock exec.Command (for simple output)-var execCommandFunc = exec.Command--// Variable for testing to mock exec.CommandContext-var execCommandContextFunc = exec.CommandContext--const (- tempWrapperPath = "/usr/local/libexec/pulse-sensor-proxy/temp-wrapper.sh"- tempWrapperScript = `#!/bin/sh-set -eu--WRAPPER_PATH="${PULSE_SENSOR_WRAPPER:-/opt/pulse/sensor-proxy/bin/pulse-sensor-wrapper.sh}"--# Prefer the full wrapper when available so SMART disk temperatures are included-if [ -x "$WRAPPER_PATH" ]; then- exec "$WRAPPER_PATH"-fi--# Legacy locations (for older installations)-if [ -x /usr/local/bin/pulse-sensor-wrapper.sh ]; then- exec /usr/local/bin/pulse-sensor-wrapper.sh-fi--# Fallback to basic lm-sensors output (no SMART data)-if command -v sensors >/dev/null 2>&1; then- OUTPUT="$(sensors -j 2>/dev/null || true)"- if [ -n "$OUTPUT" ]; then- printf '%s\n' "$OUTPUT"- exit 0- fi-fi--if [ -r /sys/class/thermal/thermal_zone0/temp ]; then- RAW="$(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null || true)"- if [ -n "$RAW" ]; then- TEMP="$(awk -v raw="$RAW" 'BEGIN { if (raw == "") exit 1; printf "%.2f", raw / 1000.0 }' 2>/dev/null || true)"- if [ -n "$TEMP" ]; then- printf '{"rpitemp-virtual":{"temp1":{"temp1_input":%s}}}\n' "$TEMP"- exit 0- fi- fi-fi--exit 1-`-)--var proxmoxClusterKnownHostsPath = "/etc/pve/priv/known_hosts"--// execCommand executes a shell command and returns output-func execCommand(cmd string) (string, error) {- out, err := execCommandFunc("sh", "-c", cmd).CombinedOutput()- return string(out), err-}--// execCommandWithLimitsContext runs a shell command with output limits and context cancellation-func execCommandWithLimitsContext(ctx context.Context, cmd string, stdoutLimit, stderrLimit int64) (string, string, bool, bool, error) {- command := execCommandContextFunc(ctx, "sh", "-c", cmd)-- stdoutPipe, err := command.StdoutPipe()- if err != nil {- return "", "", false, false, fmt.Errorf("stdout pipe: %w", err)- }- stderrPipe, err := command.StderrPipe()- if err != nil {- return "", "", false, false, fmt.Errorf("stderr pipe: %w", err)- }-- if err := command.Start(); err != nil {- return "", "", false, false, err- }-- type pipeResult struct {- data []byte- exceeded bool- err error- }-- var wg sync.WaitGroup- wg.Add(2)-- stdoutCh := make(chan pipeResult, 1)- stderrCh := make(chan pipeResult, 1)-- go func() {- defer wg.Done()- data, exceeded, readErr := readAllWithLimit(stdoutPipe, stdoutLimit)- stdoutCh <- pipeResult{data: data, exceeded: exceeded, err: readErr}- }()-- go func() {- defer wg.Done()- data, exceeded, readErr := readAllWithLimit(stderrPipe, stderrLimit)- stderrCh <- pipeResult{data: data, exceeded: exceeded, err: readErr}- }()-- var stdoutRes, stderrRes pipeResult- wgDone := make(chan struct{})- go func() {- wg.Wait()- close(wgDone)- }()-- <-wgDone- stdoutRes = <-stdoutCh- stderrRes = <-stderrCh-- waitErr := command.Wait()-- if stdoutRes.err != nil {- return "", "", stdoutRes.exceeded, stderrRes.exceeded, fmt.Errorf("stdout read: %w", stdoutRes.err)- }- if stderrRes.err != nil {- return "", "", stdoutRes.exceeded, stderrRes.exceeded, fmt.Errorf("stderr read: %w", stderrRes.err)- }-- if waitErr != nil {- return string(stdoutRes.data), string(stderrRes.data), stdoutRes.exceeded, stderrRes.exceeded, waitErr- }-- return string(stdoutRes.data), string(stderrRes.data), stdoutRes.exceeded, stderrRes.exceeded, nil-}--func execCommandWithLimits(cmd string, stdoutLimit, stderrLimit int64) (string, string, bool, bool, error) {- command := execCommandFunc("sh", "-c", cmd)-- stdoutPipe, err := command.StdoutPipe()- if err != nil {- return "", "", false, false, fmt.Errorf("stdout pipe: %w", err)- }- stderrPipe, err := command.StderrPipe()- if err != nil {- return "", "", false, false, fmt.Errorf("stderr pipe: %w", err)- }-- if err := command.Start(); err != nil {- return "", "", false, false, err- }-- type pipeResult struct {- data []byte- exceeded bool- err error- }-- var wg sync.WaitGroup- wg.Add(2)-- stdoutCh := make(chan pipeResult, 1)- stderrCh := make(chan pipeResult, 1)-- go func() {- defer wg.Done()- data, exceeded, readErr := readAllWithLimit(stdoutPipe, stdoutLimit)- stdoutCh <- pipeResult{data: data, exceeded: exceeded, err: readErr}- }()-- go func() {- defer wg.Done()- data, exceeded, readErr := readAllWithLimit(stderrPipe, stderrLimit)- stderrCh <- pipeResult{data: data, exceeded: exceeded, err: readErr}- }()-- var stdoutRes, stderrRes pipeResult- wgDone := make(chan struct{})- go func() {- wg.Wait()- close(wgDone)- }()-- <-wgDone- stdoutRes = <-stdoutCh- stderrRes = <-stderrCh-- waitErr := command.Wait()-- if stdoutRes.err != nil {- return "", "", stdoutRes.exceeded, stderrRes.exceeded, fmt.Errorf("stdout read: %w", stdoutRes.err)- }- if stderrRes.err != nil {- return "", "", stdoutRes.exceeded, stderrRes.exceeded, fmt.Errorf("stderr read: %w", stderrRes.err)- }-- if waitErr != nil {- return string(stdoutRes.data), string(stderrRes.data), stdoutRes.exceeded, stderrRes.exceeded, waitErr- }-- return string(stdoutRes.data), string(stderrRes.data), stdoutRes.exceeded, stderrRes.exceeded, nil-}--func readAllWithLimit(r io.Reader, limit int64) ([]byte, bool, error) {- if limit <= 0 {- data, err := io.ReadAll(r)- return data, false, err- }-- const chunkSize = 32 * 1024- buf := make([]byte, chunkSize)- var out bytes.Buffer- var total int64- exceeded := false-- for {- n, err := r.Read(buf)- if n > 0 {- if total < limit {- remaining := limit - total- toWrite := n- if int64(n) > remaining {- toWrite = int(remaining)- exceeded = true- }- if toWrite > 0 {- if _, writeErr := out.Write(buf[:toWrite]); writeErr != nil {- return nil, exceeded, writeErr- }- }- if int64(n) > remaining {- exceeded = true- }- } else {- exceeded = true- }- total += int64(n)- }- if err != nil {- if err == io.EOF {- break- }- return nil, exceeded, err- }- }-- return out.Bytes(), exceeded, nil-}--func (p *Proxy) ensureHostKeyFromProxmox(ctx context.Context, node string) error {- if !isProxmoxHost() {- return fmt.Errorf("not running on Proxmox host")- }-- entries, err := loadProxmoxHostKeys(node)- if err != nil {- return err- }-- if err := p.knownHosts.EnsureWithEntries(ctx, node, 22, entries); err != nil {- return p.handleHostKeyEnsureError(node, err)- }-- log.Debug().- Str("node", node).- Msg("Loaded host key from Proxmox cluster store")- return nil-}--func (p *Proxy) handleHostKeyEnsureError(node string, err error) error {- var changeErr *knownhosts.HostKeyChangeError- if errors.As(err, &changeErr) {- log.Error().- Str("node", node).- Str("host_spec", changeErr.Host).- Msg("Detected SSH host key change")- if p.metrics != nil {- p.metrics.recordHostKeyChange(node)- }- }- return err-}--func loadProxmoxHostKeys(host string) ([][]byte, error) {- file, err := os.Open(proxmoxClusterKnownHostsPath)- if err != nil {- return nil, err- }- defer file.Close()-- var entries [][]byte- scanner := bufio.NewScanner(file)- for scanner.Scan() {- line := strings.TrimSpace(scanner.Text())- if line == "" || strings.HasPrefix(line, "#") {- continue- }- fields := strings.Fields(line)- if len(fields) < 3 {- continue- }- if !knownhosts.HostFieldMatches(host, fields[0]) {- continue- }-- comment := ""- if len(fields) > 3 {- comment = strings.Join(fields[3:], " ")- }- var entry string- if comment != "" {- entry = fmt.Sprintf("%s %s %s %s", host, fields[1], fields[2], comment)- } else {- entry = fmt.Sprintf("%s %s %s", host, fields[1], fields[2])- }- entries = append(entries, []byte(entry))- }- if err := scanner.Err(); err != nil {- return nil, err- }- if len(entries) == 0 {- return nil, fmt.Errorf("no Proxmox host keys found for %s in %s", host, proxmoxClusterKnownHostsPath)- }- return entries, nil-}--// getPublicKeyFrom reads the SSH public key from a specific directory-func (p *Proxy) getPublicKeyFrom(keyDir string) (string, error) {- pubKeyPath := filepath.Join(keyDir, "id_ed25519.pub")- data, err := os.ReadFile(pubKeyPath)- if err != nil {- return "", err- }- return strings.TrimSpace(string(data)), nil-}--// buildAuthorizedKey constructs an authorized_keys entry with from= IP restrictions-func (p *Proxy) buildAuthorizedKey(pubKey string) (string, error) {- subnets := p.config.AllowedSourceSubnets- if len(subnets) == 0 {- return "", fmt.Errorf("no allowed source subnets configured or detected")- }-- // Build from= clause with all allowed subnets- fromClause := fmt.Sprintf(`from="%s"`, strings.Join(subnets, ","))-- // Comment helps identify and upgrade this key later- const comment = "pulse-sensor-proxy"-- // Forced command with all restrictions- forced := fmt.Sprintf(`command="%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty`, tempWrapperPath)-- // Format: from="...",command="...",no-* ssh-rsa AAAA... pulse-sensor-proxy- return fmt.Sprintf(`%s,%s %s %s`, fromClause, forced, pubKey, comment), nil-}--func (p *Proxy) ensureHostKey(node string) error {- if p.knownHosts == nil {- return fmt.Errorf("host key manager not configured")- }-- ctx := context.Background()- if isProxmoxHost() {- if err := p.ensureHostKeyFromProxmox(ctx, node); err == nil {- return nil- } else {- if p.config != nil && p.config.RequireProxmoxHostkeys {- return err- }- log.Warn().- Str("node", node).- Err(err).- Msg("Failed to load host key from Proxmox; falling back to ssh-keyscan")- }- } else if p.config != nil && p.config.RequireProxmoxHostkeys {- return fmt.Errorf("require_proxmox_hostkeys enabled but not running on Proxmox host")- }-- if err := p.knownHosts.Ensure(ctx, node); err != nil {- return p.handleHostKeyEnsureError(node, err)- }- return nil-}--func (p *Proxy) sshCommonOptions() string {- if p.knownHosts == nil {- return "-o StrictHostKeyChecking=yes -o BatchMode=yes"- }- return fmt.Sprintf("-o StrictHostKeyChecking=yes -o BatchMode=yes -o UserKnownHostsFile=%s -o GlobalKnownHostsFile=/dev/null",- shellQuote(p.knownHosts.Path()))-}--func shellQuote(arg string) string {- if arg == "" {- return "''"- }- if !strings.Contains(arg, "'") {- return "'" + arg + "'"- }- return strconv.Quote(arg)-}--func (p *Proxy) ensureTempWrapper(nodeHost, commonOpts string) error {- dir := filepath.Dir(tempWrapperPath)- mkdirCmd := fmt.Sprintf(- `ssh %s -o ConnectTimeout=10 root@%s "mkdir -p %s && chmod 755 %s"`,- commonOpts,- nodeHost,- dir,- dir,- )-- if _, err := execCommand(mkdirCmd); err != nil {- return fmt.Errorf("failed to prepare temperature wrapper directory on %s: %w", nodeHost, err)- }-- uploadCmd := fmt.Sprintf(- `ssh %s -o ConnectTimeout=10 root@%s "cat > %s <<'EOF'-%s-EOF-chmod 755 %s"`,- commonOpts,- nodeHost,- tempWrapperPath,- tempWrapperScript,- tempWrapperPath,- )-- if _, err := execCommand(uploadCmd); err != nil {- return fmt.Errorf("failed to install temperature wrapper on %s: %w", nodeHost, err)- }-- return nil-}--// pushSSHKeyFrom pushes a public key from a specific directory to a node-func (p *Proxy) pushSSHKeyFrom(nodeHost, keyDir string) error {- startTime := time.Now()- nodeLabel := sanitizeNodeLabel(nodeHost)-- pubKey, err := p.getPublicKeyFrom(keyDir)- if err != nil {- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return fmt.Errorf("failed to get public key from %s: %w", keyDir, err)- }-- // Build the restricted authorized_keys entry- entry, err := p.buildAuthorizedKey(pubKey)- if err != nil {- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return fmt.Errorf("failed to build authorized key: %w", err)- }-- if err := p.ensureHostKey(nodeHost); err != nil {- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return fmt.Errorf("failed to ensure host key for %s: %w", nodeHost, err)- }-- commonOpts := p.sshCommonOptions()- if err := p.ensureTempWrapper(nodeHost, commonOpts); err != nil {- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return fmt.Errorf("failed to stage temperature wrapper on %s: %w", nodeHost, err)- }-- // Check if the exact restricted entry already exists- checkCmd := fmt.Sprintf(- `ssh %s -o ConnectTimeout=10 root@%s "grep -F '%s' /root/.ssh/authorized_keys 2>/dev/null"`,- commonOpts,- nodeHost,- entry,- )-- if output, _ := execCommand(checkCmd); strings.Contains(output, entry) {- log.Debug().Str("node", nodeHost).Msg("SSH key already present with from= restrictions")- p.metrics.sshRequests.WithLabelValues(nodeLabel, "success").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return nil- }-- // Remove old pulse-temp-proxy and pulse-sensor-proxy entries (for upgrade path)- removeOldCmd := fmt.Sprintf(- `ssh %s -o ConnectTimeout=10 root@%s "mkdir -p /root/.ssh && chmod 700 /root/.ssh && grep -v -e 'pulse-temp-proxy$' -e 'pulse-sensor-proxy$' /root/.ssh/authorized_keys > /root/.ssh/authorized_keys.tmp 2>/dev/null || touch /root/.ssh/authorized_keys.tmp"`,- commonOpts,- nodeHost,- )-- if _, err := execCommand(removeOldCmd); err != nil {- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return fmt.Errorf("failed to prepare authorized_keys on %s: %w", nodeHost, err)- }-- // Add the new restricted key and atomically replace the file- addCmd := fmt.Sprintf(- `ssh %s -o ConnectTimeout=10 root@%s "echo '%s' >> /root/.ssh/authorized_keys.tmp && mv /root/.ssh/authorized_keys.tmp /root/.ssh/authorized_keys && chmod 600 /root/.ssh/authorized_keys"`,- commonOpts,- nodeHost,- entry,- )-- if _, err := execCommand(addCmd); err != nil {- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return fmt.Errorf("failed to add SSH key to %s: %w", nodeHost, err)- }-- log.Info().- Str("node", nodeHost).- Str("key_dir", keyDir).- Strs("allowed_subnets", p.config.AllowedSourceSubnets).- Msg("SSH key installed with from= IP restrictions")-- p.metrics.sshRequests.WithLabelValues(nodeLabel, "success").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return nil-}--// testSSHConnection verifies SSH connectivity to a node-func (p *Proxy) testSSHConnection(nodeHost string) error {- startTime := time.Now()- nodeLabel := sanitizeNodeLabel(nodeHost)-- privKeyPath := filepath.Join(p.sshKeyPath, "id_ed25519")- if err := p.ensureHostKey(nodeHost); err != nil {- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return fmt.Errorf("failed to ensure host key for %s: %w", nodeHost, err)- }-- commonOpts := p.sshCommonOptions()- cmd := fmt.Sprintf(- `ssh %s -i %s -T -n -o LogLevel=ERROR -o ConnectTimeout=5 root@%s ""`,- commonOpts,- shellQuote(privKeyPath),- nodeHost,- )-- _, stderr, stdoutExceeded, stderrExceeded, err := execCommandWithLimits(cmd, p.maxSSHOutputBytes, p.maxSSHOutputBytes)- if stdoutExceeded {- log.Warn().Str("node", nodeHost).Int64("limit_bytes", p.maxSSHOutputBytes).Msg("SSH test output exceeded limit")- if p.metrics != nil {- p.metrics.recordSSHOutputOversized(nodeHost)- }- return fmt.Errorf("ssh test output exceeded %d bytes", p.maxSSHOutputBytes)- }-- if stderrExceeded {- log.Warn().Str("node", nodeHost).Int64("limit_bytes", p.maxSSHOutputBytes).Msg("SSH test stderr exceeded limit")- }-- if err != nil {- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- stderrMsg := strings.TrimSpace(stderr)- if stderrMsg != "" {- return fmt.Errorf("SSH test failed: %w (stderr: %s)", err, stderrMsg)- }- return fmt.Errorf("SSH test failed: %w", err)- }-- // The forced command will run "sensors -j" instead of "echo test"- // So we should get JSON output, not "test"- // For now, just check that connection succeeded- p.metrics.sshRequests.WithLabelValues(nodeLabel, "success").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return nil-}--// getTemperatureViaSSH fetches temperature data from a node-func (p *Proxy) getTemperatureViaSSH(ctx context.Context, nodeHost string) (string, error) {- startTime := time.Now()- nodeLabel := sanitizeNodeLabel(nodeHost)- localNode := isLocalNode(nodeHost)-- if localNode {- log.Debug().Str("node", nodeHost).Msg("Self-monitoring detected, using SSH wrapper for SMART temperatures")- }-- privKeyPath := filepath.Join(p.sshKeyPath, "id_ed25519")- if err := p.ensureHostKey(nodeHost); err != nil {- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return "", fmt.Errorf("failed to ensure host key for %s: %w", nodeHost, err)- }-- commonOpts := p.sshCommonOptions()-- // Since we use a forced wrapper command, any SSH connection runs the wrapper- // We don't need to specify the command- cmd := fmt.Sprintf(- `ssh %s -i %s -T -n -o LogLevel=ERROR -o ConnectTimeout=5 root@%s ""`,- commonOpts,- shellQuote(privKeyPath),- nodeHost,- )-- stdout, stderr, stdoutExceeded, stderrExceeded, err := execCommandWithLimitsContext(ctx, cmd, p.maxSSHOutputBytes, p.maxSSHOutputBytes)- if stdoutExceeded {- log.Warn().Str("node", nodeHost).Int64("limit_bytes", p.maxSSHOutputBytes).Msg("SSH temperature output exceeded limit")- if p.metrics != nil {- p.metrics.recordSSHOutputOversized(nodeHost)- }- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return "", fmt.Errorf("ssh output exceeded %d bytes", p.maxSSHOutputBytes)- }-- if stderrExceeded {- log.Warn().Str("node", nodeHost).Int64("limit_bytes", p.maxSSHOutputBytes).Msg("SSH temperature stderr exceeded limit")- }-- if err != nil {- if localNode {- log.Warn().- Str("node", nodeHost).- Err(err).- Msg("SSH temperature collection failed on local node, falling back to direct sensors")-- if fallback, localErr := p.getTemperatureLocal(ctx); localErr == nil && strings.TrimSpace(fallback) != "" {- p.metrics.sshRequests.WithLabelValues(nodeLabel, "success").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return fallback, nil- }- }-- p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- stderrMsg := strings.TrimSpace(stderr)- if stderrMsg != "" {- return "", fmt.Errorf("failed to fetch temperatures: %w (stderr: %s)", err, stderrMsg)- }- return "", fmt.Errorf("failed to fetch temperatures: %w", err)- }-- p.metrics.sshRequests.WithLabelValues(nodeLabel, "success").Inc()- p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())- return stdout, nil-}--// discoverClusterNodes discovers all nodes in the Proxmox cluster-// Returns IP addresses of cluster nodes-// For standalone nodes (no cluster), returns the host's own addresses-func discoverClusterNodes() ([]string, error) {- // Check if pvecm is available (only on Proxmox hosts)- if _, err := execLookPath("pvecm"); err != nil {- return nil, fmt.Errorf("pvecm not found - not running on Proxmox host")- }-- // Get cluster status with IP addresses- cmd := execCommandFunc("pvecm", "status")- var out, stderr bytes.Buffer- cmd.Stdout = &out- cmd.Stderr = &stderr- err := cmd.Run()-- // pvecm status exits with code 2 or 255 on standalone nodes (not in a cluster)- // Also handle LXC containers where pvecm can't access corosync IPC- // Treat these as valid cases and discover local host addresses- if err != nil {- stderrStr := stderr.String()- stdoutStr := out.String()- combinedOutput := stderrStr + stdoutStr-- // First check for IPC/permission errors - these indicate a cluster exists but we can't access it- // These should NOT be treated as standalone mode- ipcErrorIndicators := []string{- "ipcc_send_rec",- "Unable to load access control list",- "access control list",- }-- for _, indicator := range ipcErrorIndicators {- if strings.Contains(combinedOutput, indicator) {- log.Warn().- Str("stderr", stderrStr).- Msg("Cannot access Proxmox cluster IPC - cluster validation disabled. Add nodes to allowed_nodes in config if needed.")- // Return error to disable cluster validation rather than falling back to incorrect standalone mode- return nil, fmt.Errorf("pvecm cluster IPC access denied (check systemd restrictions or run outside container): %s", stderrStr)- }- }-- // Now check for true standalone/no-cluster patterns- // These indicate the node genuinely isn't part of a cluster- standaloneIndicators := []string{- // Configuration missing- "does not exist", "not found", "no such file",- // Cluster state- "not part of a cluster", "no cluster", "standalone",- }-- isStandalone := false- for _, indicator := range standaloneIndicators {- if strings.Contains(strings.ToLower(combinedOutput), strings.ToLower(indicator)) {- isStandalone = true- break- }- }-- if isStandalone {- // Log at INFO level since this is expected for standalone scenarios- log.Info().- Str("exit_code", fmt.Sprintf("%v", err)).- Msg("Standalone Proxmox node detected - discovering local host addresses for validation")- return discoverLocalHostAddresses()- }-- // For truly unexpected errors (rare), fail with full context for debugging- log.Warn().- Err(err).- Str("stderr", stderrStr).- Str("stdout", stdoutStr).- Msg("pvecm status failed with unexpected error - please report this if temperature monitoring doesn't work")- return nil, fmt.Errorf("failed to get cluster status: %w (stderr: %s, stdout: %s)", err, stderrStr, stdoutStr)- }-- // Parse output to extract IP addresses- return parseClusterNodes(out.String())-}--// parseClusterNodes parses pvecm status output to extract IP addresses-func parseClusterNodes(output string) ([]string, error) {- var nodes []string- lines := strings.Split(output, "\n")- for _, line := range lines {- if strings.Contains(strings.ToLower(line), "qdevice") {- continue- }- fields := strings.Fields(line)- // Need at least 2 fields to be a valid node line (id + ip/name)- if len(fields) < 2 {- continue- }-- // Iterate through fields to find the IP address- for _, field := range fields {- // Check if it's a valid IP- if ip := net.ParseIP(field); ip != nil {- nodes = append(nodes, field)- break- }- }- }-- if len(nodes) == 0 {- return nil, fmt.Errorf("no cluster nodes found with IP addresses")- }-- return nodes, nil-}--// discoverLocalHostAddresses discovers all addresses of the local host-// Used for standalone nodes that aren't part of a cluster-func discoverLocalHostAddresses() ([]string, error) {- addresses := make(map[string]struct{})-- // Get hostname and FQDN- if hostname, err := os.Hostname(); err == nil && hostname != "" {- addresses[strings.ToLower(hostname)] = struct{}{}-- // Try to get FQDN- cmd := execCommandFunc("hostname", "-f")- if out, err := cmd.Output(); err == nil {- fqdn := strings.TrimSpace(string(out))- if fqdn != "" && fqdn != hostname {- addresses[strings.ToLower(fqdn)] = struct{}{}- }- }- }-- // This is more reliable than shelling out to 'ip addr' and works even with strict systemd restrictions- ipCount := 0- interfaces, err := netInterfaces()- if err != nil {- // Check if this is an AF_NETLINK restriction error from systemd- if strings.Contains(err.Error(), "netlinkrib") || strings.Contains(err.Error(), "address family not supported") {- log.Warn().- Err(err).- Msg("AF_NETLINK restricted by systemd - falling back to 'ip addr' command. Update systemd unit to add AF_NETLINK to RestrictAddressFamilies.")- return discoverLocalHostAddressesFallback()- }- log.Warn().- Err(err).- Msg("Failed to enumerate network interfaces - temperature monitoring may require manual allowed_nodes configuration")- } else {- for _, iface := range interfaces {- // Skip loopback interfaces- if iface.Flags&net.FlagLoopback != 0 {- continue- }-- // Skip interfaces that are down- if iface.Flags&net.FlagUp == 0 {- continue- }-- addrs, err := iface.Addrs()- if err != nil {- log.Debug().- Err(err).- Str("interface", iface.Name).- Msg("Failed to get addresses for interface")- continue- }-- for _, addr := range addrs {- var ip net.IP- switch v := addr.(type) {- case *net.IPNet:- ip = v.IP- case *net.IPAddr:- ip = v.IP- default:- continue- }-- // Skip loopback addresses- if ip.IsLoopback() {- continue- }-- // Skip link-local IPv6 addresses- if ip.IsLinkLocalUnicast() {- continue- }-- // Skip unspecified addresses- if ip.IsUnspecified() {- continue- }-- addresses[ip.String()] = struct{}{}- ipCount++- }- }- }-- // Convert map to slice- result := make([]string, 0, len(addresses))- for addr := range addresses {- result = append(result, addr)- }-- if len(result) == 0 {- return nil, fmt.Errorf("no local host addresses found")- }-- // Log helpful info about discovered addresses- logger := log.Info().- Strs("addresses", result).- Int("ip_count", ipCount).- Int("hostname_count", len(result)-ipCount)-- if ipCount == 0 {- logger.Msg("WARNING: No IP addresses discovered for standalone node - only hostnames available. If temperature monitoring fails with 'node_not_cluster_member' errors, add the node's IP to allowed_nodes in /etc/pulse-sensor-proxy/config.yaml")- } else {- logger.Msg("Discovered local host addresses for standalone node validation")- }-- return result, nil-}--// discoverLocalHostAddressesFallback uses 'ip addr' command when AF_NETLINK is restricted-func discoverLocalHostAddressesFallback() ([]string, error) {- addresses := make(map[string]struct{})-- // Get hostname and FQDN (same as native version)- if hostname, err := os.Hostname(); err == nil && hostname != "" {- addresses[strings.ToLower(hostname)] = struct{}{}- cmd := execCommandFunc("hostname", "-f")- if out, err := cmd.Output(); err == nil {- fqdn := strings.TrimSpace(string(out))- if fqdn != "" && fqdn != hostname {- addresses[strings.ToLower(fqdn)] = struct{}{}- }- }- }-- // Use 'ip addr' to get IP addresses- cmd := execCommandFunc("ip", "addr", "show")- out, err := cmd.Output()- if err != nil {- log.Warn().Err(err).Msg("Failed to run 'ip addr' command")- // Return at least the hostname- result := make([]string, 0, len(addresses))- for addr := range addresses {- result = append(result, addr)- }- return result, nil- }-- // Parse 'ip addr' output for inet/inet6 lines- // Example: " inet 192.168.0.5/24 brd 192.168.0.255 scope global eno1"- ipCount := 0- lines := strings.Split(string(out), "\n")- for _, line := range lines {- line = strings.TrimSpace(line)- if !strings.HasPrefix(line, "inet ") && !strings.HasPrefix(line, "inet6 ") {- continue- }-- fields := strings.Fields(line)- if len(fields) < 2 {- continue- }-- // Second field is the IP/CIDR (e.g., "192.168.0.5/24")- ipCIDR := fields[1]- ipStr, _, _ := strings.Cut(ipCIDR, "/")-- ip := net.ParseIP(ipStr)- if ip == nil || ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsUnspecified() {- continue- }-- addresses[ip.String()] = struct{}{}- ipCount++- }-- result := make([]string, 0, len(addresses))- for addr := range addresses {- result = append(result, addr)- }-- if len(result) == 0 {- return nil, fmt.Errorf("no local host addresses found")- }-- // Log helpful info about discovered addresses- logger := log.Info().- Strs("addresses", result).- Int("ip_count", ipCount).- Int("hostname_count", len(result)-ipCount)-- if ipCount == 0 {- logger.Msg("WARNING: No IP addresses discovered via 'ip addr' fallback - only hostnames available. Temperature monitoring may require manual allowed_nodes configuration.")- } else {- logger.Msg("Discovered local host addresses via 'ip addr' fallback (systemd unit needs AF_NETLINK update)")- }-- return result, nil-}--// isProxmoxHost checks if we're running on a Proxmox host-func isProxmoxHost() bool {- // Check for pvecm command- if _, err := execLookPath("pvecm"); err == nil {- return true- }- // Check for /etc/pve directory- // Check for /etc/pve directory- if info, err := osStat("/etc/pve"); err == nil && info.IsDir() {- return true- }- return false-}--// isLocalNode checks if the requested node is the local machine-func isLocalNode(nodeHost string) bool {- // Get local hostname (short)- hostname, err := osHostname()- if err == nil {- // Match short hostname- if strings.EqualFold(nodeHost, hostname) {- return true- }- // Match FQDN if nodeHost contains dots- if strings.Contains(nodeHost, ".") {- cmd := execCommandFunc("hostname", "-f")- if output, err := cmd.Output(); err == nil {- fqdn := strings.TrimSpace(string(output))- if strings.EqualFold(nodeHost, fqdn) {- return true- }- }- }- }-- // Check if nodeHost is a local IP address- ifaces, err := netInterfaces()- if err != nil {- return false- }-- for _, iface := range ifaces {- addrs, err := iface.Addrs()- if err != nil {- continue- }- for _, addr := range addrs {- var ip net.IP- switch v := addr.(type) {- case *net.IPNet:- ip = v.IP- case *net.IPAddr:- ip = v.IP- }- if ip != nil && ip.String() == nodeHost {- return true- }- }- }-- // Check special cases- if nodeHost == "localhost" || nodeHost == "127.0.0.1" || nodeHost == "::1" {- return true- }-- return false-}--// getTemperatureLocal collects temperature data from the local machine-func (p *Proxy) getTemperatureLocal(ctx context.Context) (string, error) {- // Run the same command that the wrapper script runs with context timeout- cmd := execCommandContextFunc(ctx, "sensors", "-j")- output, err := cmd.Output()- if err != nil {- // Try without -j flag as fallback- cmd = execCommandContextFunc(ctx, "sensors")- if _, err = cmd.Output(); err != nil {- return "", fmt.Errorf("failed to run sensors: %w", err)- }- // Return empty JSON object for non-JSON output- return "{}", nil- }-- result := strings.TrimSpace(string(output))- if result == "" {- return "{}", nil- }-- return result, nil-}diff --git a/cmd/pulse-sensor-proxy/ssh_parsing_test.go b/cmd/pulse-sensor-proxy/ssh_parsing_test.godeleted file mode 100644index a1ff37ebf4..0000000000--- a/cmd/pulse-sensor-proxy/ssh_parsing_test.go+++ /dev/null@@ -1,85 +0,0 @@-package main--import (- "testing"-)--func TestParseClusterNodes(t *testing.T) {- tests := []struct {- name string- output string- want []string- wantErr bool- }{- {- name: "standard output",- output: `Membership information------------------------ Nodeid Votes Name-0x00000001 1 192.168.1.10-0x00000002 1 192.168.1.11`,- want: []string{"192.168.1.10", "192.168.1.11"},- },- {- name: "output with QDevice flags",- output: `Membership information------------------------ Nodeid Votes Name-0x00000001 1 A,V,NMW 192.168.1.10-0x00000002 1 A,V,NMW 192.168.1.11`,- want: []string{"192.168.1.10", "192.168.1.11"},- },- {- name: "output with local suffix",- output: `Membership information------------------------ Nodeid Votes Name-0x00000001 1 192.168.1.10 (local)-0x00000002 1 192.168.1.11`,- want: []string{"192.168.1.10", "192.168.1.11"},- },- {- name: "mixed output",- output: `Membership information------------------------ Nodeid Votes Name-0x00000001 1 A,V,NMW 192.168.1.10 (local)-0x00000002 1 192.168.1.11`,- want: []string{"192.168.1.10", "192.168.1.11"},- },- {- name: "no nodes",- output: "some random text",- wantErr: true,- },- {- name: "numeric node id format",- output: `Membership information------------------------ Nodeid Votes Name-1 10.0.0.5 2`,- want: []string{"10.0.0.5"},- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got, err := parseClusterNodes(tt.output)- if (err != nil) != tt.wantErr {- t.Errorf("parseClusterNodes() error = %v, wantErr %v", err, tt.wantErr)- return- }- if !tt.wantErr {- if len(got) != len(tt.want) {- t.Errorf("parseClusterNodes() got = %v, want %v", got, tt.want)- } else {- for i := range got {- if got[i] != tt.want[i] {- t.Errorf("parseClusterNodes() got[%d] = %v, want %v", i, got[i], tt.want[i])- }- }- }- }- })- }-}diff --git a/cmd/pulse-sensor-proxy/ssh_test.go b/cmd/pulse-sensor-proxy/ssh_test.godeleted file mode 100644index 4cc9782026..0000000000--- a/cmd/pulse-sensor-proxy/ssh_test.go+++ /dev/null@@ -1,1017 +0,0 @@-package main--import (- "bytes"- "context"- "encoding/json"- "errors"- "fmt"- "net"- "os"- "os/exec"- "path/filepath"- "strings"- "testing"-- "github.com/rcourtman/pulse-go-rewrite/internal/ssh/knownhosts"-)--func setupTempWrapper(t *testing.T) (scriptPath, thermalFile, binDir, baseDir string) {- t.Helper()-- baseDir = t.TempDir()-- thermalDir := filepath.Join(baseDir, "sys", "class", "thermal", "thermal_zone0")- if err := os.MkdirAll(thermalDir, 0o755); err != nil {- t.Fatalf("failed to create thermal zone directory: %v", err)- }- thermalFile = filepath.Join(thermalDir, "temp")-- scriptContent := strings.ReplaceAll(tempWrapperScript, "/sys/class/thermal/thermal_zone0/temp", thermalFile)- scriptPath = filepath.Join(baseDir, "temp-wrapper.sh")- if err := os.WriteFile(scriptPath, []byte(scriptContent), 0o755); err != nil {- t.Fatalf("failed to write wrapper script: %v", err)- }-- binDir = filepath.Join(baseDir, "bin")- if err := os.MkdirAll(binDir, 0o755); err != nil {- t.Fatalf("failed to create bin directory: %v", err)- }-- linkCommand := func(name string) {- target, err := exec.LookPath(name)- if err != nil {- t.Fatalf("required command %q not found on host: %v", name, err)- }- content := fmt.Sprintf("#!/bin/sh\nexec %s \"$@\"\n", target)- if err := os.WriteFile(filepath.Join(binDir, name), []byte(content), 0o755); err != nil {- t.Fatalf("failed to create shim for %s: %v", name, err)- }- }-- linkCommand("awk")- linkCommand("cat")-- return scriptPath, thermalFile, binDir, baseDir-}--func runTempWrapper(t *testing.T, scriptPath, binDir string, extraEnv ...string) []byte {- t.Helper()- cmd := exec.Command("sh", scriptPath)- env := []string{"PATH=" + binDir}- env = append(env, extraEnv...)- cmd.Env = env- output, err := cmd.CombinedOutput()- if err != nil {- t.Fatalf("temp wrapper failed: %v (output: %s)", err, strings.TrimSpace(string(output)))- }- return output-}--func TestTempWrapperFallbackWhenSensorsMissing(t *testing.T) {- scriptPath, thermalFile, binDir, _ := setupTempWrapper(t)-- if err := os.WriteFile(thermalFile, []byte("51234\n"), 0o644); err != nil {- t.Fatalf("failed to write thermal zone temperature: %v", err)- }-- output := runTempWrapper(t, scriptPath, binDir)-- var data map[string]map[string]map[string]float64- if err := json.Unmarshal(output, &data); err != nil {- t.Fatalf("failed to parse wrapper output as JSON: %v (output: %s)", err, strings.TrimSpace(string(output)))- }-- temp1, ok := data["rpitemp-virtual"]["temp1"]["temp1_input"]- if !ok {- t.Fatalf("expected rpitemp-virtual temp1 reading in output: %v", data)- }- if temp1 != 51.23 {- t.Fatalf("expected converted temperature 51.23, got %.2f", temp1)- }-}--func TestTempWrapperFallbackWhenSensorsEmpty(t *testing.T) {- scriptPath, thermalFile, binDir, _ := setupTempWrapper(t)-- sensorsStub := filepath.Join(binDir, "sensors")- content := "#!/bin/sh\nexit 0\n"- if err := os.WriteFile(sensorsStub, []byte(content), 0o755); err != nil {- t.Fatalf("failed to create sensors stub: %v", err)- }-- if err := os.WriteFile(thermalFile, []byte("47890\n"), 0o644); err != nil {- t.Fatalf("failed to write thermal zone temperature: %v", err)- }-- output := runTempWrapper(t, scriptPath, binDir)-- var data map[string]map[string]map[string]float64- if err := json.Unmarshal(output, &data); err != nil {- t.Fatalf("failed to parse wrapper output as JSON: %v (output: %s)", err, strings.TrimSpace(string(output)))- }-- temp1, ok := data["rpitemp-virtual"]["temp1"]["temp1_input"]- if !ok {- t.Fatalf("expected rpitemp-virtual temp1 reading in output: %v", data)- }- if temp1 != 47.89 {- t.Fatalf("expected converted temperature 47.89, got %.2f", temp1)- }-}--func TestTempWrapperPrefersSensorsOutput(t *testing.T) {- scriptPath, thermalFile, binDir, _ := setupTempWrapper(t)-- jsonOutput := `{"cpu_thermal-virtual-0":{"temp1":{"temp1_input":42.5}}}`- sensorsStub := filepath.Join(binDir, "sensors")- content := fmt.Sprintf("#!/bin/sh\nprintf '%s'\n", jsonOutput)- if err := os.WriteFile(sensorsStub, []byte(content), 0o755); err != nil {- t.Fatalf("failed to create sensors stub: %v", err)- }-- // Ensure thermal zone file exists but should be ignored- if err := os.WriteFile(thermalFile, []byte("40000\n"), 0o644); err != nil {- t.Fatalf("failed to write thermal zone temperature: %v", err)- }-- output := runTempWrapper(t, scriptPath, binDir)-- trimmed := strings.TrimSpace(string(output))- if trimmed != jsonOutput {- t.Fatalf("expected wrapper to return sensors output %s, got %s", jsonOutput, trimmed)- }-}--func TestTempWrapperPrefersOverrideWrapper(t *testing.T) {- scriptPath, _, binDir, baseDir := setupTempWrapper(t)-- overrideDir := filepath.Join(baseDir, "override")- if err := os.MkdirAll(overrideDir, 0o755); err != nil {- t.Fatalf("failed to create override directory: %v", err)- }-- overridePath := filepath.Join(overrideDir, "pulse-sensor-wrapper.sh")- expectedOutput := `{"smart":[{"device":"/dev/test","temperature":42}]}`- overrideScript := fmt.Sprintf("#!/bin/sh\nprintf '%s'\n", expectedOutput)- if err := os.WriteFile(overridePath, []byte(overrideScript), 0o755); err != nil {- t.Fatalf("failed to write override wrapper: %v", err)- }-- output := runTempWrapper(t, scriptPath, binDir, "PULSE_SENSOR_WRAPPER="+overridePath)- if strings.TrimSpace(string(output)) != expectedOutput {- t.Fatalf("expected override wrapper output %s, got %s", expectedOutput, strings.TrimSpace(string(output)))- }-}--func TestReadAllWithLimit(t *testing.T) {- reader := bytes.NewBufferString("abcdefg")- data, exceeded, err := readAllWithLimit(reader, 4)- if err != nil {- t.Fatalf("readAllWithLimit returned error: %v", err)- }- if string(data) != "abcd" {- t.Fatalf("expected truncated output 'abcd', got %q", string(data))- }- if !exceeded {- t.Fatalf("expected exceeded flag when data exceeds limit")- }-- reader2 := bytes.NewBufferString("xyz")- data, exceeded, err = readAllWithLimit(reader2, 10)- if err != nil {- t.Fatalf("readAllWithLimit returned error: %v", err)- }- if string(data) != "xyz" {- t.Fatalf("expected full output 'xyz', got %q", string(data))- }- if exceeded {- t.Fatalf("did not expect exceeded flag for small output")- }-- reader3 := bytes.NewBufferString("12345")- data, exceeded, err = readAllWithLimit(reader3, 0)- if err != nil {- t.Fatalf("readAllWithLimit returned error: %v", err)- }- if string(data) != "12345" || exceeded {- t.Fatalf("expected unlimited read to return full data without exceeding")- }-}--func TestDiscoverLocalHostAddresses(t *testing.T) {- // This test verifies that discoverLocalHostAddresses returns valid addresses- // It will vary by host but should always return at least hostname or IP addresses- addresses, err := discoverLocalHostAddresses()- if err != nil {- t.Fatalf("discoverLocalHostAddresses failed: %v", err)- }-- if len(addresses) == 0 {- t.Fatal("expected at least one address from discoverLocalHostAddresses")- }-- // Verify addresses are non-empty and don't contain loopback- for _, addr := range addresses {- if addr == "" {- t.Error("got empty address in results")- }- if addr == "127.0.0.1" || addr == "::1" {- t.Errorf("discoverLocalHostAddresses should not return loopback address: %s", addr)- }- if strings.HasPrefix(addr, "127.") {- t.Errorf("discoverLocalHostAddresses should not return loopback range: %s", addr)- }- if strings.HasPrefix(addr, "fe80:") {- t.Errorf("discoverLocalHostAddresses should not return link-local IPv6: %s", addr)- }- }-- t.Logf("Discovered %d local addresses: %v", len(addresses), addresses)-}--// TestStandaloneNodeErrorPatterns verifies that the proxy correctly identifies-// all known error patterns from standalone nodes and LXC containers-func TestStandaloneNodeErrorPatterns(t *testing.T) {- // These are real error messages users reported in GitHub issues- standalonePatterns := []struct {- name string- stderr string- stdout string- issueNo string // GitHub issue reference- }{- {- name: "classic standalone node",- stderr: "Error: Corosync config '/etc/pve/corosync.conf' does not exist - is this node part of a cluster?\n",- stdout: "",- issueNo: "common",- },- {- name: "LXC ipcc_send_rec errors (issue #571)",- stderr: "ipcc_send_rec[1] failed: Unknown error -1\nipcc_send_rec[2] failed: Unknown error -1\nipcc_send_rec[3] failed: Unknown error -1\nUnable to load access control list: Unknown error -1\n",- stdout: "",- issueNo: "#571",- },- {- name: "unknown error -1 only",- stderr: "Unknown error -1\n",- stdout: "",- issueNo: "#571",- },- {- name: "access control list error",- stderr: "Unable to load access control list: Unknown error -1\n",- stdout: "",- issueNo: "#571",- },- {- name: "not part of cluster message",- stdout: "This node is not part of a cluster\n",- stderr: "",- issueNo: "common",- },- {- name: "mixed stdout/stderr (some PVE versions)",- stdout: "ipcc_send_rec failed: Unknown error -1\n",- stderr: "",- issueNo: "#571",- },- {- name: "no cluster keyword",- stderr: "Error: no cluster configuration\n",- stdout: "",- issueNo: "variation",- },- {- name: "IPC failure variant",- stderr: "IPC communication error\n",- stdout: "",- issueNo: "variation",- },- }-- // Use the same detection logic as the actual code- standaloneIndicators := []string{- "does not exist", "not found", "no such file",- "not part of a cluster", "no cluster", "standalone",- "ipcc_send_rec", "IPC", "communication failed", "connection refused",- "Unknown error -1", "Unable to load", "access denied", "permission denied",- "access control list",- }-- for _, tc := range standalonePatterns {- t.Run(tc.name, func(t *testing.T) {- combinedOutput := tc.stderr + tc.stdout-- // Check using the permissive detection strategy- isStandalone := false- for _, indicator := range standaloneIndicators {- if strings.Contains(strings.ToLower(combinedOutput), strings.ToLower(indicator)) {- isStandalone = true- break- }- }-- if !isStandalone {- t.Errorf("Failed to detect standalone/LXC pattern from %s:\n stderr: %q\n stdout: %q",- tc.issueNo, tc.stderr, tc.stdout)- } else {- t.Logf("✓ Correctly identified standalone/LXC pattern from %s", tc.issueNo)- }- })- }-}--// TestNonStandaloneErrors verifies that genuine errors are NOT misidentified as standalone nodes-func TestNonStandaloneErrors(t *testing.T) {- genuineErrors := []struct {- name string- stderr string- stdout string- }{- {- name: "network timeout",- stderr: "Connection timed out\n",- stdout: "",- },- // {- // name: "permission denied",- // stderr: "Permission denied (publickey)\n",- // stdout: "",- // },- {- name: "command not found",- stderr: "bash: pvecm: command not found\n",- stdout: "",- },- }-- for _, tc := range genuineErrors {- t.Run(tc.name, func(t *testing.T) {- combinedOutput := tc.stderr + tc.stdout-- // These should NOT match our standalone patterns- isStandalone := strings.Contains(combinedOutput, "does not exist") ||- strings.Contains(combinedOutput, "not part of a cluster") ||- strings.Contains(combinedOutput, "ipcc_send_rec") ||- strings.Contains(combinedOutput, "Unknown error -1") ||- strings.Contains(combinedOutput, "Unable to load access control list")-- if isStandalone {- t.Errorf("False positive: genuine error misidentified as standalone:\n stderr: %q\n stdout: %q",- tc.stderr, tc.stdout)- } else {- t.Logf("✓ Correctly identified genuine error (not standalone)")- }- })- }-}--func TestShellQuote(t *testing.T) {- cases := []struct {- input string- want string- }{- {"", "''"},- {"foo", "'foo'"},- {"foo'bar", "\"foo'bar\""},- }- for _, tc := range cases {- if got := shellQuote(tc.input); got != tc.want {- t.Errorf("shellQuote(%q) = %q, want %q", tc.input, got, tc.want)- }- }-}--func TestIsLocalNode(t *testing.T) {- if !isLocalNode("localhost") {- t.Error("localhost should be local")- }- if !isLocalNode("127.0.0.1") {- t.Error("127.0.0.1 should be local")- }- if !isLocalNode("::1") {- t.Error("::1 should be local")- }- if isLocalNode("8.8.8.8") {- t.Error("8.8.8.8 should not be local")- }-}--func TestIsLocalNode_Hostname(t *testing.T) {- hostname, _ := os.Hostname()- if !isLocalNode(hostname) {- t.Errorf("hostname %q should be local", hostname)- }-}--func TestIsProxmoxHost_DirCheck(t *testing.T) {- // Mock PATH to NOT find pvecm- oldPath := os.Getenv("PATH")- os.Setenv("PATH", t.TempDir()) // Empty path- defer os.Setenv("PATH", oldPath)-- // Since we can't mock /etc/pve easily, we rely on it likely not existing.- if isProxmoxHost() {- // If it exists, good for us?- }-}--func TestDiscoverLocalHostAddressesFallback(t *testing.T) {- // Only test that it doesn't panic and returns something- addresses, _ := discoverLocalHostAddressesFallback()- if len(addresses) == 0 {- // Even if 'ip addr' fails, it should return hostname- t.Log("discoverLocalHostAddressesFallback returned no addresses")- }-}--func TestGetTemperatureLocal(t *testing.T) {- _, _, binDir, _ := setupTempWrapper(t)-- // Mock sensors command- sensorsStub := filepath.Join(binDir, "sensors")- jsonOutput := `{"cpu_thermal-virtual-0":{"temp1":{"temp1_input":42.5}}}`- content := fmt.Sprintf("#!/bin/sh\nprintf '%s'\n", jsonOutput)- if err := os.WriteFile(sensorsStub, []byte(content), 0o755); err != nil {- t.Fatalf("failed to create sensors stub: %v", err)- }-- oldPath := os.Getenv("PATH")- os.Setenv("PATH", binDir+string(os.PathListSeparator)+oldPath)- defer os.Setenv("PATH", oldPath)-- p := &Proxy{metrics: NewProxyMetrics("test")}- out, err := p.getTemperatureLocal(context.Background())- if err != nil {- t.Fatalf("getTemperatureLocal failed: %v", err)- }- if strings.TrimSpace(out) != jsonOutput {- t.Errorf("expected output %s, got %s", jsonOutput, out)- }-}--func TestDiscoverClusterNodes(t *testing.T) {- tmpDir := t.TempDir()- pvecmPath := filepath.Join(tmpDir, "pvecm")- // Normal cluster output- script := "#!/bin/sh\necho \"0x00000001 1 10.0.0.1\"\n"- os.WriteFile(pvecmPath, []byte(script), 0755)-- oldPath := os.Getenv("PATH")- os.Setenv("PATH", tmpDir+string(os.PathListSeparator)+oldPath)- defer os.Setenv("PATH", oldPath)-- nodes, err := discoverClusterNodes()- if err != nil {- t.Fatalf("discoverClusterNodes failed: %v", err)- }- if len(nodes) != 1 || nodes[0] != "10.0.0.1" {- t.Errorf("expected [10.0.0.1], got %v", nodes)- }-- // Standalone node (not part of cluster)- script = "#!/bin/sh\necho \"Error: Corosync config '/etc/pve/corosync.conf' does not exist\"\nexit 1\n"- os.WriteFile(pvecmPath, []byte(script), 0755)-- // discoverClusterNodes should fall back to local discovery- nodes, err = discoverClusterNodes()- if err != nil {- t.Fatalf("discoverClusterNodes failed on standalone node: %v", err)- }- if len(nodes) == 0 {- t.Error("expected local addresses for standalone node")- }-- // Unknown error- script = "#!/bin/sh\necho \"Some other error\"\nexit 1\n"- os.WriteFile(pvecmPath, []byte(script), 0755)-- _, err = discoverClusterNodes()- if err == nil {- t.Error("expected error for unknown failure")- }-- // IPC error (should NOT fallback to local)- script = "#!/bin/sh\necho \"ipcc_send_rec failed\"\nexit 1\n"- os.WriteFile(pvecmPath, []byte(script), 0755)-- _, err = discoverClusterNodes()- if err == nil {- t.Error("expected error for IPC failure")- } else if strings.Contains(err.Error(), "ipcc_send_rec failed") {- // This is good, it propagated the error instead of masking it- }-}--func TestDiscoverClusterNodes_LookPathError(t *testing.T) {- // Modify PATH to not include pvecm- oldPath := os.Getenv("PATH")- os.Setenv("PATH", t.TempDir()) // Empty path- defer os.Setenv("PATH", oldPath)-- _, err := discoverClusterNodes()- if err == nil || !strings.Contains(err.Error(), "pvecm not found") {- t.Errorf("expected pvecm not found error, got %v", err)- }-}--func TestDiscoverLocalHostAddresses_NetlinkError(t *testing.T) {- // Mock netInterfaces to return error- oldNetInterfaces := netInterfaces- defer func() { netInterfaces = oldNetInterfaces }()-- netInterfaces = func() ([]net.Interface, error) {- return nil, fmt.Errorf("address family not supported by protocol")- }-- // Should fallback to 'ip addr' command (which we can mock or let fail naturally)- // If fallback also fails (e.g. no 'ip' command in test env), that's fine as long as we hit the code path.- // We want to verify that the error was caught and logged (we can't easily verify log output here nicely)- // But we can verify that it returned result or error without panicking.- // Since discoverLocalHostAddressesFallback relies on 'hostname' or 'ip', it usually returns at least hostname.-- addrs, err := discoverLocalHostAddresses()- if err != nil {- t.Fatalf("unexpected error (should handle fallback): %v", err)- }- if len(addrs) == 0 {- t.Log("Warning: no addresses found during fallback test")- }-- // Test generic error- netInterfaces = func() ([]net.Interface, error) {- return nil, fmt.Errorf("generic connection error")- }-- // This path logs error and continues (returning empty or hostname-only additions)- // effectively skipping interface enumeration.- addrs, err = discoverLocalHostAddresses()- if err != nil {- t.Fatalf("unexpected error from generic failure: %v", err)- }-}--func TestDiscoverLocalHostAddressesFallback_IPCommand(t *testing.T) {- // Mock netInterfaces to trigger fallback- oldNetInterfaces := netInterfaces- defer func() { netInterfaces = oldNetInterfaces }()- netInterfaces = func() ([]net.Interface, error) {- return nil, fmt.Errorf("address family not supported")- }-- // Mock 'ip' command- tmpDir := t.TempDir()- ipPath := filepath.Join(tmpDir, "ip")- // Output with some IPs and loopback- output := `-1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000- link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00- inet 127.0.0.1/8 scope host lo- valid_lft forever preferred_lft forever- inet6 ::1/128 scope host- valid_lft forever preferred_lft forever-2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000- link/ether 00:15:5d:00:07:02 brd ff:ff:ff:ff:ff:ff- inet 192.168.1.50/24 brd 192.168.1.255 scope global eth0- valid_lft forever preferred_lft forever- inet6 fe80::215:5dff:fe00:702/64 scope link- valid_lft forever preferred_lft forever-`- script := fmt.Sprintf("#!/bin/sh\ncat <<EOF\n%s\nEOF\n", output)- os.WriteFile(ipPath, []byte(script), 0755)-- oldPath := os.Getenv("PATH")- os.Setenv("PATH", tmpDir+string(os.PathListSeparator)+oldPath)- defer os.Setenv("PATH", oldPath)-- addrs, err := discoverLocalHostAddresses()- if err != nil {- t.Fatalf("discoverLocalHostAddresses failed with fallback: %v", err)- }-- found := false- for _, addr := range addrs {- if addr == "192.168.1.50" {- found = true- }- if addr == "127.0.0.1" {- t.Error("should not include loopback 127.0.0.1")- }- if strings.HasPrefix(addr, "fe80:") {- t.Error("should not include link-local fe80::")- }- }- if !found {- t.Errorf("expected to find 192.168.1.50 in %v", addrs)- }-- // Test failure of 'ip' command- script = "#!/bin/sh\nexit 1\n"- os.WriteFile(ipPath, []byte(script), 0755)- addrs, err = discoverLocalHostAddresses()- if err != nil {- t.Fatal(err)- }- // Should at least return hostname (assume test runner has hostname)- if len(addrs) == 0 {- t.Log("No hostname addresses found when ip command fails")- }-}--func TestGetTemperatureLocal_Fallback(t *testing.T) {- _, _, binDir, _ := setupTempWrapper(t)-- // Mock sensors command to fail first but succeed second- sensorsStub := filepath.Join(binDir, "sensors")- script := "#!/bin/sh\nif [ \"$1\" = \"-j\" ]; then exit 1; fi\necho \"text output\"\nexit 0\n"- if err := os.WriteFile(sensorsStub, []byte(script), 0o755); err != nil {- t.Fatalf("failed to create sensors stub: %v", err)- }-- oldPath := os.Getenv("PATH")- os.Setenv("PATH", binDir+string(os.PathListSeparator)+oldPath)- defer os.Setenv("PATH", oldPath)-- p := &Proxy{metrics: NewProxyMetrics("test")}- out, err := p.getTemperatureLocal(context.Background())- if err != nil {- t.Fatalf("getTemperatureLocal failed: %v", err)- }- if out != "{}" {- t.Errorf("expected empty JSON for fallback, got %q", out)- }-}--func TestGetTemperatureLocal_CompleteFailure(t *testing.T) {- _, _, binDir, _ := setupTempWrapper(t)-- // Mock sensors command to fail completely- sensorsStub := filepath.Join(binDir, "sensors")- script := "#!/bin/sh\nexit 1\n"- if err := os.WriteFile(sensorsStub, []byte(script), 0o755); err != nil {- t.Fatalf("failed to create sensors stub: %v", err)- }-- oldPath := os.Getenv("PATH")- os.Setenv("PATH", binDir+string(os.PathListSeparator)+oldPath)- defer os.Setenv("PATH", oldPath)-- p := &Proxy{metrics: NewProxyMetrics("test")}- _, err := p.getTemperatureLocal(context.Background())- if err == nil {- t.Error("expected error when sensors command fails")- }-}--func TestGetTemperatureLocal_EmptyOutput(t *testing.T) {- _, _, binDir, _ := setupTempWrapper(t)-- // Mock sensors to return empty string- sensorsStub := filepath.Join(binDir, "sensors")- script := "#!/bin/sh\nexit 0\n"- if err := os.WriteFile(sensorsStub, []byte(script), 0o755); err != nil {- t.Fatalf("failed to create sensors stub: %v", err)- }-- oldPath := os.Getenv("PATH")- os.Setenv("PATH", binDir+string(os.PathListSeparator)+oldPath)- defer os.Setenv("PATH", oldPath)-- p := &Proxy{metrics: NewProxyMetrics("test")}- out, err := p.getTemperatureLocal(context.Background())- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if out != "{}" {- t.Errorf("expected empty JSON for empty output, got %q", out)- }-}--func TestDiscoverLocalHostAddresses_InterfaceEdgeCases(t *testing.T) {- oldNetInterfaces := netInterfaces- defer func() { netInterfaces = oldNetInterfaces }()-- netInterfaces = func() ([]net.Interface, error) {- return []net.Interface{- {Name: "lo", Flags: net.FlagUp | net.FlagLoopback}, // Should be skipped (loopback)- {Name: "down0", Flags: 0}, // Should be skipped (down)- {Name: "nonexistent0", Flags: net.FlagUp}, // Should trigger Addrs() error- }, nil- }-- addrs, err := discoverLocalHostAddresses()- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- // We expect empty addresses because all mocked interfaces are skipped or fail Addrs()- // But it might pick up hostname addresses.- // We can't easily mock hostname without another variable.- // But we can check that it didn't crash.- t.Logf("Got addresses: %v", addrs)-}--func TestLoadProxmoxHostKeys(t *testing.T) {- tmpDir := t.TempDir()- hostsFile := filepath.Join(tmpDir, "known_hosts")-- // Override path- origPath := proxmoxClusterKnownHostsPath- defer func() { proxmoxClusterKnownHostsPath = origPath }()- proxmoxClusterKnownHostsPath = hostsFile-- // Create dummy file- content := `-# Comment-node1 ssh-ed25519 AAA...-node2 ssh-rsa BBB... comment-invalid line-node1 ssh-rsa CCC...-[node3]:2222 ssh-ed25519 DDD...-`- if err := os.WriteFile(hostsFile, []byte(content), 0644); err != nil {- t.Fatal(err)- }-- // Test success- keys, err := loadProxmoxHostKeys("node1")- if err != nil {- t.Fatalf("loadProxmoxHostKeys failed: %v", err)- }-- if len(keys) != 2 {- t.Errorf("expected 2 keys for node1, got %d", len(keys))- }-- if !strings.Contains(string(keys[0]), "node1 ssh-ed25519 AAA...") {- t.Errorf("unexpected key content: %s", keys[0])- }-- // Test node2 with comment- keys2, err := loadProxmoxHostKeys("node2")- if err != nil {- t.Fatal(err)- }- if len(keys2) != 1 {- t.Errorf("expected 1 key for node2")- }- // Normalization puts comment at end- if !strings.Contains(string(keys2[0]), "comment") {- t.Errorf("expected comment in key: %s", keys2[0])- }-- // Test not found- _, err = loadProxmoxHostKeys("unknown")- if err == nil {- t.Error("expected error for unknown host")- }-- // Test file missing- proxmoxClusterKnownHostsPath = filepath.Join(tmpDir, "missing")- _, err = loadProxmoxHostKeys("node1")- if err == nil {- t.Error("expected error for missing file")- }-}--func TestBuildAuthorizedKey(t *testing.T) {- proxy := &Proxy{- config: &Config{- AllowedSourceSubnets: []string{"10.0.0.1/32", "192.168.1.0/24"},- },- }-- pubKey := "ssh-ed25519 AAA..."- line, err := proxy.buildAuthorizedKey(pubKey)- if err != nil {- t.Fatalf("buildAuthorizedKey failed: %v", err)- }-- expectedStart := `from="10.0.0.1/32,192.168.1.0/24",command="/usr/local/libexec/pulse-sensor-proxy/temp-wrapper.sh",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-ed25519 AAA... pulse-sensor-proxy`- if !strings.HasPrefix(line, expectedStart) && line != expectedStart {- t.Errorf("unexpected authorized_key line: %s", line)- }-- // Test empty config- proxyEmpty := &Proxy{config: &Config{}}- _, err = proxyEmpty.buildAuthorizedKey(pubKey)- if err == nil {- t.Error("expected error for empty allowed subnets")- }-}--func TestGetPublicKeyFrom(t *testing.T) {- tmpDir := t.TempDir()- pubKeyPath := filepath.Join(tmpDir, "id_ed25519.pub")-- content := "ssh-ed25519 AAA... comment"- if err := os.WriteFile(pubKeyPath, []byte(content), 0644); err != nil {- t.Fatal(err)- }-- // Test getPublicKeyFrom- proxy := &Proxy{}- pub, err := proxy.getPublicKeyFrom(tmpDir)- if err != nil {- t.Fatalf("getPublicKeyFrom failed: %v", err)- }-- expected := "ssh-ed25519 AAA... comment"- if pub != expected {- t.Errorf("expected %s, got %s", expected, pub)- }-- // Test missing- _, err = proxy.getPublicKeyFrom(filepath.Join(tmpDir, "missing"))- if err == nil {- t.Error("expected error for missing key")- }-}--func TestHandleHostKeyEnsureError(t *testing.T) {- proxy := &Proxy{- metrics: NewProxyMetrics("test"),- }-- // Normal error- err := errors.New("normal error")- res := proxy.handleHostKeyEnsureError("node1", err)- if res != err {- t.Errorf("expected original error, got %v", res)- }-- // HostKeyChangeError- changeErr := &knownhosts.HostKeyChangeError{- Host: "node1",- Existing: "old",- Provided: "new",- }-- res = proxy.handleHostKeyEnsureError("node1", changeErr)- if res != changeErr {- t.Errorf("expected original error, got %v", res)- }- // Verify metrics if possible, or just standard output log-}--func TestEnsureHostKeyFromProxmox(t *testing.T) {- // Mock isProxmoxHost- origLookPath := execLookPath- origStat := osStat- defer func() {- execLookPath = origLookPath- osStat = origStat- }()-- // Case 1: Not Proxmox host- execLookPath = func(file string) (string, error) {- return "", fmt.Errorf("not found")- }- osStat = func(name string) (os.FileInfo, error) {- return nil, os.ErrNotExist- }-- proxy := &Proxy{}- err := proxy.ensureHostKeyFromProxmox(context.Background(), "node1")- if err == nil || err.Error() != "not running on Proxmox host" {- t.Errorf("expected 'not running on Proxmox host' error, got %v", err)- }-- // Case 2: Proxmox host, key found- execLookPath = func(file string) (string, error) {- if file == "pvecm" {- return "/bin/pvecm", nil- }- return "", fmt.Errorf("not found")- }-- tmpDir := t.TempDir()- hostsFile := filepath.Join(tmpDir, "known_hosts")- origPath := proxmoxClusterKnownHostsPath- defer func() { proxmoxClusterKnownHostsPath = origPath }()- proxmoxClusterKnownHostsPath = hostsFile-- os.WriteFile(hostsFile, []byte("node1 ssh-ed25519 AAA..."), 0644)-- proxy = &Proxy{- knownHosts: &mockKnownHosts{},- config: &Config{RequireProxmoxHostkeys: true},- }-- err = proxy.ensureHostKeyFromProxmox(context.Background(), "node1")- if err != nil {- t.Errorf("ensureHostKeyFromProxmox failed: %v", err)- }-- // Case 3: Proxmox host, key NOT found- // knownHosts EnsureWithEntries (mock) returns nil, but loadProxmoxHostKeys will verify if key exists in file-- // loadProxmoxHostKeys returns error if key not found- err = proxy.ensureHostKeyFromProxmox(context.Background(), "unknown")- if err == nil {- t.Error("expected error for unknown host")- }-}--func TestPushSSHKeyFrom(t *testing.T) {- tmpDir := t.TempDir()- os.WriteFile(filepath.Join(tmpDir, "id_ed25519.pub"), []byte("ssh-ed25519 AAA..."), 0644)-- proxy := &Proxy{- sshKeyPath: tmpDir,- metrics: NewProxyMetrics("test"),- knownHosts: &mockKnownHosts{},- config: &Config{AllowedSourceSubnets: []string{"10.0.0.0/24"}},- }-- origExec := execCommandFunc- defer func() { execCommandFunc = origExec }()-- // Case 1: Success (key already present)- execCommandFunc = func(name string, arg ...string) *exec.Cmd {- args := strings.Join(arg, " ")- if strings.Contains(args, "grep -F") {- return mockExecCommand("from=...,ssh-ed25519 AAA...") // Found- }- if strings.Contains(args, "stage temperature wrapper") {- return mockExecCommand("") // Wrapper install success- }- return mockExecCommand("")- }-- if err := proxy.pushSSHKeyFrom("node1", tmpDir); err != nil {- t.Errorf("pushSSHKeyFrom failed (present): %v", err)- }-- // Case 2: Success (key added)- execCommandFunc = func(name string, arg ...string) *exec.Cmd {- args := strings.Join(arg, " ")- if strings.Contains(args, "grep -F") {- return mockExecCommandWithExitCode("", 1) // Not found- }- return mockExecCommand("")- }-- if err := proxy.pushSSHKeyFrom("node1", tmpDir); err != nil {- t.Errorf("pushSSHKeyFrom failed (added): %v", err)- }-- // Case 3: Error key not found- if err := proxy.pushSSHKeyFrom("node1", filepath.Join(tmpDir, "missing")); err == nil {- t.Error("expected error for missing key dir")- }-- // Case 4: ensureHostKey error (mock knownHosts.Ensure failure?)- // mockKnownHosts returns nil.-}--func TestSSHConnection(t *testing.T) {- tmpDir := t.TempDir()-- proxy := &Proxy{- sshKeyPath: tmpDir,- metrics: NewProxyMetrics("test"),- knownHosts: &mockKnownHosts{},- maxSSHOutputBytes: 1024,- config: &Config{},- }-- origExec := execCommandFunc- origExecCtx := execCommandContextFunc- defer func() {- execCommandFunc = origExec- execCommandContextFunc = origExecCtx- }()-- mockCmd := func(name string, arg ...string) *exec.Cmd {- if name == "sh" { // execCommandWithLimits uses "sh -c"- return mockExecCommand("{}")- }- return mockExecCommand("")- }-- execCommandFunc = mockCmd- execCommandContextFunc = func(ctx context.Context, name string, arg ...string) *exec.Cmd {- return mockCmd(name, arg...)- }-- if err := proxy.testSSHConnection("node1"); err != nil {- t.Errorf("testSSHConnection failed: %v", err)- }-- // Failure- mockCmdFail := func(name string, arg ...string) *exec.Cmd {- if name == "sh" {- return mockExecCommandWithExitCode("failed", 1)- }- return mockExecCommand("")- }- execCommandContextFunc = func(ctx context.Context, name string, arg ...string) *exec.Cmd {- return mockCmdFail(name, arg...)- }- execCommandFunc = mockCmdFail-- if err := proxy.testSSHConnection("node1"); err == nil {- t.Error("expected error for connection failure")- }-}diff --git a/cmd/pulse-sensor-proxy/throttle.go b/cmd/pulse-sensor-proxy/throttle.godeleted file mode 100644index 807ef275e5..0000000000--- a/cmd/pulse-sensor-proxy/throttle.go+++ /dev/null@@ -1,322 +0,0 @@-package main--import (- "context"- "fmt"- "sync"- "time"-- "golang.org/x/time/rate"-)--// peerID identifies a connecting principal (grouped by UID or ID range)-type peerID struct {- uid uint32- uidRange *idRange-}--func (p peerID) String() string {- if p.uidRange != nil {- end := p.uidRange.start + p.uidRange.length - 1- return fmt.Sprintf("range:%d-%d", p.uidRange.start, end)- }- return fmt.Sprintf("uid:%d", p.uid)-}--// limiterEntry holds rate limiting and concurrency controls for a peer-type limiterEntry struct {- limiter *rate.Limiter- semaphore chan struct{}- lastSeen time.Time-}--type limiterPolicy struct {- perPeerLimit rate.Limit- perPeerBurst int- perPeerConcurrency int- globalConcurrency int- penaltyDuration time.Duration-}--// rateLimiter manages per-peer rate limits and concurrency-type rateLimiter struct {- mu sync.Mutex- entries map[string]*limiterEntry- quitChan chan struct{}- globalSem chan struct{}- policy limiterPolicy- metrics *ProxyMetrics- uidRanges []idRange- gidRanges []idRange-}--const (- defaultPerPeerBurst = 10 // Allow burst of 10 requests for multi-node polling with retries- defaultPerPeerConcurrency = 2- defaultGlobalConcurrency = 8-)--var (- defaultPerPeerRateInterval = 500 * time.Millisecond // 2 qps (120/min) - supports larger deployments- defaultPenaltyDuration = 2 * time.Second- defaultPerPeerLimit = rate.Every(defaultPerPeerRateInterval)-)--// newRateLimiter creates a new rate limiter with cleanup loop-// If rateLimitCfg is provided, it overrides the default rate limit settings-func newRateLimiter(metrics *ProxyMetrics, rateLimitCfg *RateLimitConfig, uidRanges, gidRanges []idRange) *rateLimiter {- // Use defaults- perPeerLimit := defaultPerPeerLimit- perPeerBurst := defaultPerPeerBurst-- // Override with config if provided- if rateLimitCfg != nil {- if rateLimitCfg.PerPeerIntervalMs > 0 {- interval := time.Duration(rateLimitCfg.PerPeerIntervalMs) * time.Millisecond- perPeerLimit = rate.Every(interval)- }- if rateLimitCfg.PerPeerBurst > 0 {- perPeerBurst = rateLimitCfg.PerPeerBurst- }- }-- rl := &rateLimiter{- entries: make(map[string]*limiterEntry),- quitChan: make(chan struct{}),- globalSem: make(chan struct{}, defaultGlobalConcurrency),- policy: limiterPolicy{- perPeerLimit: perPeerLimit,- perPeerBurst: perPeerBurst,- perPeerConcurrency: defaultPerPeerConcurrency,- globalConcurrency: defaultGlobalConcurrency,- penaltyDuration: defaultPenaltyDuration,- },- metrics: metrics,- uidRanges: append([]idRange(nil), uidRanges...),- gidRanges: append([]idRange(nil), gidRanges...),- }- if rl.metrics != nil {- rl.metrics.setLimiterPeers(0)- }- go rl.cleanupLoop()- return rl-}--// allow checks if a peer is allowed to make a request and reserves concurrency.-// Returns a release function, rejection reason (if any), and whether the request is allowed.-func (rl *rateLimiter) allow(id peerID) (release func(), reason string, allowed bool) {- key := id.String()- rl.mu.Lock()- entry := rl.entries[key]- if entry == nil {- entry = &limiterEntry{- limiter: rate.NewLimiter(rl.policy.perPeerLimit, rl.policy.perPeerBurst),- semaphore: make(chan struct{}, rl.policy.perPeerConcurrency),- }- rl.entries[key] = entry- if rl.metrics != nil {- rl.metrics.setLimiterPeers(len(rl.entries))- }- }- entry.lastSeen = time.Now()- rl.mu.Unlock()-- // Check rate limit- if !entry.limiter.Allow() {- rl.recordRejection("rate", key)- return nil, "rate", false- }-- // Acquire global concurrency- select {- case rl.globalSem <- struct{}{}:- if rl.metrics != nil {- rl.metrics.incGlobalConcurrency()- }- default:- rl.recordRejection("global_concurrency", key)- return nil, "global_concurrency", false- }-- // Try to acquire per-peer concurrency slot- select {- case entry.semaphore <- struct{}{}:- return func() {- <-entry.semaphore- <-rl.globalSem- if rl.metrics != nil {- rl.metrics.decGlobalConcurrency()- }- }, "", true- default:- <-rl.globalSem- if rl.metrics != nil {- rl.metrics.decGlobalConcurrency()- }- rl.recordRejection("peer_concurrency", key)- return nil, "peer_concurrency", false- }-}--// cleanupLoop periodically removes idle peer entries-func (rl *rateLimiter) cleanupLoop() {- ticker := time.NewTicker(5 * time.Minute)- defer ticker.Stop()- for {- select {- case <-ticker.C:- rl.mu.Lock()- for key, entry := range rl.entries {- if time.Since(entry.lastSeen) > 10*time.Minute {- delete(rl.entries, key)- }- }- if rl.metrics != nil {- rl.metrics.setLimiterPeers(len(rl.entries))- }- rl.mu.Unlock()- case <-rl.quitChan:- return- }- }-}--// shutdown stops the cleanup loop-func (rl *rateLimiter) shutdown() {- close(rl.quitChan)-}--func (rl *rateLimiter) penalize(peerLabel, reason string) {- if rl.policy.penaltyDuration <= 0 {- return- }- time.Sleep(rl.policy.penaltyDuration)- if rl.metrics != nil {- rl.metrics.recordPenalty(reason, peerLabel)- }-}--func (rl *rateLimiter) recordRejection(reason, peerLabel string) {- if rl.metrics != nil {- rl.metrics.recordLimiterReject(reason, peerLabel)- }-}--func (rl *rateLimiter) identifyPeer(cred *peerCredentials) peerID {- if cred == nil {- return peerID{}- }- if rl == nil {- return peerID{uid: cred.uid}- }-- if len(rl.uidRanges) == 0 || len(rl.gidRanges) == 0 {- return peerID{uid: cred.uid}- }-- uidRange := findRange(rl.uidRanges, cred.uid)- gidRange := findRange(rl.gidRanges, cred.gid)-- if uidRange != nil && gidRange != nil {- return peerID{uid: cred.uid, uidRange: uidRange}- }-- return peerID{uid: cred.uid}-}--func findRange(ranges []idRange, value uint32) *idRange {- for i := range ranges {- if ranges[i].contains(value) {- return &ranges[i]- }- }- return nil-}--// nodeGate controls per-node concurrency for temperature requests-type nodeGate struct {- mu sync.Mutex- inFlight map[string]*nodeLock-}--// nodeLock tracks in-flight requests for a specific node-type nodeLock struct {- refCount int- guard chan struct{}-}--// newNodeGate creates a new node concurrency gate-func newNodeGate() *nodeGate {- return &nodeGate{- inFlight: make(map[string]*nodeLock),- }-}--// acquire gets exclusive access to make requests to a node-// Returns a release function that must be called when done-// Deprecated: Use acquireContext for context-aware acquisition-func (g *nodeGate) acquire(node string) func() {- g.mu.Lock()- lock := g.inFlight[node]- if lock == nil {- lock = &nodeLock{- guard: make(chan struct{}, 1), // single slot = only one SSH fetch per node- }- g.inFlight[node] = lock- }- lock.refCount++- g.mu.Unlock()-- // Wait for exclusive access- lock.guard <- struct{}{}-- // Return release function- return func() {- <-lock.guard- g.mu.Lock()- lock.refCount--- if lock.refCount == 0 {- delete(g.inFlight, node)- }- g.mu.Unlock()- }-}--// acquireContext gets exclusive access to make requests to a node with context cancellation support.-// Returns a release function and nil error on success.-// Returns nil and context error if context is cancelled while waiting.-func (g *nodeGate) acquireContext(ctx context.Context, node string) (func(), error) {- g.mu.Lock()- lock := g.inFlight[node]- if lock == nil {- lock = &nodeLock{- guard: make(chan struct{}, 1),- }- g.inFlight[node] = lock- }- lock.refCount++- g.mu.Unlock()-- // Wait for exclusive access OR context cancellation- select {- case lock.guard <- struct{}{}:- return func() {- <-lock.guard- g.mu.Lock()- lock.refCount--- if lock.refCount == 0 {- delete(g.inFlight, node)- }- g.mu.Unlock()- }, nil- case <-ctx.Done():- // Clean up refCount since we're not proceeding- g.mu.Lock()- lock.refCount--- if lock.refCount == 0 {- delete(g.inFlight, node)- }- g.mu.Unlock()- return nil, ctx.Err()- }-}diff --git a/cmd/pulse-sensor-proxy/throttle_test.go b/cmd/pulse-sensor-proxy/throttle_test.godeleted file mode 100644index 2360581bbc..0000000000--- a/cmd/pulse-sensor-proxy/throttle_test.go+++ /dev/null@@ -1,198 +0,0 @@-package main--import (- "context"- "testing"- "time"-)--func TestRateLimiterPenalizeMetrics(t *testing.T) {- metrics := NewProxyMetrics("test")- rl := newRateLimiter(metrics, nil, nil, nil)- rl.policy.penaltyDuration = 10 * time.Millisecond-- start := time.Now()- rl.penalize("uid:42", "invalid_json")- if time.Since(start) < rl.policy.penaltyDuration {- t.Fatalf("expected penalize to sleep at least %v", rl.policy.penaltyDuration)- }-- mf, err := metrics.registry.Gather()- if err != nil {- t.Fatalf("gather metrics: %v", err)- }-- found := false- for _, fam := range mf {- if fam.GetName() != "pulse_proxy_limiter_penalties_total" {- continue- }- for _, metric := range fam.GetMetric() {- if metric.GetCounter().GetValue() == 0 {- continue- }- var reasonLabel, peerLabel string- for _, label := range metric.GetLabel() {- switch label.GetName() {- case "reason":- reasonLabel = label.GetValue()- case "peer":- peerLabel = label.GetValue()- }- }- if reasonLabel == "invalid_json" && peerLabel == "uid:42" {- found = true- }- }- }- if !found {- t.Fatalf("expected limiter penalty metric for invalid_json and peer uid:42")- }-}--func TestIdentifyPeerRangeVsUID(t *testing.T) {- uidRanges := []idRange{{start: 100000, length: 65536}}- gidRanges := []idRange{{start: 100000, length: 65536}}- rl := newRateLimiter(nil, nil, uidRanges, gidRanges)-- containerCred := &peerCredentials{uid: 110000, gid: 110000}- containerPeer := rl.identifyPeer(containerCred)- if containerPeer.uidRange == nil {- t.Fatalf("expected container peer to map to UID range")- }- if got := containerPeer.String(); got != "range:100000-165535" {- t.Fatalf("unexpected container peer label: %s", got)- }-- hostCred := &peerCredentials{uid: 1000, gid: 1000}- hostPeer := rl.identifyPeer(hostCred)- if hostPeer.uidRange != nil {- t.Fatalf("expected host peer to use UID label")- }- if got := hostPeer.String(); got != "uid:1000" {- t.Fatalf("unexpected host peer label: %s", got)- }-}--func TestRateLimiter_Allow(t *testing.T) {- rl := newRateLimiter(nil, nil, nil, nil)- rl.policy.perPeerConcurrency = 1- rl.policy.globalConcurrency = 10- rl.policy.perPeerBurst = 10-- id := peerID{uid: 1000}- release1, _, allowed1 := rl.allow(id)- if !allowed1 {- t.Fatal("expected first request to be allowed")- }-- // per-peer concurrency hit- _, reason, allowed2 := rl.allow(id)- if allowed2 {- t.Fatal("expected second request to be rejected")- }- if reason != "peer_concurrency" {- t.Errorf("expected reason peer_concurrency, got %s", reason)- }-- release1()-- // Now allowed again- _, _, allowed3 := rl.allow(id)- if !allowed3 {- t.Fatal("expected third request to be allowed")- }-}--func TestRateLimiter_GlobalConcurrency(t *testing.T) {- rl := newRateLimiter(nil, nil, nil, nil)- rl.globalSem = make(chan struct{}, 1) // Force global limit to 1-- id1 := peerID{uid: 1001}- id2 := peerID{uid: 1002}-- release1, _, _ := rl.allow(id1)-- _, reason, allowed := rl.allow(id2)- if allowed {- t.Fatal("expected id2 to be rejected due to global concurrency")- }- if reason != "global_concurrency" {- t.Errorf("expected global_concurrency, got %s", reason)- }-- release1()-}--func TestNodeGate(t *testing.T) {- g := newNodeGate()-- release1 := g.acquire("node1")-- acquired2 := make(chan bool)- go func() {- release2 := g.acquire("node1")- acquired2 <- true- release2()- }()-- select {- case <-acquired2:- t.Fatal("should not have acquired node1 while held")- case <-time.After(20 * time.Millisecond):- // Good- }-- release1()-- select {- case <-acquired2:- // Good- case <-time.After(100 * time.Millisecond):- t.Fatal("should have acquired node1 after release")- }-}--func TestNodeGate_AcquireContext(t *testing.T) {- g := newNodeGate()-- ctx, cancel := context.WithCancel(context.Background())- defer cancel()- release1, _ := g.acquireContext(ctx, "node1")-- // Try to acquire again with cancelled context- ctx2, cancel2 := context.WithCancel(context.Background())- cancel2()- _, err := g.acquireContext(ctx2, "node1")- if err == nil {- t.Error("expected error for cancelled context")- }-- release1()-}--func TestRateLimiter_NewLimit(t *testing.T) {- metrics := NewProxyMetrics("test")- cfg := &RateLimitConfig{- PerPeerIntervalMs: 100,- PerPeerBurst: 5,- }- rl := newRateLimiter(metrics, cfg, nil, nil)- if rl.policy.perPeerBurst != 5 {- t.Errorf("expected burst 5, got %d", rl.policy.perPeerBurst)- }- rl.shutdown()-}--func TestIdentifyPeer_EdgeCases(t *testing.T) {- rl := newRateLimiter(nil, nil, nil, nil)- if id := rl.identifyPeer(nil); id.uid != 0 {- t.Error("expected 0 UID for nil creds")- }-- var nilRl *rateLimiter- id := nilRl.identifyPeer(&peerCredentials{uid: 123})- if id.uid != 123 {- t.Error("expected 123 UID for nil limiter")- }-}diff --git a/cmd/pulse-sensor-proxy/validation.go b/cmd/pulse-sensor-proxy/validation.godeleted file mode 100644index 80095ff6de..0000000000--- a/cmd/pulse-sensor-proxy/validation.go+++ /dev/null@@ -1,497 +0,0 @@-package main--import (- "context"- "errors"- "fmt"- "net"- "regexp"- "strings"- "sync"- "time"-- "github.com/google/uuid"- "github.com/rs/zerolog/log"-)--var (- // nodeNameRegex validates node names (alphanumeric, dots, underscores, hyphens, 1-64 chars)- // Must not start with hyphen to prevent SSH option injection- nodeNameRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$`)-- // ipv4Regex validates IPv4 addresses- ipv4Regex = regexp.MustCompile(`^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`)-)--// sanitizeCorrelationID validates and sanitizes a correlation ID-// Returns a valid UUID, generating a new one if input is missing or invalid-func sanitizeCorrelationID(id string) string {- if id == "" {- return uuid.NewString()- }- if _, err := uuid.Parse(id); err != nil {- return uuid.NewString()- }- return id-}--// validateNodeName checks if a node name is in valid format-func validateNodeName(name string) error {- if name == "" {- return fmt.Errorf("invalid node name")- }-- if ipv4Regex.MatchString(name) {- return nil- }-- candidate := name- if strings.HasPrefix(candidate, "[") && strings.HasSuffix(candidate, "]") {- candidate = candidate[1 : len(candidate)-1]- }-- if ip := net.ParseIP(candidate); ip != nil {- return nil- }-- if nodeNameRegex.MatchString(name) {- return nil- }-- return fmt.Errorf("invalid node name")-}--const (- nodeValidatorCacheTTL = 5 * time.Minute-- validationReasonNotAllowlisted = "node_not_allowlisted"- validationReasonNotClusterMember = "node_not_cluster_member"- validationReasonNoSources = "no_validation_sources"- validationReasonResolutionFailed = "allowlist_resolution_failed"- validationReasonClusterFailed = "cluster_query_failed"-)--// nodeValidator enforces node allow-list and cluster membership checks-type nodeValidator struct {- mu sync.RWMutex- allowHosts map[string]struct{}- allowCIDRs []*net.IPNet- hasAllowlist bool- strict bool- clusterEnabled bool- metrics *ProxyMetrics- resolver hostResolver- clusterFetcher func() ([]string, error)- cacheTTL time.Duration- clock func() time.Time- clusterCache clusterMembershipCache-}--type clusterMembershipCache struct {- mu sync.Mutex- expires time.Time- nodes map[string]struct{}-}--type hostResolver interface {- LookupIP(ctx context.Context, host string) ([]net.IP, error)-}--type defaultHostResolver struct{}--func (defaultHostResolver) LookupIP(ctx context.Context, host string) ([]net.IP, error) {- if ctx == nil {- ctx = context.Background()- }- results, err := net.DefaultResolver.LookupIPAddr(ctx, host)- if err != nil {- return nil, err- }- if len(results) == 0 {- return nil, fmt.Errorf("no IPs resolved for %s", host)- }-- ips := make([]net.IP, 0, len(results))- for _, addr := range results {- if addr.IP != nil {- ips = append(ips, addr.IP)- }- }- if len(ips) == 0 {- return nil, fmt.Errorf("no IP addresses resolved for %s", host)- }-- return ips, nil-}--func newNodeValidator(cfg *Config, metrics *ProxyMetrics) (*nodeValidator, error) {- if cfg == nil {- return nil, errors.New("config is required for node validator")- }-- v := &nodeValidator{- allowHosts: make(map[string]struct{}),- strict: cfg.StrictNodeValidation,- metrics: metrics,- resolver: defaultHostResolver{},- clusterFetcher: discoverClusterNodes,- cacheTTL: nodeValidatorCacheTTL,- clock: time.Now,- }-- v.setAllowlist(cfg.AllowedNodes)-- if v.hasAllowlist {- log.Info().- Int("allowed_node_count", len(v.allowHosts)).- Int("allowed_cidr_count", len(v.allowCIDRs)).- Msg("Node allow-list configured")- }-- if !v.hasAllowlist && isProxmoxHost() {- v.clusterEnabled = true- log.Info().Msg("Node validator using Proxmox cluster membership (auto-detect)")- }-- if !v.clusterEnabled {- v.clusterFetcher = nil- }-- if !v.hasAllowlist && !v.clusterEnabled {- if v.strict {- log.Warn().Msg("strict_node_validation enabled but no allowlist or cluster context is available")- } else {- log.Warn().Msg("SECURITY: Node validator running in permissive mode (no allowlist or cluster context) - all nodes allowed. Configure allowed_nodes to restrict access.")- }- }-- return v, nil-}--func (v *nodeValidator) setAllowlist(entries []string) {- v.allowHosts = make(map[string]struct{})- v.allowCIDRs = nil-- for _, raw := range entries {- entry := strings.TrimSpace(raw)- if entry == "" {- continue- }-- if _, network, err := net.ParseCIDR(entry); err == nil {- v.allowCIDRs = append(v.allowCIDRs, network)- continue- }-- if normalized := normalizeAllowlistEntry(entry); normalized != "" {- v.allowHosts[normalized] = struct{}{}- }- }-- v.hasAllowlist = len(v.allowHosts) > 0 || len(v.allowCIDRs) > 0-}--func (v *nodeValidator) UpdateAllowlist(entries []string) {- if v == nil {- return- }-- v.mu.Lock()- v.setAllowlist(entries)- hasAllowlist := v.hasAllowlist- hosts := len(v.allowHosts)- cidrs := len(v.allowCIDRs)- v.mu.Unlock()-- if hasAllowlist {- log.Info().- Int("allowed_node_count", hosts).- Int("allowed_cidr_count", cidrs).- Msg("Updated node allow-list from control plane")- } else {- log.Warn().Msg("Control plane allow-list update produced empty set")- }-}--// Validate ensures the provided node is authorized before any SSH is attempted.-func (v *nodeValidator) Validate(ctx context.Context, node string) error {- if v == nil {- return nil- }-- v.mu.RLock()- hasAllowlist := v.hasAllowlist- clusterEnabled := v.clusterEnabled- v.mu.RUnlock()-- if ctx == nil {- ctx = context.Background()- }-- if hasAllowlist {- allowed, err := v.matchesAllowlist(ctx, node)- if err != nil {- v.recordFailure(validationReasonResolutionFailed)- log.Warn().Err(err).Str("node", node).Msg("Node allow-list resolution failed")- return err- }- if !allowed {- return v.deny(node, validationReasonNotAllowlisted)- }- return nil- }-- if clusterEnabled {- allowed, err := v.matchesCluster(ctx, node)- if err != nil {- // Cluster query failed (e.g., IPC permission denied, running in LXC)- // Fall back to localhost-only validation instead of permissive mode- v.recordFailure(validationReasonClusterFailed)- log.Warn().- Err(err).- Str("node", node).- Msg("SECURITY: Cluster validation unavailable - falling back to localhost-only validation. Configure allowed_nodes for cluster-wide access.")- // Attempt to validate against localhost addresses- return v.validateAsLocalhost(ctx, node)- } else if !allowed {- return v.deny(node, validationReasonNotClusterMember)- } else {- return nil- }- }-- if v.strict {- return v.deny(node, validationReasonNoSources)- }-- return nil-}--func (v *nodeValidator) validateAsLocalhost(_ context.Context, node string) error {- // When cluster validation is unavailable, only allow access to localhost- // This maintains security while allowing self-monitoring-- // Try to discover local host addresses- localAddrs, err := discoverLocalHostAddresses()- if err != nil {- log.Warn().Err(err).Msg("Failed to discover local host addresses for fallback validation")- // If we can't even discover localhost, deny access- return v.deny(node, validationReasonClusterFailed)- }-- // Check if the requested node matches any local address- normalized := normalizeAllowlistEntry(node)- if normalized == "" {- normalized = strings.ToLower(strings.TrimSpace(node))- }-- for _, localAddr := range localAddrs {- if strings.EqualFold(localAddr, normalized) {- log.Debug().- Str("node", node).- Str("matched_local", localAddr).- Msg("Node validated as localhost (cluster validation unavailable)")- return nil- }- }-- // Node doesn't match any local address - deny- return v.deny(node, "node_not_localhost")-}--func (v *nodeValidator) matchesAllowlist(ctx context.Context, node string) (bool, error) {- v.mu.RLock()- allowHosts := v.allowHosts- allowCIDRs := v.allowCIDRs- resolver := v.resolver- v.mu.RUnlock()-- normalized := normalizeAllowlistEntry(node)- if normalized != "" {- if _, ok := allowHosts[normalized]; ok {- return true, nil- }- }-- if ip := parseNodeIP(node); ip != nil {- if ipAllowed(ip, allowHosts, allowCIDRs) {- return true, nil- }- // If the node itself is an IP and it didn't match, no need to resolve again.- return false, nil- }-- if len(allowCIDRs) == 0 {- return false, nil- }-- host := stripNodeDelimiters(node)- ips, err := resolver.LookupIP(ctx, host)- if err != nil {- return false, fmt.Errorf("resolve node %q: %w", host, err)- }-- for _, ip := range ips {- if ipAllowed(ip, allowHosts, allowCIDRs) {- return true, nil- }- }-- return false, nil-}--func (v *nodeValidator) matchesCluster(ctx context.Context, node string) (bool, error) {- if v.clusterFetcher == nil {- return false, errors.New("cluster membership disabled")- }-- if ctx == nil {- ctx = context.Background()- }-- members, err := v.getClusterMembers(ctx)- if err != nil {- return false, err- }-- normalized := normalizeAllowlistEntry(node)- if normalized == "" {- normalized = strings.ToLower(strings.TrimSpace(node))- }-- _, ok := members[normalized]- return ok, nil-}--func (v *nodeValidator) getClusterMembers(ctx context.Context) (map[string]struct{}, error) {- if ctx == nil {- ctx = context.Background()- }-- now := time.Now()- if v.clock != nil {- now = v.clock()- }-- v.clusterCache.mu.Lock()- defer v.clusterCache.mu.Unlock()-- if v.clusterCache.nodes != nil && now.Before(v.clusterCache.expires) {- return v.clusterCache.nodes, nil- }-- nodes, err := v.clusterFetcher()- if err != nil {- return nil, err- }-- result := make(map[string]struct{}, len(nodes))- resolvedHosts := make(map[string]struct{})- for _, node := range nodes {- if normalized := normalizeAllowlistEntry(node); normalized != "" {- result[normalized] = struct{}{}- }-- host := stripNodeDelimiters(strings.TrimSpace(node))- if host == "" {- continue- }-- if net.ParseIP(host) != nil {- continue- }-- if _, seen := resolvedHosts[host]; seen {- continue- }- resolvedHosts[host] = struct{}{}-- if v.resolver == nil {- continue- }-- ips, err := v.resolver.LookupIP(ctx, host)- if err != nil {- log.Debug().- Str("host", host).- Err(err).- Msg("Failed to resolve cluster node hostname to IP")- continue- }-- for _, ip := range ips {- if ip == nil {- continue- }- result[ip.String()] = struct{}{}- }- }-- ttl := v.cacheTTL- if ttl <= 0 {- ttl = nodeValidatorCacheTTL- }- v.clusterCache.nodes = result- v.clusterCache.expires = now.Add(ttl)- log.Debug().- Int("cluster_node_count", len(result)).- Msg("Refreshed cluster membership cache")-- return result, nil-}--func ipAllowed(ip net.IP, hosts map[string]struct{}, cidrs []*net.IPNet) bool {- if ip == nil {- return false- }- if hosts != nil {- if _, ok := hosts[ip.String()]; ok {- return true- }- }- for _, network := range cidrs {- if network.Contains(ip) {- return true- }- }- return false-}--func (v *nodeValidator) recordFailure(reason string) {- if v.metrics != nil {- v.metrics.recordNodeValidationFailure(reason)- }-}--func (v *nodeValidator) deny(node, reason string) error {- v.recordFailure(reason)- log.Warn().- Str("node", node).- Str("reason", reason).- Msg("potential SSRF attempt blocked")- return fmt.Errorf("node %q rejected by validator (%s)", node, reason)-}--func normalizeAllowlistEntry(entry string) string {- candidate := strings.TrimSpace(entry)- if candidate == "" {- return ""- }- unwrapped := stripNodeDelimiters(candidate)- if ip := net.ParseIP(unwrapped); ip != nil {- return ip.String()- }- return strings.ToLower(candidate)-}--func parseNodeIP(node string) net.IP {- clean := stripNodeDelimiters(strings.TrimSpace(node))- return net.ParseIP(clean)-}--func stripNodeDelimiters(node string) string {- if strings.HasPrefix(node, "[") && strings.HasSuffix(node, "]") && len(node) > 2 {- return node[1 : len(node)-1]- }- return node-}diff --git a/cmd/pulse-sensor-proxy/validation_test.go b/cmd/pulse-sensor-proxy/validation_test.godeleted file mode 100644index 97538040b8..0000000000--- a/cmd/pulse-sensor-proxy/validation_test.go+++ /dev/null@@ -1,664 +0,0 @@-package main--import (- "context"- "errors"- "net"- "strings"- "testing"- "time"-)--func TestSanitizeCorrelationID(t *testing.T) {- valid := sanitizeCorrelationID("550e8400-e29b-41d4-a716-446655440000")- if valid != "550e8400-e29b-41d4-a716-446655440000" {- t.Fatalf("expected valid UUID to pass through, got %s", valid)- }-- invalid := sanitizeCorrelationID("not-a-uuid")- if invalid == "not-a-uuid" {- t.Fatalf("expected invalid UUID to be replaced")- }-- empty := sanitizeCorrelationID("")- if empty == "" {- t.Fatalf("expected empty string to be replaced")- }-- if invalid == empty {- t.Fatalf("expected regenerated UUIDs to differ")- }-}--func TestValidateNodeName(t *testing.T) {- cases := []struct {- name string- wantErr bool- desc string- }{- {name: "node-1", wantErr: false, desc: "alphanumeric"},- {name: "example.com", wantErr: false, desc: "dns hostname"},- {name: "1.2.3.4", wantErr: false, desc: "ipv4"},- {name: "2001:db8::1", wantErr: false, desc: "ipv6 compressed"},- {name: "[2001:db8::10]", wantErr: false, desc: "ipv6 bracketed"},- {name: "::1", wantErr: false, desc: "ipv6 loopback"},- {name: "::", wantErr: false, desc: "ipv6 unspecified"},- {name: "::ffff:192.0.2.1", wantErr: false, desc: "ipv4-mapped ipv6 dual stack"},- {name: "[::1]", wantErr: false, desc: "ipv6 loopback bracketed"},- {name: "fe80::1%eth0", wantErr: true, desc: "ipv6 zone identifier"},- {name: "[fe80::1%eth0]", wantErr: true, desc: "ipv6 zone identifier bracketed"},- {name: "[2001:db8::1]:22", wantErr: true, desc: "ipv6 with port suffix"},- {name: "[2001:db8::1", wantErr: true, desc: "missing closing bracket"},- {name: "2001:db8::1]", wantErr: true, desc: "missing opening bracket"},- {name: "bad host", wantErr: true, desc: "whitespace disallowed"},- {name: "-leadinghyphen", wantErr: true, desc: "leading hyphen disallowed"},- {name: "example.com:22", wantErr: true, desc: "dns name with port"},- {name: "", wantErr: true, desc: "empty string"},- {name: "example_com", wantErr: false, desc: "underscore"},- {name: "NODE123", wantErr: false, desc: "uppercase"},- {name: strings.Repeat("a", 64), wantErr: false, desc: "64 chars"},- {name: strings.Repeat("a", 65), wantErr: true, desc: "65 chars"},- {name: "senso\u200Brs", wantErr: true, desc: "zero-width space"},- {name: "node\\name", wantErr: true, desc: "backslash"},- {name: "/etc/passwd", wantErr: true, desc: "absolute path"},- {name: "node\x00", wantErr: true, desc: "null byte"},- {name: "example.com;rm", wantErr: true, desc: "semicolon"},- {name: "node$(rm)", wantErr: true, desc: "subshell"},- }-- for _, tc := range cases {- tc := tc- name := tc.desc- if name == "" {- name = tc.name- }- t.Run(name, func(t *testing.T) {- err := validateNodeName(tc.name)- if tc.wantErr && err == nil {- t.Fatalf("expected error validating %q", tc.name)- }- if !tc.wantErr && err != nil {- t.Fatalf("unexpected error for %q: %v", tc.name, err)- }- })- }-}--type stubResolver struct {- ips []net.IP- err error-}--func (s stubResolver) LookupIP(ctx context.Context, host string) ([]net.IP, error) {- if s.err != nil {- return nil, s.err- }- return s.ips, nil-}--func TestNodeValidatorAllowlistHost(t *testing.T) {- v := &nodeValidator{- allowHosts: map[string]struct{}{"node-1": {}},- hasAllowlist: true,- resolver: stubResolver{},- }-- if err := v.Validate(context.Background(), "node-1"); err != nil {- t.Fatalf("expected node-1 to be permitted, got error: %v", err)- }-- if err := v.Validate(context.Background(), "node-2"); err == nil {- t.Fatalf("expected node-2 to be rejected without allow-list entry")- }-}--func TestNodeValidatorAllowlistCIDRWithLookup(t *testing.T) {- _, network, _ := net.ParseCIDR("10.0.0.0/24")- v := &nodeValidator{- allowHosts: make(map[string]struct{}),- allowCIDRs: []*net.IPNet{network},- hasAllowlist: true,- resolver: stubResolver{- ips: []net.IP{net.ParseIP("10.0.0.5")},- },- }-- if err := v.Validate(context.Background(), "worker.local"); err != nil {- t.Fatalf("expected worker.local to resolve into allowed CIDR: %v", err)- }-}--func TestNodeValidatorClusterCaching(t *testing.T) {- current := time.Now()- fetches := 0-- v := &nodeValidator{- clusterEnabled: true,- clusterFetcher: func() ([]string, error) {- fetches++- return []string{"10.0.0.9"}, nil- },- cacheTTL: nodeValidatorCacheTTL,- clock: func() time.Time {- return current- },- }-- if err := v.Validate(context.Background(), "10.0.0.9"); err != nil {- t.Fatalf("expected node to be allowed via cluster membership: %v", err)- }- if fetches != 1 {- t.Fatalf("expected initial cluster fetch, got %d", fetches)- }-- current = current.Add(30 * time.Second)- if err := v.Validate(context.Background(), "10.0.0.9"); err != nil {- t.Fatalf("expected cached cluster membership to allow node: %v", err)- }- if fetches != 1 {- t.Fatalf("expected cache hit to avoid new fetch, got %d fetches", fetches)- }-- current = current.Add(nodeValidatorCacheTTL + time.Second)- if err := v.Validate(context.Background(), "10.0.0.9"); err != nil {- t.Fatalf("expected refreshed cluster membership to allow node: %v", err)- }- if fetches != 2 {- t.Fatalf("expected cache expiry to trigger new fetch, got %d", fetches)- }-}--func TestNodeValidatorClusterResolvesHostIPs(t *testing.T) {- v := &nodeValidator{- clusterEnabled: true,- clusterFetcher: func() ([]string, error) {- return []string{"worker.local"}, nil- },- resolver: stubResolver{- ips: []net.IP{net.ParseIP("10.0.0.5")},- },- }-- if err := v.Validate(context.Background(), "10.0.0.5"); err != nil {- t.Fatalf("expected cluster hostname resolution to permit node: %v", err)- }-}--func TestNodeValidatorStrictNoSources(t *testing.T) {- v := &nodeValidator{- strict: true,- }-- if err := v.Validate(context.Background(), "node-1"); err == nil {- t.Fatalf("expected strict mode without sources to reject nodes")- }-}--func TestStripNodeDelimiters(t *testing.T) {- tests := []struct {- name string- input string- expected string- }{- {- name: "ipv6 with brackets",- input: "[2001:db8::1]",- expected: "2001:db8::1",- },- {- name: "ipv6 loopback bracketed",- input: "[::1]",- expected: "::1",- },- {- name: "ipv4 no brackets",- input: "192.168.1.1",- expected: "192.168.1.1",- },- {- name: "hostname no brackets",- input: "node-1.example.com",- expected: "node-1.example.com",- },- {- name: "empty string",- input: "",- expected: "",- },- {- name: "only opening bracket",- input: "[2001:db8::1",- expected: "[2001:db8::1",- },- {- name: "only closing bracket",- input: "2001:db8::1]",- expected: "2001:db8::1]",- },- {- name: "brackets with single char",- input: "[a]",- expected: "a",- },- {- name: "empty brackets",- input: "[]",- expected: "[]",- },- {- name: "single bracket char",- input: "[",- expected: "[",- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := stripNodeDelimiters(tc.input)- if result != tc.expected {- t.Errorf("stripNodeDelimiters(%q) = %q, want %q", tc.input, result, tc.expected)- }- })- }-}--func TestParseNodeIP(t *testing.T) {- tests := []struct {- name string- input string- expectNil bool- expectedIP string- }{- {- name: "ipv4",- input: "192.168.1.1",- expectNil: false,- expectedIP: "192.168.1.1",- },- {- name: "ipv4 with whitespace",- input: " 10.0.0.1 ",- expectNil: false,- expectedIP: "10.0.0.1",- },- {- name: "ipv6",- input: "2001:db8::1",- expectNil: false,- expectedIP: "2001:db8::1",- },- {- name: "ipv6 bracketed",- input: "[2001:db8::1]",- expectNil: false,- expectedIP: "2001:db8::1",- },- {- name: "ipv6 loopback",- input: "::1",- expectNil: false,- expectedIP: "::1",- },- {- name: "ipv6 loopback bracketed",- input: "[::1]",- expectNil: false,- expectedIP: "::1",- },- {- name: "hostname",- input: "node-1.example.com",- expectNil: true,- },- {- name: "empty string",- input: "",- expectNil: true,- },- {- name: "invalid ip",- input: "999.999.999.999",- expectNil: true,- },- {- name: "partial ipv4",- input: "192.168.1",- expectNil: true,- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := parseNodeIP(tc.input)- if tc.expectNil {- if result != nil {- t.Errorf("parseNodeIP(%q) = %v, want nil", tc.input, result)- }- } else {- if result == nil {- t.Errorf("parseNodeIP(%q) = nil, want %s", tc.input, tc.expectedIP)- } else if result.String() != tc.expectedIP {- t.Errorf("parseNodeIP(%q) = %v, want %s", tc.input, result, tc.expectedIP)- }- }- })- }-}--func TestNormalizeAllowlistEntry(t *testing.T) {- tests := []struct {- name string- input string- expected string- }{- {- name: "ipv4",- input: "192.168.1.1",- expected: "192.168.1.1",- },- {- name: "ipv4 with whitespace",- input: " 10.0.0.1 ",- expected: "10.0.0.1",- },- {- name: "ipv6",- input: "2001:db8::1",- expected: "2001:db8::1",- },- {- name: "ipv6 bracketed",- input: "[2001:db8::1]",- expected: "2001:db8::1",- },- {- name: "hostname lowercase",- input: "node-1.example.com",- expected: "node-1.example.com",- },- {- name: "hostname uppercase normalized",- input: "NODE-1.EXAMPLE.COM",- expected: "node-1.example.com",- },- {- name: "hostname mixed case",- input: "Node-1.Example.Com",- expected: "node-1.example.com",- },- {- name: "empty string",- input: "",- expected: "",- },- {- name: "whitespace only",- input: " ",- expected: "",- },- {- name: "ipv6 loopback",- input: "::1",- expected: "::1",- },- {- name: "ipv6 full form normalized",- input: "2001:0db8:0000:0000:0000:0000:0000:0001",- expected: "2001:db8::1",- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := normalizeAllowlistEntry(tc.input)- if result != tc.expected {- t.Errorf("normalizeAllowlistEntry(%q) = %q, want %q", tc.input, result, tc.expected)- }- })- }-}--func TestIPAllowed(t *testing.T) {- // Setup test CIDRs- _, cidr10, _ := net.ParseCIDR("10.0.0.0/8")- _, cidr192, _ := net.ParseCIDR("192.168.1.0/24")- _, cidr172, _ := net.ParseCIDR("172.16.0.0/12")-- tests := []struct {- name string- ip net.IP- hosts map[string]struct{}- cidrs []*net.IPNet- expected bool- }{- {- name: "nil ip",- ip: nil,- hosts: map[string]struct{}{"10.0.0.1": {}},- cidrs: nil,- expected: false,- },- {- name: "ip in hosts map",- ip: net.ParseIP("192.168.1.100"),- hosts: map[string]struct{}{"192.168.1.100": {}},- cidrs: nil,- expected: true,- },- {- name: "ip not in hosts map",- ip: net.ParseIP("192.168.1.100"),- hosts: map[string]struct{}{"192.168.1.200": {}},- cidrs: nil,- expected: false,- },- {- name: "ip in cidr range",- ip: net.ParseIP("10.1.2.3"),- hosts: nil,- cidrs: []*net.IPNet{cidr10},- expected: true,- },- {- name: "ip not in cidr range",- ip: net.ParseIP("11.0.0.1"),- hosts: nil,- cidrs: []*net.IPNet{cidr10},- expected: false,- },- {- name: "ip in second cidr",- ip: net.ParseIP("192.168.1.50"),- hosts: nil,- cidrs: []*net.IPNet{cidr10, cidr192},- expected: true,- },- {- name: "ip matches hosts not cidrs",- ip: net.ParseIP("8.8.8.8"),- hosts: map[string]struct{}{"8.8.8.8": {}},- cidrs: []*net.IPNet{cidr10},- expected: true,- },- {- name: "ip matches cidrs not hosts",- ip: net.ParseIP("172.20.0.1"),- hosts: map[string]struct{}{"8.8.8.8": {}},- cidrs: []*net.IPNet{cidr172},- expected: true,- },- {- name: "empty hosts and cidrs",- ip: net.ParseIP("192.168.1.1"),- hosts: nil,- cidrs: nil,- expected: false,- },- {- name: "ipv6 in hosts",- ip: net.ParseIP("2001:db8::1"),- hosts: map[string]struct{}{"2001:db8::1": {}},- cidrs: nil,- expected: true,- },- {- name: "nil hosts map with ip match in cidr",- ip: net.ParseIP("10.255.255.255"),- hosts: nil,- cidrs: []*net.IPNet{cidr10},- expected: true,- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := ipAllowed(tc.ip, tc.hosts, tc.cidrs)- if result != tc.expected {- t.Errorf("ipAllowed(%v, hosts, cidrs) = %v, want %v", tc.ip, result, tc.expected)- }- })- }-}--func TestDefaultHostResolver(t *testing.T) {- r := defaultHostResolver{}- // Test with localhost- ips, err := r.LookupIP(context.Background(), "localhost")- if err != nil {- t.Logf("localhost lookup failed (might be expected in some environments): %v", err)- } else if len(ips) == 0 {- t.Error("expected at least one IP for localhost")- }-- // Test with nil (TODO) context- _, _ = r.LookupIP(context.TODO(), "localhost")-- // Test with invalid host- _, err = r.LookupIP(context.Background(), "invalid.host.local.test")- if err == nil {- t.Error("expected error for invalid host")- }-}--func TestNewNodeValidator(t *testing.T) {- if _, err := newNodeValidator(nil, nil); err == nil {- t.Error("expected error for nil config")- }-- cfg := &Config{- AllowedNodes: []string{"node1", "10.0.0.0/24", ""},- StrictNodeValidation: true,- }- v, err := newNodeValidator(cfg, nil)- if err != nil {- t.Fatal(err)- }- if !v.hasAllowlist {- t.Error("expected hasAllowlist to be true")- }- if len(v.allowHosts) != 1 {- t.Errorf("expected 1 host, got %d", len(v.allowHosts))- }- if len(v.allowCIDRs) != 1 {- t.Errorf("expected 1 CIDR, got %d", len(v.allowCIDRs))- }-}--func TestNodeValidator_UpdateAllowlist(t *testing.T) {- v := &nodeValidator{}- v.UpdateAllowlist([]string{"node1"})- if len(v.allowHosts) != 1 {- t.Error("expected 1 allowed host")- }-- // Update to empty- v.UpdateAllowlist([]string{})- if v.hasAllowlist {- t.Error("expected hasAllowlist to be false")- }-- // Nil validator- var nilV *nodeValidator- nilV.UpdateAllowlist([]string{"node1"})-}--func TestNodeValidator_Validate_Errors(t *testing.T) {- v := &nodeValidator{- hasAllowlist: true,- resolver: stubResolver{- err: errors.New("resolution failed"),- },- allowCIDRs: []*net.IPNet{{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(24, 32)}},- }-- // matchesAllowlist returns error- err := v.Validate(context.Background(), "hostname")- if err == nil || !strings.Contains(err.Error(), "resolution failed") {- t.Errorf("expected resolution failed error, got %v", err)- }-- // Cluster enabled but fetcher fails- v2 := &nodeValidator{- clusterEnabled: true,- clusterFetcher: func() ([]string, error) {- return nil, errors.New("fetch failed")- },- metrics: NewProxyMetrics("test"),- }- // Note: validateAsLocalhost will be called, which might succeed or fail depending on env- _ = v2.Validate(context.Background(), "some-node")-}--func TestNodeValidator_ValidateAsLocalhost(t *testing.T) {- v := &nodeValidator{}- // Test with node that is likely NOT localhost- err := v.validateAsLocalhost(context.Background(), "not-localhost-host")- if err == nil {- t.Error("expected error for non-localhost node")- }-- // Test with "127.0.0.1"- err = v.validateAsLocalhost(context.Background(), "127.0.0.1")- if err != nil {- t.Logf("127.0.0.1 validation failed (env dependent): %v", err)- }-}--func TestGetClusterMembers_Error(t *testing.T) {- v := &nodeValidator{- clusterFetcher: func() ([]string, error) {- return nil, errors.New("fetch failed")- },- }- _, err := v.getClusterMembers(context.Background())- if err == nil {- t.Error("expected error from clusterFetcher")- }-}--func TestGetClusterMembers_ResolutionFails(t *testing.T) {- v := &nodeValidator{- clusterFetcher: func() ([]string, error) {- return []string{"valid-node", "invalid-node", "10.0.0.1", ""}, nil- },- resolver: stubResolver{- err: errors.New("resolution failed"),- },- }- members, err := v.getClusterMembers(context.Background())- if err != nil {- t.Fatal(err)- }- // "valid-node", "invalid-node" (both normalized), and "10.0.0.1" should be in members- // Hostnames are added even if resolution fails.- if len(members) < 3 {- t.Errorf("expected at least 3 members, got %d: %v", len(members), members)- }-}--func TestNodeValidator_Validate_Nil(t *testing.T) {- var v *nodeValidator- if err := v.Validate(context.Background(), "node"); err != nil {- t.Error("expected nil error for nil validator")- }-}diff --git a/internal/api/config_handlers_temperature_test.go b/internal/api/config_handlers_temperature_test.godeleted file mode 100644index c18ed08692..0000000000--- a/internal/api/config_handlers_temperature_test.go+++ /dev/null@@ -1,83 +0,0 @@-package api--import "testing"--func TestDetermineTemperatureTransport(t *testing.T) {- t.Parallel()- testCases := []struct {- name string- enabled bool- proxyURL string- proxyToken string- socketAvailable bool- containerSSHBlocked bool- expectedTransport string- }{- {- name: "disabled",- enabled: false,- expectedTransport: temperatureTransportDisabled,- },- {- name: "https proxy preferred when configured",- enabled: true,- proxyURL: " https://pve.example ",- proxyToken: "token",- expectedTransport: temperatureTransportHTTPSProxy,- },- {- name: "socket proxy when available",- enabled: true,- socketAvailable: true,- expectedTransport: temperatureTransportSocketProxy,- },- {- name: "ssh blocked in container without override",- enabled: true,- socketAvailable: false,- containerSSHBlocked: true,- expectedTransport: temperatureTransportSSHBlocked,- },- {- name: "ssh fallback when nothing else available",- enabled: true,- expectedTransport: temperatureTransportSSHFallback,- },- }-- for _, tc := range testCases {- tc := tc- t.Run(tc.name, func(t *testing.T) {- t.Parallel()- got := determineTemperatureTransport(tc.enabled, tc.proxyURL, tc.proxyToken, tc.socketAvailable, tc.containerSSHBlocked)- if got != tc.expectedTransport {- t.Fatalf("expected %q, got %q", tc.expectedTransport, got)- }- })- }-}--func TestEnsureTemperatureTransportAvailable(t *testing.T) {- t.Parallel()-- t.Run("allows socket transport", func(t *testing.T) {- t.Parallel()- if err := ensureTemperatureTransportAvailable(true, "", "", true, true); err != nil {- t.Fatalf("unexpected error: %v", err)- }- })-- t.Run("blocks container without proxy", func(t *testing.T) {- t.Parallel()- if err := ensureTemperatureTransportAvailable(true, "", "", false, true); err == nil {- t.Fatal("expected error when no transport is available")- }- })-- t.Run("ignores disabled state", func(t *testing.T) {- t.Parallel()- if err := ensureTemperatureTransportAvailable(false, "", "", false, true); err != nil {- t.Fatalf("expected nil error when not enabling transport, got %v", err)- }- })-}diff --git a/internal/api/sensor_proxy_gate.go b/internal/api/sensor_proxy_gate.godeleted file mode 100644index 1761a02a2d..0000000000--- a/internal/api/sensor_proxy_gate.go+++ /dev/null@@ -1,28 +0,0 @@-package api--import "net/http"--func (r *Router) isSensorProxyEnabled() bool {- return r != nil && r.config != nil && r.config.EnableSensorProxy-}--func (r *Router) requireSensorProxyEnabled(next http.HandlerFunc) http.HandlerFunc {- return func(w http.ResponseWriter, req *http.Request) {- if r.isSensorProxyEnabled() {- next(w, req)- return- }-- w.Header().Set("Warning", `299 - "pulse-sensor-proxy is deprecated and disabled by default in v5"`)- writeErrorResponse(- w,- http.StatusGone,- "sensor_proxy_disabled",- "pulse-sensor-proxy is deprecated and disabled by default in v5",- map[string]string{- "migration": "Use pulse-agent --enable-proxmox for temperature monitoring.",- "enable_env": "Set PULSE_ENABLE_SENSOR_PROXY=true (unsupported legacy) and restart Pulse to re-enable these endpoints.",- },- )- }-}diff --git a/internal/api/sensor_proxy_gate_test.go b/internal/api/sensor_proxy_gate_test.godeleted file mode 100644index 6ee038d5bd..0000000000--- a/internal/api/sensor_proxy_gate_test.go+++ /dev/null@@ -1,48 +0,0 @@-package api--import (- "encoding/json"- "net/http"- "net/http/httptest"- "testing"-- "github.com/rcourtman/pulse-go-rewrite/internal/config"-)--func TestSensorProxyGate(t *testing.T) {- r := &Router{config: &config.Config{EnableSensorProxy: true}}- if !r.isSensorProxyEnabled() {- t.Fatal("expected sensor proxy enabled")- }-- allowed := r.requireSensorProxyEnabled(func(w http.ResponseWriter, _ *http.Request) {- w.WriteHeader(http.StatusNoContent)- })- req := httptest.NewRequest(http.MethodGet, "/api/sensor", nil)- resp := httptest.NewRecorder()- allowed(resp, req)- if resp.Code != http.StatusNoContent {- t.Fatalf("unexpected status: %d", resp.Code)- }-- r.config.EnableSensorProxy = false- denied := r.requireSensorProxyEnabled(func(http.ResponseWriter, *http.Request) {- t.Fatal("handler should not be called")- })- resp = httptest.NewRecorder()- denied(resp, req)- if resp.Code != http.StatusGone {- t.Fatalf("unexpected status: %d", resp.Code)- }- if warning := resp.Header().Get("Warning"); warning == "" {- t.Fatal("expected Warning header")- }-- var apiErr APIError- if err := json.Unmarshal(resp.Body.Bytes(), &apiErr); err != nil {- t.Fatalf("decode response: %v", err)- }- if apiErr.Code != "sensor_proxy_disabled" {- t.Fatalf("unexpected error code: %s", apiErr.Code)- }-}diff --git a/internal/api/temperature_proxy.go b/internal/api/temperature_proxy.godeleted file mode 100644index a8ef259b20..0000000000--- a/internal/api/temperature_proxy.go+++ /dev/null@@ -1,549 +0,0 @@-package api--import (- "crypto/rand"- "crypto/sha256"- "encoding/base64"- "encoding/hex"- "encoding/json"- "fmt"- "net/http"- "net/url"- "sort"- "strconv"- "strings"- "sync"- "time"-- "github.com/rcourtman/pulse-go-rewrite/internal/config"- "github.com/rcourtman/pulse-go-rewrite/internal/utils"- "github.com/rs/zerolog/log"-)--// TemperatureProxyHandlers manages temperature proxy registration-type TemperatureProxyHandlers struct {- config *config.Config- persistence *config.ConfigPersistence- reloadFunc func() error- syncMu sync.RWMutex- syncStatus map[string]proxySyncState-}--type proxySyncState struct {- Instance string- LastPull time.Time- RefreshInterval int-}--const defaultProxyAllowlistRefreshSeconds = 60--type authorizedNode struct {- Name string `json:"name,omitempty"`- IP string `json:"ip,omitempty"`-}--// NewTemperatureProxyHandlers constructs a new handler set for temperature proxy-func NewTemperatureProxyHandlers(cfg *config.Config, persistence *config.ConfigPersistence, reloadFunc func() error) *TemperatureProxyHandlers {- return &TemperatureProxyHandlers{- config: cfg,- persistence: persistence,- reloadFunc: reloadFunc,- syncStatus: make(map[string]proxySyncState),- }-}--// SetConfig updates the configuration reference used by the handler.-func (h *TemperatureProxyHandlers) SetConfig(cfg *config.Config) {- if h != nil {- h.config = cfg- }-}--func (h *TemperatureProxyHandlers) recordSync(instance string, refreshSeconds int) {- if h == nil {- return- }-- instance = strings.TrimSpace(instance)- if instance == "" {- return- }-- if refreshSeconds <= 0 {- refreshSeconds = defaultProxyAllowlistRefreshSeconds- }-- h.syncMu.Lock()- defer h.syncMu.Unlock()-- key := strings.ToLower(instance)- h.syncStatus[key] = proxySyncState{- Instance: instance,- LastPull: time.Now(),- RefreshInterval: refreshSeconds,- }-}--// SnapshotSyncStatus returns a copy of the current sync status for all temperature proxies.-func (h *TemperatureProxyHandlers) SnapshotSyncStatus() map[string]proxySyncState {- if h == nil {- return nil- }-- h.syncMu.RLock()- defer h.syncMu.RUnlock()-- if len(h.syncStatus) == 0 {- return nil- }-- copy := make(map[string]proxySyncState, len(h.syncStatus))- for key, state := range h.syncStatus {- copy[key] = state- }- return copy-}--func extractHostPart(raw string) string {- host := strings.TrimSpace(raw)- if host == "" {- return ""- }-- if strings.HasPrefix(host, "http://") || strings.HasPrefix(host, "https://") {- if parsed, err := url.Parse(host); err == nil {- return parsed.Hostname()- }- }-- if idx := strings.Index(host, "/"); idx != -1 {- host = host[:idx]- }- if idx := strings.Index(host, ":"); idx != -1 {- host = host[:idx]- }- return strings.TrimSpace(host)-}--func buildAuthorizedNodeList(instances []config.PVEInstance) []authorizedNode {- nodes := make([]authorizedNode, 0)- seen := make(map[string]struct{})- add := func(name, ip string) {- name = strings.TrimSpace(name)- ip = strings.TrimSpace(ip)- if name == "" && ip == "" {- return- }- key := name + "|" + ip- if _, ok := seen[key]; ok {- return- }- seen[key] = struct{}{}- nodes = append(nodes, authorizedNode{Name: name, IP: ip})- }-- for i := range instances {- instance := &instances[i]- add(instance.Name, extractHostPart(instance.Host))- add(instance.Name, extractHostPart(instance.GuestURL))-- if instance.ClusterEndpoints != nil {- for _, ep := range instance.ClusterEndpoints {- name := ep.NodeName- // Use EffectiveIP() which prefers IPOverride over auto-discovered IP- ip := ep.EffectiveIP()- if ip == "" {- ip = extractHostPart(ep.Host)- }- if name == "" {- name = ep.Host- }- add(name, ip)- }- }- }-- return nodes-}--// HandleRegister handles temperature proxy registration from the installer-//-// POST /api/temperature-proxy/register-// Body: {"hostname": "pve1", "proxy_url": "https://pve1.lan:8443"}-// Response: {"success": true, "token": "...", "pve_instance": "pve1"}-func (h *TemperatureProxyHandlers) HandleRegister(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only POST is allowed", nil)- return- }-- // Limit request body to 8KB to prevent memory exhaustion- r.Body = http.MaxBytesReader(w, r.Body, 8*1024)- defer r.Body.Close()-- var req struct {- Hostname string `json:"hostname"`- ProxyURL string `json:"proxy_url"`- Mode string `json:"mode"`- }-- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", map[string]string{"error": err.Error()})- return- }-- // Validate inputs- hostname := strings.TrimSpace(req.Hostname)- proxyURL := strings.TrimSpace(req.ProxyURL)-- if hostname == "" {- writeErrorResponse(w, http.StatusBadRequest, "missing_hostname", "Hostname is required", nil)- return- }-- mode := strings.ToLower(strings.TrimSpace(req.Mode))- if mode == "" {- if proxyURL != "" {- mode = "http"- } else {- mode = "socket"- }- }-- isHTTPMode := mode == "http"- if isHTTPMode {- if proxyURL == "" {- writeErrorResponse(w, http.StatusBadRequest, "missing_proxy_url", "Proxy URL is required for HTTP mode", nil)- return- }- if !strings.HasPrefix(strings.ToLower(proxyURL), "https://") {- writeErrorResponse(w, http.StatusBadRequest, "invalid_proxy_url", "Proxy URL must use HTTPS", nil)- return- }- } else {- proxyURL = ""- }-- // Load current config- nodesConfig, err := h.persistence.LoadNodesConfig()- if err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "config_load_failed", "Failed to load configuration", map[string]string{"error": err.Error()})- return- }-- // Find matching PVE instance by hostname- var matchedInstance *config.PVEInstance- var matchedIndex int- var matchedEndpointIndex = -1 // For cluster nodes, track which endpoint matched- hostnameLower := strings.ToLower(hostname)-- for i := range nodesConfig.PVEInstances {- instance := &nodesConfig.PVEInstances[i]-- // Try to match by instance name- if strings.EqualFold(instance.Name, hostname) {- matchedInstance = instance- matchedIndex = i- break- }-- // Try to match by hostname in the Host field or cluster endpoints- if strings.Contains(strings.ToLower(instance.Host), hostnameLower) {- matchedInstance = instance- matchedIndex = i- break- }-- // Check cluster endpoints- if instance.IsCluster {- for j, ep := range instance.ClusterEndpoints {- if strings.EqualFold(ep.NodeName, hostname) || strings.Contains(strings.ToLower(ep.Host), hostnameLower) {- matchedInstance = instance- matchedIndex = i- matchedEndpointIndex = j- break- }- }- }- }-- if matchedInstance == nil {- writeErrorResponse(w, http.StatusNotFound, "pve_instance_not_found", fmt.Sprintf("No PVE instance configured for hostname '%s'. Add the instance in Pulse first.", hostname), nil)- return- }-- // Generate tokens- authToken := ""- if isHTTPMode {- authToken, err = generateSecureToken(32)- if err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "token_generation_failed", "Failed to generate authentication token", map[string]string{"error": err.Error()})- return- }- }-- ctrlToken, err := generateSecureToken(32)- if err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "token_generation_failed", "Failed to generate authentication token", map[string]string{"error": err.Error()})- return- }-- // Update the instance with proxy configuration- // For clusters, store per-node tokens on the ClusterEndpoint; instance-level token is for non-cluster or fallback- nodesConfig.PVEInstances[matchedIndex].TemperatureProxyURL = proxyURL- if isHTTPMode {- nodesConfig.PVEInstances[matchedIndex].TemperatureProxyToken = authToken- }-- // For cluster nodes, store token on the specific endpoint so each node has its own token- if matchedEndpointIndex >= 0 && matchedInstance.IsCluster {- nodesConfig.PVEInstances[matchedIndex].ClusterEndpoints[matchedEndpointIndex].TemperatureProxyControlToken = ctrlToken- log.Debug().- Str("hostname", hostname).- Int("endpoint_index", matchedEndpointIndex).- Msg("Storing control token on cluster endpoint")- } else {- // Non-cluster instance or matched by instance name directly- nodesConfig.PVEInstances[matchedIndex].TemperatureProxyControlToken = ctrlToken- }-- // Save updated configuration- log.Debug().- Int("matchedIndex", matchedIndex).- Int("matchedEndpointIndex", matchedEndpointIndex).- Str("saving_url", nodesConfig.PVEInstances[matchedIndex].TemperatureProxyURL).- Bool("saving_has_token", nodesConfig.PVEInstances[matchedIndex].TemperatureProxyToken != "").- Str("instance_name", nodesConfig.PVEInstances[matchedIndex].Name).- Msg("About to save nodes config with proxy registration")- if err := h.persistence.SaveNodesConfig(nodesConfig.PVEInstances, nodesConfig.PBSInstances, nodesConfig.PMGInstances); err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "config_save_failed", "Failed to save configuration", map[string]string{"error": err.Error()})- return- }-- // Reload the entire config to ensure all components (router, monitor, handlers) get the fresh config- // This prevents the monitor from later overwriting nodes.enc with stale data- if h.reloadFunc != nil {- if err := h.reloadFunc(); err != nil {- log.Error().Err(err).Msg("Failed to reload config after temperature proxy registration")- // Don't fail the request - the save succeeded, reload is best-effort- } else {- log.Info().Str("instance", matchedInstance.Name).Msg("Config reloaded after temperature proxy registration")- }- }-- log.Info().- Str("hostname", hostname).- Str("proxy_url", proxyURL).- Str("mode", mode).- Str("pve_instance", matchedInstance.Name).- Msg("Temperature proxy registered successfully")-- allowed := buildAuthorizedNodeList(nodesConfig.PVEInstances)- resp := map[string]any{- "success": true,- "token": authToken,- "control_token": ctrlToken,- "pve_instance": matchedInstance.Name,- "allowed_nodes": allowed,- "refresh_interval": defaultProxyAllowlistRefreshSeconds,- "message": fmt.Sprintf("Temperature proxy registered for instance '%s'", matchedInstance.Name),- }-- if err := utils.WriteJSONResponse(w, resp); err != nil {- log.Error().Err(err).Msg("Failed to serialize temperature proxy registration response")- }-}--// HandleAuthorizedNodes returns the list of nodes Pulse has authorized for a proxy.-//-// GET /api/temperature-proxy/authorized-nodes-// Headers:-//-// X-Proxy-Token: <control-plane token>-func (h *TemperatureProxyHandlers) HandleAuthorizedNodes(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only GET is allowed", nil)- return- }-- token := strings.TrimSpace(r.Header.Get("X-Proxy-Token"))- if token == "" {- authHeader := strings.TrimSpace(r.Header.Get("Authorization"))- if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {- token = strings.TrimSpace(authHeader[7:])- }- }-- if token == "" {- writeErrorResponse(w, http.StatusUnauthorized, "missing_token", "X-Proxy-Token header required", nil)- return- }-- nodesConfig, err := h.persistence.LoadNodesConfig()- if err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "config_load_failed", "Failed to load configuration", map[string]string{"error": err.Error()})- return- }-- var matched *config.PVEInstance- for i := range nodesConfig.PVEInstances {- inst := &nodesConfig.PVEInstances[i]-- // Check instance-level token first- switch {- case strings.TrimSpace(inst.TemperatureProxyControlToken) == token:- matched = inst- case inst.TemperatureProxyControlToken == "" && strings.TrimSpace(inst.TemperatureProxyToken) == token:- // Legacy HTTP-mode proxies reuse TemperatureProxyToken- matched = inst- }- if matched != nil {- break- }-- // For clusters, also check per-node tokens on ClusterEndpoints- if inst.IsCluster {- for j := range inst.ClusterEndpoints {- ep := &inst.ClusterEndpoints[j]- if strings.TrimSpace(ep.TemperatureProxyControlToken) == token {- matched = inst- break- }- }- if matched != nil {- break- }- }- }-- refreshFromProxy := 0- if hdr := strings.TrimSpace(r.Header.Get("X-Proxy-Refresh")); hdr != "" {- if val, err := strconv.Atoi(hdr); err == nil && val > 0 {- refreshFromProxy = val- }- }-- if matched == nil {- writeErrorResponse(w, http.StatusUnauthorized, "invalid_token", "Proxy token not recognized", nil)- return- }-- refreshInterval := defaultProxyAllowlistRefreshSeconds- if refreshFromProxy > 0 {- refreshInterval = refreshFromProxy- }-- nodes := buildAuthorizedNodeList(nodesConfig.PVEInstances)- if len(nodes) == 0 && matched != nil {- nodes = append(nodes, authorizedNode{Name: matched.Name, IP: extractHostPart(matched.Host)})- }-- hashMaterial := make([]string, 0, len(nodes))- for _, node := range nodes {- hashMaterial = append(hashMaterial, fmt.Sprintf("%s|%s", node.Name, node.IP))- }- sort.Strings(hashMaterial)- hashBytes := sha256.Sum256([]byte(strings.Join(hashMaterial, "\n")))-- resp := map[string]interface{}{- "instance": matched.Name,- "nodes": nodes,- "hash": hex.EncodeToString(hashBytes[:]),- "refresh_interval": refreshInterval,- "generated_at": time.Now().UTC(),- }-- if err := utils.WriteJSONResponse(w, resp); err != nil {- log.Error().Err(err).Msg("Failed to write authorized-nodes response")- } else {- h.recordSync(matched.Name, refreshInterval)- }-}--// HandleUnregister removes temperature proxy configuration from a PVE instance-//-// DELETE /api/temperature-proxy/unregister?hostname=pve1-func (h *TemperatureProxyHandlers) HandleUnregister(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodDelete {- writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only DELETE is allowed", nil)- return- }-- hostname := strings.TrimSpace(r.URL.Query().Get("hostname"))- if hostname == "" {- writeErrorResponse(w, http.StatusBadRequest, "missing_hostname", "Hostname query parameter is required", nil)- return- }-- // Load current config- nodesConfig, err := h.persistence.LoadNodesConfig()- if err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "config_load_failed", "Failed to load configuration", map[string]string{"error": err.Error()})- return- }-- // Find matching PVE instance- var matchedIndex = -1- var matchedName string- hostnameLower := strings.ToLower(hostname)-- for i := range nodesConfig.PVEInstances {- instance := &nodesConfig.PVEInstances[i]-- if strings.Contains(strings.ToLower(instance.Host), hostnameLower) {- matchedIndex = i- matchedName = instance.Name- break- }-- if instance.IsCluster {- for _, ep := range instance.ClusterEndpoints {- if strings.EqualFold(ep.NodeName, hostname) || strings.Contains(strings.ToLower(ep.Host), hostnameLower) {- matchedIndex = i- matchedName = instance.Name- break- }- }- }- }-- if matchedIndex == -1 {- writeErrorResponse(w, http.StatusNotFound, "pve_instance_not_found", fmt.Sprintf("No PVE instance found for hostname '%s'", hostname), nil)- return- }-- // Clear proxy configuration- nodesConfig.PVEInstances[matchedIndex].TemperatureProxyURL = ""- nodesConfig.PVEInstances[matchedIndex].TemperatureProxyToken = ""- nodesConfig.PVEInstances[matchedIndex].TemperatureProxyControlToken = ""-- // Save updated configuration- if err := h.persistence.SaveNodesConfig(nodesConfig.PVEInstances, nodesConfig.PBSInstances, nodesConfig.PMGInstances); err != nil {- writeErrorResponse(w, http.StatusInternalServerError, "config_save_failed", "Failed to save configuration", map[string]string{"error": err.Error()})- return- }-- log.Info().- Str("hostname", hostname).- Str("pve_instance", matchedName).- Msg("Temperature proxy unregistered")-- resp := map[string]any{- "success": true,- "pve_instance": matchedName,- "message": "Temperature proxy configuration removed",- }-- if err := utils.WriteJSONResponse(w, resp); err != nil {- log.Error().Err(err).Msg("Failed to serialize temperature proxy unregistration response")- }-}--// generateSecureToken creates a cryptographically secure random token-func generateSecureToken(byteLength int) (string, error) {- bytes := make([]byte, byteLength)- if _, err := rand.Read(bytes); err != nil {- return "", fmt.Errorf("failed to generate random bytes: %w", err)- }- return base64.URLEncoding.EncodeToString(bytes), nil-}diff --git a/internal/api/temperature_proxy_command_test.go b/internal/api/temperature_proxy_command_test.godeleted file mode 100644index b0a70b3979..0000000000--- a/internal/api/temperature_proxy_command_test.go+++ /dev/null@@ -1,48 +0,0 @@-package api--import (- "encoding/json"- "net/http"- "net/http/httptest"- "strings"- "testing"-- "github.com/rcourtman/pulse-go-rewrite/internal/config"-)--func TestHandleTemperatureProxyInstallCommand(t *testing.T) {- cfg := &config.Config{PublicURL: "https://pulse.example:7655"}- router := &Router{config: cfg}-- req := httptest.NewRequest(http.MethodGet, "/api/temperature-proxy/install-command?node=pve-a", nil)- rec := httptest.NewRecorder()-- router.handleTemperatureProxyInstallCommand(rec, req)-- if rec.Code != http.StatusOK {- t.Fatalf("expected status 200, got %d", rec.Code)- }-- var resp map[string]string- if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {- t.Fatalf("failed to decode response: %v", err)- }-- if resp["node"] != "pve-a" {- t.Fatalf("expected node pve-a, got %s", resp["node"])- }-- command := resp["command"]- if command == "" {- t.Fatalf("command missing in response")- }- if !strings.Contains(command, cfg.PublicURL) {- t.Fatalf("command does not include pulse URL: %s", command)- }- if !strings.Contains(command, "--ctid") {- t.Fatalf("command missing expected --ctid flag: %s", command)- }- if !strings.Contains(command, "--pulse-server") {- t.Fatalf("command missing expected --pulse-server flag: %s", command)- }-}diff --git a/internal/api/temperature_proxy_test.go b/internal/api/temperature_proxy_test.godeleted file mode 100644index c79c8f86f4..0000000000--- a/internal/api/temperature_proxy_test.go+++ /dev/null@@ -1,420 +0,0 @@-package api--import (- "testing"-- "github.com/rcourtman/pulse-go-rewrite/internal/config"-)--func TestExtractHostPart(t *testing.T) {- tests := []struct {- name string- input string- expected string- }{- // Empty/whitespace inputs- {name: "empty string", input: "", expected: ""},- {name: "whitespace only", input: " ", expected: ""},- {name: "tabs and newlines", input: "\t\n", expected: ""},-- // Simple hostnames- {name: "simple hostname", input: "pve1.local", expected: "pve1.local"},- {name: "hostname with whitespace", input: " pve1.local ", expected: "pve1.local"},- {name: "ip address", input: "192.168.1.100", expected: "192.168.1.100"},-- // Hostnames with ports- {name: "hostname with port", input: "pve1.local:8006", expected: "pve1.local"},- {name: "ip with port", input: "192.168.1.100:8006", expected: "192.168.1.100"},- {name: "ipv4 with default port", input: "10.0.0.1:443", expected: "10.0.0.1"},-- // URLs with scheme- {name: "https url", input: "https://pve1.local", expected: "pve1.local"},- {name: "https url with port", input: "https://pve1.local:8006", expected: "pve1.local"},- {name: "http url", input: "http://pve1.local", expected: "pve1.local"},- {name: "http url with port", input: "http://pve1.local:8080", expected: "pve1.local"},- {name: "https url with ip", input: "https://192.168.1.100:8006", expected: "192.168.1.100"},-- // URLs with paths- {name: "url with path", input: "https://pve1.local/api2", expected: "pve1.local"},- {name: "url with path and port", input: "https://pve1.local:8006/api2/json", expected: "pve1.local"},-- // Hostnames with paths (no scheme)- {name: "hostname with path", input: "pve1.local/api", expected: "pve1.local"},- {name: "hostname with port and path", input: "pve1.local:8006/api", expected: "pve1.local"},-- // Edge cases- {name: "just a port colon", input: ":8006", expected: ""},- {name: "just a slash", input: "/api", expected: ""},- {name: "double colon", input: "host::8006", expected: "host"},- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := extractHostPart(tc.input)- if result != tc.expected {- t.Errorf("extractHostPart(%q) = %q, want %q", tc.input, result, tc.expected)- }- })- }-}--func TestBuildAuthorizedNodeList(t *testing.T) {- t.Run("empty instances", func(t *testing.T) {- result := buildAuthorizedNodeList(nil)- if len(result) != 0 {- t.Errorf("expected empty list for nil input, got %d items", len(result))- }-- result = buildAuthorizedNodeList([]config.PVEInstance{})- if len(result) != 0 {- t.Errorf("expected empty list for empty slice, got %d items", len(result))- }- })-- t.Run("single instance with host", func(t *testing.T) {- instances := []config.PVEInstance{- {Name: "pve1", Host: "https://pve1.local:8006"},- }- result := buildAuthorizedNodeList(instances)-- // Function calls add() for both Host and GuestURL (even if empty)- // With empty GuestURL, we get one entry from Host only (name=pve1, IP=pve1.local)- // But it also adds an entry for the empty GuestURL case: (name=pve1, IP="")- // So we expect 2 entries- if len(result) != 2 {- t.Fatalf("expected 2 nodes (Host + empty GuestURL), got %d: %+v", len(result), result)- }-- // Verify the Host-based entry exists- foundHostEntry := false- for _, node := range result {- if node.Name == "pve1" && node.IP == "pve1.local" {- foundHostEntry = true- break- }- }- if !foundHostEntry {- t.Errorf("expected entry for Host (name=pve1, IP=pve1.local) in %+v", result)- }- })-- t.Run("instance with GuestURL", func(t *testing.T) {- instances := []config.PVEInstance{- {- Name: "pve1",- Host: "https://pve1.local:8006",- GuestURL: "https://guest.local:8006",- },- }- result := buildAuthorizedNodeList(instances)-- // Should have 2 entries: one from Host and one from GuestURL- if len(result) != 2 {- t.Fatalf("expected 2 nodes, got %d", len(result))- }-- // Check that both entries exist- foundHost := false- foundGuest := false- for _, node := range result {- if node.IP == "pve1.local" {- foundHost = true- }- if node.IP == "guest.local" {- foundGuest = true- }- }- if !foundHost {- t.Error("missing entry for Host URL")- }- if !foundGuest {- t.Error("missing entry for GuestURL")- }- })-- t.Run("cluster endpoints", func(t *testing.T) {- instances := []config.PVEInstance{- {- Name: "cluster1",- Host: "https://pve1.local:8006",- IsCluster: true,- ClusterEndpoints: []config.ClusterEndpoint{- {NodeName: "pve2", Host: "https://pve2.local:8006", IP: ""},- {NodeName: "pve3", Host: "", IP: "192.168.1.103"},- },- },- }- result := buildAuthorizedNodeList(instances)-- // Should have 4 entries:- // - (cluster1, pve1.local) from Host- // - (cluster1, "") from empty GuestURL- // - (pve2, pve2.local) from ClusterEndpoint[0]- // - (pve3, 192.168.1.103) from ClusterEndpoint[1]- if len(result) != 4 {- t.Fatalf("expected 4 nodes, got %d: %+v", len(result), result)- }- })-- t.Run("deduplication", func(t *testing.T) {- instances := []config.PVEInstance{- {Name: "pve1", Host: "https://pve1.local:8006"},- {Name: "pve1", Host: "https://pve1.local:8006"}, // duplicate- }- result := buildAuthorizedNodeList(instances)-- // Each instance adds 2 entries (Host and empty GuestURL)- // But deduplication should result in 2 unique entries:- // - (pve1, pve1.local) - from Host- // - (pve1, "") - from empty GuestURL- if len(result) != 2 {- t.Errorf("expected 2 nodes after dedup (host + empty guesturl), got %d: %+v", len(result), result)- }- })-- t.Run("empty name and ip filtered", func(t *testing.T) {- instances := []config.PVEInstance{- {Name: "", Host: ""}, // should be skipped- {Name: "pve1", Host: ""}, // should be added with empty IP- {Name: "", Host: "pve2.local"}, // should be added with empty name- }- result := buildAuthorizedNodeList(instances)-- // First entry has empty name and IP - should be skipped- // Second has name but empty IP- // Third has empty name but IP- if len(result) != 2 {- t.Errorf("expected 2 nodes, got %d: %+v", len(result), result)- }- })-- t.Run("cluster endpoint with IP takes precedence", func(t *testing.T) {- instances := []config.PVEInstance{- {- Name: "cluster1",- Host: "https://pve1.local:8006",- IsCluster: true,- ClusterEndpoints: []config.ClusterEndpoint{- {NodeName: "pve2", Host: "https://pve2.local:8006", IP: "10.0.0.2"},- },- },- }- result := buildAuthorizedNodeList(instances)-- // Should have 2 entries: pve1.local and 10.0.0.2 (IP from endpoint, not host)- foundIP := false- for _, node := range result {- if node.IP == "10.0.0.2" {- foundIP = true- }- if node.IP == "pve2.local" {- t.Error("expected IP to take precedence over Host extraction")- }- }- if !foundIP {- t.Error("expected to find IP 10.0.0.2 from cluster endpoint")- }- })-- t.Run("cluster endpoint name fallback to host", func(t *testing.T) {- instances := []config.PVEInstance{- {- Name: "cluster1",- Host: "https://pve1.local:8006",- IsCluster: true,- ClusterEndpoints: []config.ClusterEndpoint{- {NodeName: "", Host: "pve2.local", IP: "10.0.0.2"},- },- },- }- result := buildAuthorizedNodeList(instances)-- // Should find an entry where name is the host value- foundNameFallback := false- for _, node := range result {- if node.Name == "pve2.local" && node.IP == "10.0.0.2" {- foundNameFallback = true- }- }- if !foundNameFallback {- t.Errorf("expected name to fallback to host, got: %+v", result)- }- })-}--func TestGenerateSecureToken(t *testing.T) {- t.Run("generates non-empty token", func(t *testing.T) {- token, err := generateSecureToken(32)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if token == "" {- t.Error("expected non-empty token")- }- })-- t.Run("token length corresponds to byte length", func(t *testing.T) {- // 32 bytes = 256 bits, base64 encoded = 44 chars (with padding)- token, err := generateSecureToken(32)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- // Base64 URL encoding: 32 bytes = ceil(32 * 4 / 3) = 43 chars + padding = 44- if len(token) != 44 {- t.Errorf("expected token length 44, got %d", len(token))- }- })-- t.Run("tokens are unique", func(t *testing.T) {- tokens := make(map[string]bool)- for i := 0; i < 100; i++ {- token, err := generateSecureToken(32)- if err != nil {- t.Fatalf("unexpected error on iteration %d: %v", i, err)- }- if tokens[token] {- t.Errorf("duplicate token generated on iteration %d", i)- }- tokens[token] = true- }- })-- t.Run("different byte lengths", func(t *testing.T) {- testCases := []struct {- bytes int- expectedLength int- }{- {16, 24}, // 16 bytes = 128 bits, base64 = 22 chars + 2 padding- {24, 32}, // 24 bytes = 192 bits, base64 = 32 chars- {48, 64}, // 48 bytes = 384 bits, base64 = 64 chars- }-- for _, tc := range testCases {- token, err := generateSecureToken(tc.bytes)- if err != nil {- t.Errorf("unexpected error for %d bytes: %v", tc.bytes, err)- continue- }- if len(token) != tc.expectedLength {- t.Errorf("generateSecureToken(%d) length = %d, want %d", tc.bytes, len(token), tc.expectedLength)- }- }- })-- t.Run("zero bytes returns empty string", func(t *testing.T) {- token, err := generateSecureToken(0)- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if token != "" {- t.Errorf("expected empty token for 0 bytes, got %q", token)- }- })-}--func TestProxySyncState(t *testing.T) {- t.Run("record and snapshot sync", func(t *testing.T) {- handlers := NewTemperatureProxyHandlers(nil, nil, nil)-- // Initially empty- snap := handlers.SnapshotSyncStatus()- if snap != nil {- t.Errorf("expected nil snapshot initially, got %+v", snap)- }-- // Record a sync- handlers.recordSync("pve1", 60)-- snap = handlers.SnapshotSyncStatus()- if snap == nil {- t.Fatal("expected non-nil snapshot after recording sync")- }- if len(snap) != 1 {- t.Errorf("expected 1 entry, got %d", len(snap))- }-- // Key should be lowercase- state, ok := snap["pve1"]- if !ok {- t.Error("expected entry for 'pve1'")- }- if state.Instance != "pve1" {- t.Errorf("expected Instance 'pve1', got %q", state.Instance)- }- if state.RefreshInterval != 60 {- t.Errorf("expected RefreshInterval 60, got %d", state.RefreshInterval)- }- if state.LastPull.IsZero() {- t.Error("expected non-zero LastPull time")- }- })-- t.Run("record with empty instance ignored", func(t *testing.T) {- handlers := NewTemperatureProxyHandlers(nil, nil, nil)-- handlers.recordSync("", 60)- handlers.recordSync(" ", 60)-- snap := handlers.SnapshotSyncStatus()- if snap != nil {- t.Errorf("expected nil snapshot for empty instances, got %+v", snap)- }- })-- t.Run("default refresh interval", func(t *testing.T) {- handlers := NewTemperatureProxyHandlers(nil, nil, nil)-- handlers.recordSync("pve1", 0) // 0 should use default- handlers.recordSync("pve2", -1) // negative should use default-- snap := handlers.SnapshotSyncStatus()- if snap["pve1"].RefreshInterval != defaultProxyAllowlistRefreshSeconds {- t.Errorf("expected default refresh for 0, got %d", snap["pve1"].RefreshInterval)- }- if snap["pve2"].RefreshInterval != defaultProxyAllowlistRefreshSeconds {- t.Errorf("expected default refresh for -1, got %d", snap["pve2"].RefreshInterval)- }- })-- t.Run("snapshot returns copy", func(t *testing.T) {- handlers := NewTemperatureProxyHandlers(nil, nil, nil)- handlers.recordSync("pve1", 60)-- snap1 := handlers.SnapshotSyncStatus()- snap2 := handlers.SnapshotSyncStatus()-- // Modify snap1- snap1["modified"] = proxySyncState{Instance: "modified"}-- // snap2 should not be affected- if _, ok := snap2["modified"]; ok {- t.Error("snapshot should return a copy, not a reference")- }- })-- t.Run("nil handlers safe", func(t *testing.T) {- var handlers *TemperatureProxyHandlers-- // These should not panic- handlers.recordSync("pve1", 60)- snap := handlers.SnapshotSyncStatus()- if snap != nil {- t.Error("expected nil from nil handlers")- }- })-- t.Run("case insensitive key storage", func(t *testing.T) {- handlers := NewTemperatureProxyHandlers(nil, nil, nil)-- handlers.recordSync("PVE1", 60)- handlers.recordSync("pve1", 120) // should overwrite-- snap := handlers.SnapshotSyncStatus()- if len(snap) != 1 {- t.Errorf("expected 1 entry after case-insensitive merge, got %d", len(snap))- }- if snap["pve1"].RefreshInterval != 120 {- t.Errorf("expected overwritten refresh 120, got %d", snap["pve1"].RefreshInterval)- }- })-}diff --git a/internal/monitoring/monitor_proxy_test.go b/internal/monitoring/monitor_proxy_test.godeleted file mode 100644index d9f4aba73b..0000000000--- a/internal/monitoring/monitor_proxy_test.go+++ /dev/null@@ -1,23 +0,0 @@-package monitoring--import (- "os"- "path/filepath"- "testing"-)--func TestMonitorHasSocketTemperatureProxyDetectsEnvSocket(t *testing.T) {- dir := t.TempDir()- socketPath := filepath.Join(dir, "pulse-sensor-proxy.sock")-- if err := os.WriteFile(socketPath, []byte("socket-placeholder"), 0o600); err != nil {- t.Fatalf("failed to create fake socket: %v", err)- }-- t.Setenv("PULSE_SENSOR_PROXY_SOCKET", socketPath)-- monitor := &Monitor{}- if !monitor.HasSocketTemperatureProxy() {- t.Fatalf("expected monitor to detect proxy socket at %s", socketPath)- }-}diff --git a/internal/monitoring/temperature_test.go b/internal/monitoring/temperature_test.godeleted file mode 100644index f47053d4af..0000000000--- a/internal/monitoring/temperature_test.go+++ /dev/null@@ -1,3471 +0,0 @@-package monitoring--import (- "context"- "fmt"- "math"- "strings"- "sync"- "sync/atomic"- "testing"- "time"-- "github.com/rcourtman/pulse-go-rewrite/internal/models"- "github.com/rcourtman/pulse-go-rewrite/internal/tempproxy"-)--type stubProxyResponse struct {- output string- err error-}--type stubTemperatureProxy struct {- mu sync.Mutex- available bool- responses []stubProxyResponse- responseFunc func(call int) stubProxyResponse- callCount int-}--func (s *stubTemperatureProxy) IsAvailable() bool {- s.mu.Lock()- defer s.mu.Unlock()- return s.available-}--func (s *stubTemperatureProxy) GetTemperature(host string) (string, error) {- s.mu.Lock()- call := s.callCount- s.callCount++-- resp := stubProxyResponse{}- switch {- case call < len(s.responses):- resp = s.responses[call]- case s.responseFunc != nil:- resp = s.responseFunc(call)- case len(s.responses) > 0:- resp = s.responses[len(s.responses)-1]- }- s.mu.Unlock()-- return resp.output, resp.err-}--func (s *stubTemperatureProxy) setAvailable(v bool) {- s.mu.Lock()- s.available = v- s.mu.Unlock()-}--func TestParseSensorsJSON_NoTemperatureData(t *testing.T) {- collector := &TemperatureCollector{}-- // Test with a chip that doesn't match any known CPU or NVMe patterns- jsonStr := `{- "unknown-sensor-0": {- "Adapter": "Unknown interface",- "temp1": {- "temp1_label": "temp1"- }- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing sensors output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if temp.Available {- t.Fatalf("expected temperature to be unavailable when no CPU or NVMe chips are detected")- }- if temp.HasCPU {- t.Fatalf("expected HasCPU to be false when no CPU chip detected")- }- if temp.HasNVMe {- t.Fatalf("expected HasNVMe to be false when no NVMe chip detected")- }-}--func TestParseSensorsJSON_WithCpuAndNvmeData(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{- "coretemp-isa-0000": {- "Package id 0": {"temp1_input": 45.5},- "Core 0": {"temp2_input": 43.0},- "Core 1": {"temp3_input": 44.2}- },- "nvme-pci-0400": {- "Composite": {"temp1_input": 38.75}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing sensors output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if !temp.Available {- t.Fatalf("expected temperature to be available when readings are present")- }- if temp.CPUPackage != 45.5 {- t.Fatalf("expected cpu package temperature 45.5, got %.2f", temp.CPUPackage)- }- if temp.CPUMax <= 0 {- t.Fatalf("expected cpu max temperature to be greater than zero, got %.2f", temp.CPUMax)- }- if len(temp.Cores) != 2 {- t.Fatalf("expected two core temperatures, got %d", len(temp.Cores))- }- if len(temp.NVMe) != 1 {- t.Fatalf("expected one NVMe temperature, got %d", len(temp.NVMe))- }- if temp.NVMe[0].Temp != 38.75 {- t.Fatalf("expected NVMe temperature 38.75, got %.2f", temp.NVMe[0].Temp)- }- if !temp.HasCPU {- t.Fatalf("expected HasCPU to be true when CPU data present")- }- if !temp.HasNVMe {- t.Fatalf("expected HasNVMe to be true when NVMe data present")- }-}--func TestParseSensorsJSON_WithAmdTctlOnly(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{- "k10temp-pci-00c3": {- "Tctl": {"temp1_input": 55.4}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing sensors output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if !temp.Available {- t.Fatalf("expected temperature to be available when Tctl reading present")- }- if !temp.HasCPU {- t.Fatalf("expected HasCPU to be true when AMD Tctl is present")- }- if temp.CPUPackage != 55.4 {- t.Fatalf("expected cpu package temperature 55.4, got %.2f", temp.CPUPackage)- }- if temp.CPUMax != 55.4 {- t.Fatalf("expected cpu max temperature to follow Tctl value, got %.2f", temp.CPUMax)- }-}--func TestParseSensorsJSON_RPiWrapper(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{"rpitemp-virtual":{"temp1":{"temp1_input":47.5}}}`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing wrapper output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if !temp.HasCPU {- t.Fatalf("expected HasCPU to be true for wrapper output")- }- if temp.CPUPackage != 47.5 {- t.Fatalf("expected cpu package temperature 47.5, got %.2f", temp.CPUPackage)- }- if !temp.Available {- t.Fatalf("expected temperature to be available for wrapper output")- }-}--func TestParseSensorsJSON_SMARTWithNullTemperature(t *testing.T) {- collector := &TemperatureCollector{}-- lastUpdated := time.Now().UTC().Truncate(time.Second).Format(time.RFC3339)- jsonStr := fmt.Sprintf(`{- "sensors": {- "coretemp-isa-0000": {- "Package id 0": {"temp1_input": 55.0}- }- },- "smart": [- {- "device": "/dev/sda",- "serial": "S1",- "wwn": "WWN1",- "model": "Model1",- "type": "sat",- "temperature": 34,- "lastUpdated": "%s",- "standbySkipped": false- },- {- "device": "/dev/zd0",- "temperature": null,- "standbySkipped": true- }- ]- }`, lastUpdated)-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing SMART wrapper output: %v", err)- }-- if temp == nil || !temp.Available {- t.Fatalf("expected temperature data to be available when SMART data present")- }- if !temp.HasSMART {- t.Fatalf("expected HasSMART to be true when SMART data present")- }- if len(temp.SMART) != 2 {- t.Fatalf("expected two SMART entries, got %d", len(temp.SMART))- }- if temp.SMART[0].Temperature != 34 {- t.Fatalf("expected first SMART temperature 34, got %d", temp.SMART[0].Temperature)- }- if temp.SMART[0].LastUpdated.IsZero() {- t.Fatalf("expected first SMART entry to include parsed lastUpdated timestamp")- }- if temp.SMART[1].Temperature != 0 {- t.Fatalf("expected standby SMART entry to default to temperature 0, got %d", temp.SMART[1].Temperature)- }- if !temp.SMART[1].StandbySkipped {- t.Fatalf("expected standbySkipped to be true for second SMART entry")- }-}--func TestShouldDisableProxy(t *testing.T) {- collector := &TemperatureCollector{}-- if !collector.shouldDisableProxy(fmt.Errorf("plain")) {- t.Fatalf("expected plain errors to disable proxy")- }-- transportErr := &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport}- if !collector.shouldDisableProxy(transportErr) {- t.Fatalf("expected transport errors to disable proxy")- }-- sensorErr := &tempproxy.ProxyError{Type: tempproxy.ErrorTypeSensor}- if collector.shouldDisableProxy(sensorErr) {- t.Fatalf("sensor errors should not disable proxy")- }-}--// TestParseSensorsJSON_NVMeOnly tests that NVMe-only systems don't show "No CPU sensor"-func TestParseSensorsJSON_NVMeOnly(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{- "nvme-pci-0400": {- "Composite": {"temp1_input": 42.5}- },- "nvme-pci-0500": {- "Composite": {"temp1_input": 38.0}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing sensors output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- // available should be true (any temperature data exists)- if !temp.Available {- t.Fatalf("expected temperature to be available when NVMe readings are present")- }- // hasCPU should be false (no CPU temperature data)- if temp.HasCPU {- t.Fatalf("expected HasCPU to be false when only NVMe data present")- }- // hasNVMe should be true- if !temp.HasNVMe {- t.Fatalf("expected HasNVMe to be true when NVMe data present")- }- // Verify NVMe data was parsed correctly- if len(temp.NVMe) != 2 {- t.Fatalf("expected two NVMe temperatures, got %d", len(temp.NVMe))- }- // Check that both expected temperatures are present (order may vary)- foundTemps := make(map[float64]bool)- for _, nvme := range temp.NVMe {- foundTemps[nvme.Temp] = true- }- if !foundTemps[42.5] {- t.Fatalf("expected to find NVMe temperature 42.5")- }- if !foundTemps[38.0] {- t.Fatalf("expected to find NVMe temperature 38.0")- }-}--// TestParseSensorsJSON_ZeroTemperature tests that HasCPU is true even when sensor reports 0°C-func TestParseSensorsJSON_ZeroTemperature(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{- "coretemp-isa-0000": {- "Package id 0": {"temp1_input": 0.0},- "Core 0": {"temp2_input": 0.0}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing sensors output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- // hasCPU should be true because coretemp chip was detected, even though values are 0- if !temp.HasCPU {- t.Fatalf("expected HasCPU to be true when CPU chip is detected (even with 0°C readings)")- }- // available should be true because we have a CPU sensor- if !temp.Available {- t.Fatalf("expected temperature to be available when CPU chip is detected")- }- // Values should be accepted (not filtered out)- if temp.CPUPackage != 0.0 {- t.Fatalf("expected CPUPackage to be 0.0, got %.2f", temp.CPUPackage)- }- if len(temp.Cores) != 1 {- t.Fatalf("expected one core temperature, got %d", len(temp.Cores))- }- if temp.Cores[0].Temp != 0.0 {- t.Fatalf("expected core temperature to be 0.0, got %.2f", temp.Cores[0].Temp)- }-}--func TestParseRPiTemperature(t *testing.T) {- tests := []struct {- name string- output string- wantErr bool- errContains string- wantTempC float64- }{- {- name: "empty output returns error",- output: "",- wantErr: true,- errContains: "empty RPi temperature output",- },- {- name: "whitespace-only output returns error",- output: " \t\n ",- wantErr: true,- errContains: "empty RPi temperature output",- },- {- name: "invalid non-numeric output returns error",- output: "not-a-number",- wantErr: true,- errContains: "failed to parse RPi temperature",- },- {- name: "valid millidegrees 45678 returns 45.678°C",- output: "45678",- wantErr: false,- wantTempC: 45.678,- },- {- name: "valid millidegrees with whitespace returns correct temp",- output: " 45678\n",- wantErr: false,- wantTempC: 45.678,- },- {- name: "zero value returns 0°C",- output: "0",- wantErr: false,- wantTempC: 0.0,- },- {- name: "negative value returns negative temp",- output: "-5000",- wantErr: false,- wantTempC: -5.0,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- collector := &TemperatureCollector{}- temp, err := collector.parseRPiTemperature(tt.output)-- if tt.wantErr {- if err == nil {- t.Fatalf("expected error containing %q, got nil", tt.errContains)- }- if tt.errContains != "" && !strings.Contains(err.Error(), tt.errContains) {- t.Fatalf("expected error containing %q, got %q", tt.errContains, err.Error())- }- return- }-- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if !temp.Available {- t.Errorf("expected temperature to be marked available")- }- if !temp.HasCPU {- t.Errorf("expected HasCPU to be true")- }- if diff := temp.CPUPackage - tt.wantTempC; diff > 1e-9 || diff < -1e-9 {- t.Errorf("expected CPUPackage %.3f, got %.3f", tt.wantTempC, temp.CPUPackage)- }- if temp.CPUMax != temp.CPUPackage {- t.Errorf("expected CPUMax to equal CPUPackage (%.3f), got %.3f", temp.CPUPackage, temp.CPUMax)- }- if len(temp.Cores) != 0 {- t.Errorf("expected empty Cores slice, got %d entries", len(temp.Cores))- }- if len(temp.NVMe) != 0 {- t.Errorf("expected empty NVMe slice, got %d entries", len(temp.NVMe))- }- if temp.LastUpdate.IsZero() {- t.Errorf("expected LastUpdate to be set")- }- if elapsed := time.Since(temp.LastUpdate); elapsed > 2*time.Second {- t.Errorf("expected LastUpdate to be recent, got %s", elapsed)- }- })- }-}--func TestParseSensorsJSON_PiPartialSensors(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{- "cpu_thermal-virtual-0": {- "Adapter": "Virtual device",- "temp1": {"temp1_input": 51.625}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing Pi sensors output: %v", err)- }- if !temp.Available {- t.Fatalf("expected temperature to be available when cpu_thermal sensor present")- }- if !temp.HasCPU {- t.Fatalf("expected HasCPU to be true when cpu_thermal sensor present")- }- if temp.CPUPackage != 51.625 {- t.Fatalf("expected cpu package temperature 51.625, got %.3f", temp.CPUPackage)- }- if temp.CPUMax != 51.625 {- t.Fatalf("expected cpu max temperature 51.625, got %.3f", temp.CPUMax)- }- if len(temp.Cores) != 0 {- t.Fatalf("expected no per-core temperatures, got %d entries", len(temp.Cores))- }-}--func TestParseSensorsJSON_CoretempAndRPiFallback(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{- "coretemp-isa-0000": {- "Package id 0": {"temp1_input": 65.0},- "Core 0": {"temp2_input": 63.0},- "Core 1": {"temp3_input": 62.5}- },- "cpu_thermal-virtual-0": {- "temp1": {"temp1_input": 50.0}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing mixed sensors output: %v", err)- }- if temp.CPUPackage != 65.0 {- t.Fatalf("expected cpu package temperature 65.0 from coretemp, got %.2f", temp.CPUPackage)- }- if temp.CPUMax < 63.0 {- t.Fatalf("expected cpu max to reflect hottest core (>=63.0), got %.2f", temp.CPUMax)- }- if !temp.HasCPU {- t.Fatalf("expected HasCPU to be true when CPU sensors present")- }- if !temp.Available {- t.Fatalf("expected temperature to be available when CPU sensors present")- }-}--func TestTemperatureCollector_DisablesProxyAfterFailures(t *testing.T) {- stub := &stubTemperatureProxy{- responses: []stubProxyResponse{- {err: &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "transport failure 1"}},- {err: &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "transport failure 2"}},- {err: &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "transport failure 3"}},- },- }- stub.setAvailable(true)-- collector := &TemperatureCollector{- proxyClient: stub,- useProxy: true,- }-- ctx := context.Background()- for i := 0; i < proxyFailureThreshold; i++ {- temp, err := collector.CollectTemperature(ctx, "https://node.example", "node")- if err != nil {- t.Fatalf("unexpected error on proxy failure %d: %v", i+1, err)- }- if temp.Available {- t.Fatalf("expected temperature to be unavailable after proxy failure %d", i+1)- }- }-- if collector.useProxy {- t.Fatalf("expected proxy to be disabled after %d failures", proxyFailureThreshold)- }- if collector.proxyFailures != 0 {- t.Fatalf("expected proxy failure counter to reset after disable, got %d", collector.proxyFailures)- }- if collector.proxyCooldownUntil.IsZero() {- t.Fatalf("expected proxy cooldown to be scheduled after disable")- }- if time.Until(collector.proxyCooldownUntil) <= 0 {- t.Fatalf("expected proxy cooldown to be in the future, got %s", collector.proxyCooldownUntil)- }-}--func TestTemperatureCollector_ProxyReenablesAfterCooldown(t *testing.T) {- stub := &stubTemperatureProxy{}- stub.setAvailable(true)-- collector := &TemperatureCollector{- proxyClient: stub,- useProxy: false,- proxyCooldownUntil: time.Now().Add(-time.Minute),- }-- if !collector.isProxyEnabled() {- t.Fatalf("expected proxy to re-enable when available after cooldown")- }- if !collector.useProxy {- t.Fatalf("expected useProxy to be true after proxy restored")- }- if !collector.proxyCooldownUntil.IsZero() {- t.Fatalf("expected cooldown to reset after proxy restoration, got %s", collector.proxyCooldownUntil)- }- if collector.proxyFailures != 0 {- t.Fatalf("expected proxy failure counter to reset after restoration, got %d", collector.proxyFailures)- }-}--func TestTemperatureCollector_ProxyCooldownExtendsWhenUnavailable(t *testing.T) {- stub := &stubTemperatureProxy{}- stub.setAvailable(false)-- collector := &TemperatureCollector{- proxyClient: stub,- useProxy: false,- proxyCooldownUntil: time.Now().Add(-time.Minute),- }-- before := time.Now()- if collector.isProxyEnabled() {- t.Fatalf("expected proxy to remain disabled while unavailable")- }- if collector.useProxy {- t.Fatalf("expected useProxy to remain false while proxy unavailable")- }- if !collector.proxyCooldownUntil.After(before) {- t.Fatalf("expected cooldown to be pushed into the future, got %s", collector.proxyCooldownUntil)- }-}--func TestTemperatureCollector_SuccessResetsFailureCount(t *testing.T) {- successJSON := `{"coretemp-isa-0000":{"Package id 0":{"temp1_input": 45.0}}}`- stub := &stubTemperatureProxy{- responses: []stubProxyResponse{- {err: &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "transient failure"}},- {output: successJSON},- },- }- stub.setAvailable(true)-- collector := &TemperatureCollector{- proxyClient: stub,- useProxy: true,- }-- ctx := context.Background()- if temp, err := collector.CollectTemperature(ctx, "https://node.example", "node"); err != nil {- t.Fatalf("unexpected error during proxy failure: %v", err)- } else if temp.Available {- t.Fatalf("expected unavailable temperature on proxy failure")- }- if collector.proxyFailures != 1 {- t.Fatalf("expected proxy failure counter to increment to 1, got %d", collector.proxyFailures)- }-- temp, err := collector.CollectTemperature(ctx, "https://node.example", "node")- if err != nil {- t.Fatalf("unexpected error on proxy success: %v", err)- }- if temp == nil || !temp.Available {- t.Fatalf("expected valid temperature after proxy success")- }- if collector.proxyFailures != 0 {- t.Fatalf("expected proxy failure counter reset after success, got %d", collector.proxyFailures)- }- if !collector.useProxy {- t.Fatalf("expected proxy to remain enabled after success")- }-}--func TestTemperatureCollector_ConcurrentCollectTemperature(t *testing.T) {- successJSON := `{"coretemp-isa-0000":{"Package id 0":{"temp1_input": 55.0}}}`- var callCounter int32- stub := &stubTemperatureProxy{- responseFunc: func(int) stubProxyResponse {- n := atomic.AddInt32(&callCounter, 1)- // Only fail every 5th call to avoid hitting the consecutive failure threshold (3)- // due to concurrent execution ordering. n%2 was causing flaky failures where- // 3 failures could happen before a success reset the counter.- if n%5 == 0 {- return stubProxyResponse{- err: &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "transient transport error"},- }- }- return stubProxyResponse{output: successJSON}- },- }- stub.setAvailable(true)-- collector := &TemperatureCollector{- proxyClient: stub,- useProxy: true,- }-- const goroutines = 16- const iterations = 32-- var wg sync.WaitGroup- wg.Add(goroutines)-- ctx := context.Background()- for i := 0; i < goroutines; i++ {- go func() {- defer wg.Done()- for j := 0; j < iterations; j++ {- temp, err := collector.CollectTemperature(ctx, "https://node.example", "node")- if err != nil {- t.Errorf("collect temperature returned error: %v", err)- return- }- if temp == nil {- t.Errorf("expected non-nil temperature result")- return- }- }- }()- }-- wg.Wait()-- if !collector.useProxy {- t.Fatalf("expected proxy to remain enabled during concurrent collection")- }- if collector.proxyFailures >= proxyFailureThreshold {- t.Fatalf("expected proxy failures to stay below disable threshold, got %d", collector.proxyFailures)- }-}--func TestDisableLegacySSHOnAuthFailure(t *testing.T) {- tests := []struct {- name string- err error- expected bool- }{- {- name: "nil error returns false",- err: nil,- expected: false,- },- {- name: "non-auth error connection refused returns false",- err: fmt.Errorf("connection refused"),- expected: false,- },- {- name: "non-auth error connection timed out returns false",- err: fmt.Errorf("connection timed out"),- expected: false,- },- {- name: "non-auth error network unreachable returns false",- err: fmt.Errorf("network unreachable"),- expected: false,- },- {- name: "permission denied returns true",- err: fmt.Errorf("permission denied"),- expected: true,- },- {- name: "authentication failed returns true",- err: fmt.Errorf("authentication failed"),- expected: true,- },- {- name: "publickey returns true",- err: fmt.Errorf("publickey"),- expected: true,- },- {- name: "case insensitive PERMISSION DENIED returns true",- err: fmt.Errorf("PERMISSION DENIED"),- expected: true,- },- {- name: "case insensitive Authentication Failed returns true",- err: fmt.Errorf("Authentication Failed"),- expected: true,- },- {- name: "case insensitive PUBLICKEY returns true",- err: fmt.Errorf("PUBLICKEY"),- expected: true,- },- {- name: "mixed case Permission Denied returns true",- err: fmt.Errorf("Permission Denied"),- expected: true,- },- {- name: "embedded permission denied in message returns true",- err: fmt.Errorf("ssh command failed: Permission denied (publickey)."),- expected: true,- },- {- name: "embedded authentication failed in message returns true",- err: fmt.Errorf("ssh: authentication failed: no supported methods remain"),- expected: true,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- collector := &TemperatureCollector{}- result := collector.disableLegacySSHOnAuthFailure(tt.err, "test-node", "test-host")- if result != tt.expected {- t.Errorf("disableLegacySSHOnAuthFailure() = %v, want %v", result, tt.expected)- }- })- }-}--// TestParseSensorsJSON_NCT6687SuperIO tests NCT6687 SuperIO chip detection-func TestParseSensorsJSON_NCT6687SuperIO(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{- "nct6687-isa-0a20": {- "CPUTIN": {"temp1_input": 48.5},- "SYSTIN": {"temp2_input": 35.0}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing NCT6687 sensors output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if !temp.Available {- t.Fatalf("expected temperature to be available when NCT6687 CPUTIN is present")- }- if !temp.HasCPU {- t.Fatalf("expected HasCPU to be true when NCT6687 chip is detected")- }- if temp.CPUPackage != 48.5 {- t.Fatalf("expected cpu package temperature 48.5 from CPUTIN, got %.2f", temp.CPUPackage)- }-}--// TestParseSensorsJSON_AmdChipletTemps tests AMD Tccd chiplet temperature detection-func TestParseSensorsJSON_AmdChipletTemps(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{- "k10temp-pci-00c3": {- "Tccd1": {"temp3_input": 62.5},- "Tccd2": {"temp4_input": 58.0}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing AMD chiplet sensors output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if !temp.Available {- t.Fatalf("expected temperature to be available when AMD chiplet temps are present")- }- if !temp.HasCPU {- t.Fatalf("expected HasCPU to be true when K10temp chip is detected")- }- // Should use highest chiplet temp as package temp- if temp.CPUPackage != 62.5 {- t.Fatalf("expected cpu package temperature to be highest chiplet temp (62.5), got %.2f", temp.CPUPackage)- }- // CPUMax should also be 62.5- if temp.CPUMax != 62.5 {- t.Fatalf("expected cpu max temperature 62.5, got %.2f", temp.CPUMax)- }-}--// TestParseSensorsJSON_AmdTctlAndChiplets tests AMD with both Tctl and chiplet temps-func TestParseSensorsJSON_AmdTctlAndChiplets(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{- "k10temp-pci-00c3": {- "Tctl": {"temp1_input": 65.0},- "Tccd1": {"temp3_input": 62.5},- "Tccd2": {"temp4_input": 58.0}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing AMD full sensors output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if !temp.Available {- t.Fatalf("expected temperature to be available")- }- if !temp.HasCPU {- t.Fatalf("expected HasCPU to be true")- }- // Tctl should take precedence over chiplet temps for package temperature- if temp.CPUPackage != 65.0 {- t.Fatalf("expected cpu package temperature from Tctl (65.0), got %.2f", temp.CPUPackage)- }- // CPUMax should be Tctl since it's highest- if temp.CPUMax != 65.0 {- t.Fatalf("expected cpu max temperature 65.0, got %.2f", temp.CPUMax)- }-}--// TestParseSensorsJSON_MultipleSuperioCPUFields tests SuperIO chips with multiple CPU temp fields-func TestParseSensorsJSON_MultipleSuperioCPUFields(t *testing.T) {- collector := &TemperatureCollector{}-- jsonStr := `{- "nct6775-isa-0290": {- "CPU Temperature": {"temp1_input": 52.0},- "SYSTIN": {"temp2_input": 38.0},- "AUXTIN0": {"temp3_input": 40.0}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing NCT6775 sensors output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if !temp.Available {- t.Fatalf("expected temperature to be available")- }- if !temp.HasCPU {- t.Fatalf("expected HasCPU to be true")- }- if temp.CPUPackage != 52.0 {- t.Fatalf("expected cpu package temperature from 'CPU Temperature' field (52.0), got %.2f", temp.CPUPackage)- }-}--// TestParseSensorsJSON_CoreTempExceedsPackage tests that CPUMax is updated when a core temp exceeds package temp-func TestParseSensorsJSON_CoreTempExceedsPackage(t *testing.T) {- collector := &TemperatureCollector{}-- // Core 1 has a higher temp than Package id 0- jsonStr := `{- "coretemp-isa-0000": {- "Package id 0": {"temp1_input": 45.0},- "Core 0": {"temp2_input": 42.0},- "Core 1": {"temp3_input": 52.0}- }- }`-- temp, err := collector.parseSensorsJSON(jsonStr)- if err != nil {- t.Fatalf("unexpected error parsing sensors output: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if !temp.Available {- t.Fatalf("expected temperature to be available")- }- if temp.CPUPackage != 45.0 {- t.Fatalf("expected cpu package temperature 45.0, got %.2f", temp.CPUPackage)- }- // CPUMax should be the highest core temp (52.0), not the package temp (45.0)- if temp.CPUMax != 52.0 {- t.Fatalf("expected cpu max temperature to be highest core temp (52.0), got %.2f", temp.CPUMax)- }- if len(temp.Cores) != 2 {- t.Fatalf("expected two core temperatures, got %d", len(temp.Cores))- }-}--// =============================================================================-// Unit tests for utility functions-// =============================================================================--func TestExtractTempInput(t *testing.T) {- tests := []struct {- name string- sensorMap map[string]interface{}- wantTemp float64- wantNaN bool- }{- {- name: "float64 temp1_input",- sensorMap: map[string]interface{}{- "temp1_input": 45.5,- },- wantTemp: 45.5,- },- {- name: "float64 temp2_input",- sensorMap: map[string]interface{}{- "temp2_input": 72.3,- },- wantTemp: 72.3,- },- {- name: "int value converted to float64",- sensorMap: map[string]interface{}{- "temp1_input": 55,- },- wantTemp: 55.0,- },- {- name: "string value parseable",- sensorMap: map[string]interface{}{- "temp1_input": "62.5",- },- wantTemp: 62.5,- },- {- name: "string value non-numeric",- sensorMap: map[string]interface{}{- "temp1_input": "N/A",- },- wantNaN: true,- },- {- name: "no _input suffix",- sensorMap: map[string]interface{}{- "temp1": 45.5,- "temp1_max": 100.0,- },- wantNaN: true,- },- {- name: "empty map",- sensorMap: map[string]interface{}{},- wantNaN: true,- },- {- name: "nil map",- sensorMap: nil,- wantNaN: true,- },- {- name: "zero temperature",- sensorMap: map[string]interface{}{- "temp1_input": 0.0,- },- wantTemp: 0.0,- },- {- name: "negative temperature",- sensorMap: map[string]interface{}{- "temp1_input": -10.5,- },- wantTemp: -10.5,- },- {- name: "mixed valid and invalid fields",- sensorMap: map[string]interface{}{- "temp1": 45.0,- "temp1_input": 50.0,- "temp1_max": 100.0,- },- wantTemp: 50.0,- },- {- name: "boolean value (invalid type)",- sensorMap: map[string]interface{}{- "temp1_input": true,- },- wantNaN: true,- },- {- name: "nil value",- sensorMap: map[string]interface{}{- "temp1_input": nil,- },- wantNaN: true,- },- {- name: "very high temperature",- sensorMap: map[string]interface{}{- "temp1_input": 125.5,- },- wantTemp: 125.5,- },- {- name: "fractional precision",- sensorMap: map[string]interface{}{- "temp1_input": 45.123456789,- },- wantTemp: 45.123456789,- },- {- name: "temp_crit_input also matches",- sensorMap: map[string]interface{}{- "temp1_crit_input": 95.0,- },- wantTemp: 95.0,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := extractTempInput(tt.sensorMap)-- if tt.wantNaN {- if !math.IsNaN(got) {- t.Errorf("extractTempInput() = %v, want NaN", got)- }- return- }-- if got != tt.wantTemp {- t.Errorf("extractTempInput() = %v, want %v", got, tt.wantTemp)- }- })- }-}--func TestExtractCoreNumber(t *testing.T) {- tests := []struct {- name string- want int- }{- {"Core 0", 0},- {"Core 1", 1},- {"Core 10", 10},- {"Core 99", 99},- {"Core 127", 127},- {"Core", 0}, // missing number- {"Core ", 0}, // trailing space, no number- {"core 5", 5}, // lowercase- {"CORE 7", 7}, // uppercase- {"Core 12", 12}, // extra space (Fields handles this)- {"", 0}, // empty string- {" ", 0}, // whitespace only- {"Core abc", 0}, // non-numeric- {"Package id 0", 0}, // last part is "0"- {"temp1", 0}, // no spaces- {"Core 1000", 1000}, // large core number- {"Prefix Core 5", 5}, // core not at start- {"Core 0 extra", 0}, // text after number - "extra" is last field- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := extractCoreNumber(tt.name)- if got != tt.want {- t.Errorf("extractCoreNumber(%q) = %v, want %v", tt.name, got, tt.want)- }- })- }-}--func TestExtractHostname(t *testing.T) {- tests := []struct {- name string- hostURL string- want string- }{- {- name: "https with port",- hostURL: "https://192.168.1.100:8006",- want: "192.168.1.100",- },- {- name: "https without port",- hostURL: "https://192.168.1.100",- want: "192.168.1.100",- },- {- name: "http with port",- hostURL: "http://192.168.1.100:8006",- want: "192.168.1.100",- },- {- name: "http without port",- hostURL: "http://192.168.1.100",- want: "192.168.1.100",- },- {- name: "hostname with port",- hostURL: "https://proxmox.local:8006",- want: "proxmox.local",- },- {- name: "hostname without port",- hostURL: "https://proxmox.local",- want: "proxmox.local",- },- {- name: "bare IP",- hostURL: "192.168.1.100",- want: "192.168.1.100",- },- {- name: "bare IP with port",- hostURL: "192.168.1.100:8006",- want: "192.168.1.100",- },- {- name: "bare hostname",- hostURL: "proxmox.local",- want: "proxmox.local",- },- {- name: "bare hostname with port",- hostURL: "proxmox.local:8006",- want: "proxmox.local",- },- {- name: "with path",- hostURL: "https://192.168.1.100:8006/api2/json",- want: "192.168.1.100",- },- {- name: "empty string",- hostURL: "",- want: "",- },- {- name: "protocol only",- hostURL: "https://",- want: "",- },- {- name: "FQDN",- hostURL: "https://pve1.example.com:8006",- want: "pve1.example.com",- },- {- name: "localhost",- hostURL: "http://localhost:8006",- want: "localhost",- },- {- name: "127.0.0.1",- hostURL: "https://127.0.0.1:8006",- want: "127.0.0.1",- },- {- name: "uppercase protocol not stripped",- hostURL: "HTTPS://192.168.1.100:8006",- want: "HTTPS", // TrimPrefix is case-sensitive, so "HTTPS:" becomes hostname part- },- {- name: "trailing slash",- hostURL: "https://192.168.1.100/",- want: "192.168.1.100",- },- {- name: "query string",- hostURL: "https://192.168.1.100:8006/api?key=value",- want: "192.168.1.100",- },- {- name: "double protocol",- hostURL: "https://https://192.168.1.100",- want: "https",- },- {- name: "port only",- hostURL: ":8006",- want: "",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := extractHostname(tt.hostURL)- if got != tt.want {- t.Errorf("extractHostname(%q) = %q, want %q", tt.hostURL, got, tt.want)- }- })- }-}--func TestNormalizeSMARTEntries(t *testing.T) {- tests := []struct {- name string- raw []smartEntryRaw- want []models.DiskTemp- }{- {- name: "nil input",- raw: nil,- want: nil,- },- {- name: "empty slice",- raw: []smartEntryRaw{},- want: nil,- },- {- name: "single entry with all fields",- raw: []smartEntryRaw{- {- Device: "/dev/sda",- Serial: "WD-WMC1T0123456",- WWN: "5 0014ee 2b1234567",- Model: "WDC WD40EFRX-68N32N0",- Type: "sata",- Temperature: intPtr(38),- LastUpdated: "2024-01-15T10:30:00Z",- StandbySkipped: false,- },- },- want: []models.DiskTemp{- {- Device: "/dev/sda",- Serial: "WD-WMC1T0123456",- WWN: "5 0014ee 2b1234567",- Model: "WDC WD40EFRX-68N32N0",- Type: "sata",- Temperature: 38,- LastUpdated: mustParseTime("2024-01-15T10:30:00Z"),- StandbySkipped: false,- },- },- },- {- name: "entry with nil temperature",- raw: []smartEntryRaw{- {- Device: "/dev/sdb",- Temperature: nil,- },- },- want: []models.DiskTemp{- {- Device: "/dev/sdb",- Temperature: 0, // nil becomes 0- },- },- },- {- name: "entry with standby skipped",- raw: []smartEntryRaw{- {- Device: "/dev/sdc",- StandbySkipped: true,- Temperature: nil,- },- },- want: []models.DiskTemp{- {- Device: "/dev/sdc",- StandbySkipped: true,- Temperature: 0,- },- },- },- {- name: "empty device skipped",- raw: []smartEntryRaw{- {- Device: "",- Temperature: intPtr(40),- },- },- want: []models.DiskTemp{},- },- {- name: "whitespace-only device skipped",- raw: []smartEntryRaw{- {- Device: " ",- Temperature: intPtr(40),- },- },- want: []models.DiskTemp{},- },- {- name: "invalid timestamp ignored",- raw: []smartEntryRaw{- {- Device: "/dev/sda",- LastUpdated: "not-a-timestamp",- Temperature: intPtr(42),- },- },- want: []models.DiskTemp{- {- Device: "/dev/sda",- Temperature: 42,- LastUpdated: time.Time{}, // zero time- },- },- },- {- name: "empty timestamp",- raw: []smartEntryRaw{- {- Device: "/dev/sda",- LastUpdated: "",- Temperature: intPtr(42),- },- },- want: []models.DiskTemp{- {- Device: "/dev/sda",- Temperature: 42,- LastUpdated: time.Time{},- },- },- },- {- name: "multiple entries",- raw: []smartEntryRaw{- {Device: "/dev/sda", Temperature: intPtr(38), Type: "sata"},- {Device: "/dev/sdb", Temperature: intPtr(40), Type: "sata"},- {Device: "/dev/nvme0n1", Temperature: intPtr(45), Type: "nvme"},- },- want: []models.DiskTemp{- {Device: "/dev/sda", Temperature: 38, Type: "sata"},- {Device: "/dev/sdb", Temperature: 40, Type: "sata"},- {Device: "/dev/nvme0n1", Temperature: 45, Type: "nvme"},- },- },- {- name: "whitespace trimmed from fields",- raw: []smartEntryRaw{- {- Device: " /dev/sda ",- Serial: " ABC123 ",- WWN: " 1234 ",- Model: " Model X ",- Type: " sata ",- },- },- want: []models.DiskTemp{- {- Device: "/dev/sda",- Serial: "ABC123",- WWN: "1234",- Model: "Model X",- Type: "sata",- },- },- },- {- name: "mixed valid and empty devices",- raw: []smartEntryRaw{- {Device: "/dev/sda", Temperature: intPtr(38)},- {Device: "", Temperature: intPtr(40)},- {Device: "/dev/sdc", Temperature: intPtr(42)},- },- want: []models.DiskTemp{- {Device: "/dev/sda", Temperature: 38},- {Device: "/dev/sdc", Temperature: 42},- },- },- {- name: "zero temperature",- raw: []smartEntryRaw{- {Device: "/dev/sda", Temperature: intPtr(0)},- },- want: []models.DiskTemp{- {Device: "/dev/sda", Temperature: 0},- },- },- {- name: "negative temperature",- raw: []smartEntryRaw{- {Device: "/dev/sda", Temperature: intPtr(-10)},- },- want: []models.DiskTemp{- {Device: "/dev/sda", Temperature: -10},- },- },- {- name: "high temperature",- raw: []smartEntryRaw{- {Device: "/dev/sda", Temperature: intPtr(85)},- },- want: []models.DiskTemp{- {Device: "/dev/sda", Temperature: 85},- },- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := normalizeSMARTEntries(tt.raw)-- if tt.want == nil {- if got != nil {- t.Errorf("normalizeSMARTEntries() = %v, want nil", got)- }- return- }-- if len(got) != len(tt.want) {- t.Fatalf("normalizeSMARTEntries() returned %d entries, want %d", len(got), len(tt.want))- }-- for i := range got {- if got[i].Device != tt.want[i].Device {- t.Errorf("entry[%d].Device = %q, want %q", i, got[i].Device, tt.want[i].Device)- }- if got[i].Serial != tt.want[i].Serial {- t.Errorf("entry[%d].Serial = %q, want %q", i, got[i].Serial, tt.want[i].Serial)- }- if got[i].WWN != tt.want[i].WWN {- t.Errorf("entry[%d].WWN = %q, want %q", i, got[i].WWN, tt.want[i].WWN)- }- if got[i].Model != tt.want[i].Model {- t.Errorf("entry[%d].Model = %q, want %q", i, got[i].Model, tt.want[i].Model)- }- if got[i].Type != tt.want[i].Type {- t.Errorf("entry[%d].Type = %q, want %q", i, got[i].Type, tt.want[i].Type)- }- if got[i].Temperature != tt.want[i].Temperature {- t.Errorf("entry[%d].Temperature = %d, want %d", i, got[i].Temperature, tt.want[i].Temperature)- }- if !got[i].LastUpdated.Equal(tt.want[i].LastUpdated) {- t.Errorf("entry[%d].LastUpdated = %v, want %v", i, got[i].LastUpdated, tt.want[i].LastUpdated)- }- if got[i].StandbySkipped != tt.want[i].StandbySkipped {- t.Errorf("entry[%d].StandbySkipped = %v, want %v", i, got[i].StandbySkipped, tt.want[i].StandbySkipped)- }- }- })- }-}--// =============================================================================-// Tests for shouldSkipProxyHost-// =============================================================================--func TestShouldSkipProxyHost_EmptyHost(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: make(map[string]*proxyHostState),- }-- if tc.shouldSkipProxyHost("") {- t.Error("expected empty host to return false")- }-}--func TestShouldSkipProxyHost_WhitespaceOnlyHost(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: make(map[string]*proxyHostState),- }-- if tc.shouldSkipProxyHost(" ") {- t.Error("expected whitespace-only host (trimmed to empty) to return false")- }- if tc.shouldSkipProxyHost("\t\n") {- t.Error("expected tab/newline host (trimmed to empty) to return false")- }-}--func TestShouldSkipProxyHost_NotInMap(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: make(map[string]*proxyHostState),- }-- if tc.shouldSkipProxyHost("192.168.1.100") {- t.Error("expected host not in map to return false")- }-}--func TestShouldSkipProxyHost_NilState(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": nil,- },- }-- if tc.shouldSkipProxyHost("192.168.1.100") {- t.Error("expected host with nil state to return false")- }-}--func TestShouldSkipProxyHost_ZeroCooldownUntil(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {- failures: 2,- cooldownUntil: time.Time{}, // zero value- },- },- }-- if tc.shouldSkipProxyHost("192.168.1.100") {- t.Error("expected host with zero cooldownUntil to return false")- }-- // Verify the host was cleaned up from the map- tc.proxyMu.Lock()- _, exists := tc.proxyHostStates["192.168.1.100"]- tc.proxyMu.Unlock()-- if exists {- t.Error("expected host with zero cooldownUntil to be deleted from map")- }-}--func TestShouldSkipProxyHost_ExpiredCooldown(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {- failures: 2,- cooldownUntil: time.Now().Add(-time.Minute), // expired- lastError: "some error",- },- },- }-- if tc.shouldSkipProxyHost("192.168.1.100") {- t.Error("expected host with expired cooldown to return false")- }-- // Verify the state was reset and host was deleted- tc.proxyMu.Lock()- _, exists := tc.proxyHostStates["192.168.1.100"]- tc.proxyMu.Unlock()-- if exists {- t.Error("expected host with expired cooldown to be deleted from map")- }-}--func TestShouldSkipProxyHost_ActiveCooldown(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {- failures: 0,- cooldownUntil: time.Now().Add(5 * time.Minute), // active- lastError: "connection refused",- },- },- }-- if !tc.shouldSkipProxyHost("192.168.1.100") {- t.Error("expected host with active cooldown to return true")- }-- // Verify the host is still in the map- tc.proxyMu.Lock()- state, exists := tc.proxyHostStates["192.168.1.100"]- tc.proxyMu.Unlock()-- if !exists {- t.Error("expected host with active cooldown to remain in map")- }- if state.lastError != "connection refused" {- t.Errorf("expected lastError to be preserved, got %q", state.lastError)- }-}--func TestShouldSkipProxyHost_ExpiredCooldownResetsState(t *testing.T) {- initialState := &proxyHostState{- failures: 5,- cooldownUntil: time.Now().Add(-time.Second), // just expired- lastError: "previous error",- }- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": initialState,- },- }-- // This call should reset the state and delete the host- result := tc.shouldSkipProxyHost("192.168.1.100")- if result {- t.Error("expected expired cooldown to return false")- }-- // After the call, the host should be deleted from the map- tc.proxyMu.Lock()- _, exists := tc.proxyHostStates["192.168.1.100"]- tc.proxyMu.Unlock()-- if exists {- t.Error("expected host to be deleted after cooldown expired")- }-}--func TestShouldSkipProxyHost_TrimsWhitespace(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {- cooldownUntil: time.Now().Add(5 * time.Minute),- },- },- }-- // Host with leading/trailing whitespace should match after trimming- if !tc.shouldSkipProxyHost(" 192.168.1.100 ") {- t.Error("expected trimmed host to match entry in map")- }-}--// =============================================================================-// Tests for handleProxySuccess-// =============================================================================--func TestHandleProxySuccess_NilProxyClient(t *testing.T) {- tc := &TemperatureCollector{- proxyClient: nil,- proxyFailures: 5, // should remain unchanged- }-- tc.handleProxySuccess()-- if tc.proxyFailures != 5 {- t.Errorf("expected proxyFailures to remain 5 when proxyClient is nil, got %d", tc.proxyFailures)- }-}--func TestHandleProxySuccess_ResetsFailures(t *testing.T) {- stub := &stubTemperatureProxy{}-- tc := &TemperatureCollector{- proxyClient: stub,- proxyFailures: 3,- }-- tc.handleProxySuccess()-- if tc.proxyFailures != 0 {- t.Errorf("expected proxyFailures to be reset to 0, got %d", tc.proxyFailures)- }-}--func TestHandleProxySuccess_AlreadyZeroFailures(t *testing.T) {- stub := &stubTemperatureProxy{}-- tc := &TemperatureCollector{- proxyClient: stub,- proxyFailures: 0,- }-- tc.handleProxySuccess()-- if tc.proxyFailures != 0 {- t.Errorf("expected proxyFailures to remain 0, got %d", tc.proxyFailures)- }-}--// =============================================================================-// Tests for handleProxyHostSuccess-// =============================================================================--func TestHandleProxyHostSuccess_EmptyHost(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {failures: 2, cooldownUntil: time.Now().Add(time.Minute)},- },- }-- tc.handleProxyHostSuccess("")-- // Map should be unchanged- tc.proxyMu.Lock()- if len(tc.proxyHostStates) != 1 {- t.Errorf("expected map to have 1 entry, got %d", len(tc.proxyHostStates))- }- tc.proxyMu.Unlock()-}--func TestHandleProxyHostSuccess_WhitespaceOnlyHost(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {failures: 2, cooldownUntil: time.Now().Add(time.Minute)},- },- }-- tc.handleProxyHostSuccess(" ")-- // Map should be unchanged- tc.proxyMu.Lock()- if len(tc.proxyHostStates) != 1 {- t.Errorf("expected map to have 1 entry, got %d", len(tc.proxyHostStates))- }- tc.proxyMu.Unlock()-}--func TestHandleProxyHostSuccess_RemovesHostFromMap(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {failures: 5, cooldownUntil: time.Now().Add(time.Minute)},- "192.168.1.101": {failures: 3, cooldownUntil: time.Now().Add(time.Minute)},- },- }-- tc.handleProxyHostSuccess("192.168.1.100")-- tc.proxyMu.Lock()- defer tc.proxyMu.Unlock()-- if _, exists := tc.proxyHostStates["192.168.1.100"]; exists {- t.Error("expected host 192.168.1.100 to be removed from map")- }- if _, exists := tc.proxyHostStates["192.168.1.101"]; !exists {- t.Error("expected host 192.168.1.101 to remain in map")- }-}--func TestHandleProxyHostSuccess_HostNotInMap(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {failures: 2},- },- }-- // Should not panic when host doesn't exist- tc.handleProxyHostSuccess("192.168.1.200")-- tc.proxyMu.Lock()- if len(tc.proxyHostStates) != 1 {- t.Errorf("expected map to have 1 entry, got %d", len(tc.proxyHostStates))- }- tc.proxyMu.Unlock()-}--func TestHandleProxyHostSuccess_TrimsWhitespace(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {failures: 5, cooldownUntil: time.Now().Add(time.Minute)},- },- }-- tc.handleProxyHostSuccess(" 192.168.1.100 ")-- tc.proxyMu.Lock()- defer tc.proxyMu.Unlock()-- if _, exists := tc.proxyHostStates["192.168.1.100"]; exists {- t.Error("expected host to be removed after trimming whitespace from input")- }-}--func TestHandleProxyHostSuccess_NilMap(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: nil,- }-- // Should not panic with nil map- tc.handleProxyHostSuccess("192.168.1.100")-}--// =============================================================================-// Tests for parseNVMeTemps-// =============================================================================--func TestParseNVMeTemps(t *testing.T) {- tests := []struct {- name string- chipName string- chipMap map[string]interface{}- wantNVMe []models.NVMeTemp- wantDevice string- }{- {- name: "empty chipMap does nothing",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{},- wantNVMe: nil,- },- {- name: "sensorData is not a map (skipped)",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Composite": "not a map",- "Sensor 1": 12345,- },- wantNVMe: nil,- },- {- name: "sensor name doesn't contain Composite or Sensor 1 (skipped)",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Temperature": map[string]interface{}{- "temp1_input": 42.5,- },- "Sensor 2": map[string]interface{}{- "temp1_input": 38.0,- },- },- wantNVMe: nil,- },- {- name: "Composite with valid temp_input is added",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Composite": map[string]interface{}{- "temp1_input": 42.5,- },- },- wantNVMe: []models.NVMeTemp{- {Device: "nvme0400", Temp: 42.5},- },- },- {- name: "Sensor 1 with valid temp_input is added",- chipName: "nvme-pci-0500",- chipMap: map[string]interface{}{- "Sensor 1": map[string]interface{}{- "temp1_input": 38.75,- },- },- wantNVMe: []models.NVMeTemp{- {Device: "nvme0500", Temp: 38.75},- },- },- {- name: "invalid/NaN temp value is skipped",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Composite": map[string]interface{}{- "temp1_input": "not-a-number",- },- },- wantNVMe: nil,- },- {- name: "zero temp value is skipped",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Composite": map[string]interface{}{- "temp1_input": 0.0,- },- },- wantNVMe: nil,- },- {- name: "negative temp value is skipped",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Composite": map[string]interface{}{- "temp1_input": -5.0,- },- },- wantNVMe: nil,- },- {- name: "device name extraction from chip name works correctly",- chipName: "nvme-pci-0100",- chipMap: map[string]interface{}{- "Composite": map[string]interface{}{- "temp1_input": 35.0,- },- },- wantNVMe: []models.NVMeTemp{- {Device: "nvme0100", Temp: 35.0},- },- },- {- name: "only first valid sensor is used (Composite before Sensor 1)",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Composite": map[string]interface{}{- "temp1_input": 40.0,- },- "Sensor 1": map[string]interface{}{- "temp1_input": 45.0,- },- },- wantNVMe: []models.NVMeTemp{- {Device: "nvme0400", Temp: 40.0},- },- },- {- name: "Composite substring match (e.g., 'Composite temp')",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Composite temp": map[string]interface{}{- "temp1_input": 41.0,- },- },- wantNVMe: []models.NVMeTemp{- {Device: "nvme0400", Temp: 41.0},- },- },- {- name: "Sensor 1 substring match (e.g., 'Sensor 1 temp')",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Sensor 1 temp": map[string]interface{}{- "temp1_input": 39.0,- },- },- wantNVMe: []models.NVMeTemp{- {Device: "nvme0400", Temp: 39.0},- },- },- {- name: "nil sensorData is skipped",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Composite": nil,- },- wantNVMe: nil,- },- {- name: "temp2_input also works",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Composite": map[string]interface{}{- "temp2_input": 44.0,- },- },- wantNVMe: []models.NVMeTemp{- {Device: "nvme0400", Temp: 44.0},- },- },- {- name: "skips invalid Composite and uses valid Sensor 1",- chipName: "nvme-pci-0400",- chipMap: map[string]interface{}{- "Composite": map[string]interface{}{- "temp1_input": 0.0, // invalid (zero)- },- "Sensor 1": map[string]interface{}{- "temp1_input": 42.0,- },- },- wantNVMe: []models.NVMeTemp{- {Device: "nvme0400", Temp: 42.0},- },- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- collector.parseNVMeTemps(tt.chipName, tt.chipMap, temp)-- if tt.wantNVMe == nil {- if len(temp.NVMe) != 0 {- t.Errorf("parseNVMeTemps() added %d NVMe entries, want 0", len(temp.NVMe))- }- return- }-- if len(temp.NVMe) != len(tt.wantNVMe) {- t.Fatalf("parseNVMeTemps() added %d NVMe entries, want %d", len(temp.NVMe), len(tt.wantNVMe))- }-- for i, want := range tt.wantNVMe {- got := temp.NVMe[i]- if got.Device != want.Device {- t.Errorf("NVMe[%d].Device = %q, want %q", i, got.Device, want.Device)- }- if got.Temp != want.Temp {- t.Errorf("NVMe[%d].Temp = %v, want %v", i, got.Temp, want.Temp)- }- }- })- }-}--func TestParseNVMeTemps_AppendsToExisting(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{- NVMe: []models.NVMeTemp{- {Device: "nvme0300", Temp: 30.0},- },- }-- chipMap := map[string]interface{}{- "Composite": map[string]interface{}{- "temp1_input": 42.5,- },- }-- collector.parseNVMeTemps("nvme-pci-0400", chipMap, temp)-- if len(temp.NVMe) != 2 {- t.Fatalf("expected 2 NVMe entries after append, got %d", len(temp.NVMe))- }-- if temp.NVMe[0].Device != "nvme0300" || temp.NVMe[0].Temp != 30.0 {- t.Errorf("first NVMe entry was modified: got %+v", temp.NVMe[0])- }-- if temp.NVMe[1].Device != "nvme0400" || temp.NVMe[1].Temp != 42.5 {- t.Errorf("second NVMe entry incorrect: got %+v", temp.NVMe[1])- }-}--// =============================================================================-// Tests for isProxyEnabled-// =============================================================================--func TestIsProxyEnabled_NilProxyClient(t *testing.T) {- tc := &TemperatureCollector{- proxyClient: nil,- useProxy: true, // even if this is true, nil client should return false- }-- if tc.isProxyEnabled() {- t.Error("expected isProxyEnabled() to return false when proxyClient is nil")- }-}--func TestIsProxyEnabled_UseProxyAlreadyTrue(t *testing.T) {- stub := &stubTemperatureProxy{}- stub.setAvailable(false) // shouldn't matter since useProxy is already true-- tc := &TemperatureCollector{- proxyClient: stub,- useProxy: true,- }-- if !tc.isProxyEnabled() {- t.Error("expected isProxyEnabled() to return true when useProxy is already true")- }-- // Verify useProxy remains true (unchanged)- if !tc.useProxy {- t.Error("expected useProxy to remain true")- }-}--func TestIsProxyEnabled_UseProxyFalseStillInCooldown(t *testing.T) {- stub := &stubTemperatureProxy{}- stub.setAvailable(true) // shouldn't be checked since still in cooldown-- cooldownTime := time.Now().Add(5 * time.Minute)- tc := &TemperatureCollector{- proxyClient: stub,- useProxy: false,- proxyCooldownUntil: cooldownTime,- proxyFailures: 2,- }-- if tc.isProxyEnabled() {- t.Error("expected isProxyEnabled() to return false while in cooldown")- }-- // Verify state is unchanged- if tc.useProxy {- t.Error("expected useProxy to remain false during cooldown")- }- if tc.proxyFailures != 2 {- t.Errorf("expected proxyFailures to remain 2, got %d", tc.proxyFailures)- }- if !tc.proxyCooldownUntil.Equal(cooldownTime) {- t.Errorf("expected proxyCooldownUntil to remain unchanged")- }-}--func TestIsProxyEnabled_CooldownExpiredProxyAvailable(t *testing.T) {- stub := &stubTemperatureProxy{}- stub.setAvailable(true)-- tc := &TemperatureCollector{- proxyClient: stub,- useProxy: false,- proxyCooldownUntil: time.Now().Add(-time.Minute), // expired- proxyFailures: 2,- }-- if !tc.isProxyEnabled() {- t.Error("expected isProxyEnabled() to return true when cooldown expired and proxy available")- }-- // Verify state was restored- if !tc.useProxy {- t.Error("expected useProxy to be set to true after restoration")- }- if tc.proxyFailures != 0 {- t.Errorf("expected proxyFailures to be reset to 0, got %d", tc.proxyFailures)- }- if !tc.proxyCooldownUntil.IsZero() {- t.Errorf("expected proxyCooldownUntil to be zero after restoration, got %s", tc.proxyCooldownUntil)- }-}--func TestIsProxyEnabled_CooldownExpiredProxyUnavailable(t *testing.T) {- stub := &stubTemperatureProxy{}- stub.setAvailable(false)-- expiredCooldown := time.Now().Add(-time.Minute)- tc := &TemperatureCollector{- proxyClient: stub,- useProxy: false,- proxyCooldownUntil: expiredCooldown,- proxyFailures: 2,- }-- before := time.Now()- if tc.isProxyEnabled() {- t.Error("expected isProxyEnabled() to return false when proxy unavailable")- }-- // Verify state- if tc.useProxy {- t.Error("expected useProxy to remain false when proxy unavailable")- }- // Cooldown should be extended by proxyRetryInterval (5 minutes)- if !tc.proxyCooldownUntil.After(before) {- t.Errorf("expected proxyCooldownUntil to be extended into the future, got %s", tc.proxyCooldownUntil)- }- expectedMinCooldown := before.Add(proxyRetryInterval - time.Second)- if tc.proxyCooldownUntil.Before(expectedMinCooldown) {- t.Errorf("expected proxyCooldownUntil to be at least %s, got %s", expectedMinCooldown, tc.proxyCooldownUntil)- }-}--func TestIsProxyEnabled_ZeroCooldownProxyAvailable(t *testing.T) {- stub := &stubTemperatureProxy{}- stub.setAvailable(true)-- tc := &TemperatureCollector{- proxyClient: stub,- useProxy: false,- proxyCooldownUntil: time.Time{}, // zero value - time.Now().After(zero) is true- proxyFailures: 0,- }-- if !tc.isProxyEnabled() {- t.Error("expected isProxyEnabled() to return true with zero cooldown and available proxy")- }-- if !tc.useProxy {- t.Error("expected useProxy to be set to true")- }-}--func TestIsProxyEnabled_ZeroCooldownProxyUnavailable(t *testing.T) {- stub := &stubTemperatureProxy{}- stub.setAvailable(false)-- tc := &TemperatureCollector{- proxyClient: stub,- useProxy: false,- proxyCooldownUntil: time.Time{}, // zero value- }-- before := time.Now()- if tc.isProxyEnabled() {- t.Error("expected isProxyEnabled() to return false when proxy unavailable")- }-- // Should set a new cooldown since proxy is unavailable- if !tc.proxyCooldownUntil.After(before) {- t.Errorf("expected proxyCooldownUntil to be set in the future, got %s", tc.proxyCooldownUntil)- }-}--// =============================================================================-// Tests for handleProxyFailure-// =============================================================================--func TestHandleProxyFailure_NilProxyClient(t *testing.T) {- tc := &TemperatureCollector{- proxyClient: nil,- proxyFailures: 2,- proxyHostStates: make(map[string]*proxyHostState),- }-- // Should return early without panic- tc.handleProxyFailure("192.168.1.100", fmt.Errorf("some error"))-- // State should remain unchanged- if tc.proxyFailures != 2 {- t.Errorf("expected proxyFailures to remain 2, got %d", tc.proxyFailures)- }- if len(tc.proxyHostStates) != 0 {- t.Errorf("expected proxyHostStates to remain empty, got %d entries", len(tc.proxyHostStates))- }-}--func TestHandleProxyFailure_ShouldDisableProxyFalse_CallsHandleProxyHostFailure(t *testing.T) {- stub := &stubTemperatureProxy{}-- tc := &TemperatureCollector{- proxyClient: stub,- proxyFailures: 0,- useProxy: true,- proxyHostStates: make(map[string]*proxyHostState),- }-- // ErrorTypeSensor does NOT trigger shouldDisableProxy (returns false)- sensorErr := &tempproxy.ProxyError{Type: tempproxy.ErrorTypeSensor, Message: "sensor not found"}- tc.handleProxyFailure("192.168.1.100", sensorErr)-- // proxyFailures should NOT be incremented (that's for global disable path)- if tc.proxyFailures != 0 {- t.Errorf("expected proxyFailures to remain 0, got %d", tc.proxyFailures)- }-- // handleProxyHostFailure should have been called - check host state- tc.proxyMu.Lock()- state, exists := tc.proxyHostStates["192.168.1.100"]- tc.proxyMu.Unlock()-- if !exists {- t.Fatal("expected host to be added to proxyHostStates")- }- if state.failures != 1 {- t.Errorf("expected host failures to be 1, got %d", state.failures)- }- if state.lastError != "sensor not found" {- t.Errorf("expected lastError to be 'sensor not found', got %q", state.lastError)- }-}--func TestHandleProxyFailure_ShouldDisableProxyTrue_IncrementsFailures(t *testing.T) {- stub := &stubTemperatureProxy{}-- tc := &TemperatureCollector{- proxyClient: stub,- proxyFailures: 0,- useProxy: true,- proxyHostStates: make(map[string]*proxyHostState),- }-- // ErrorTypeTransport triggers shouldDisableProxy (returns true)- transportErr := &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "connection refused"}- tc.handleProxyFailure("192.168.1.100", transportErr)-- if tc.proxyFailures != 1 {- t.Errorf("expected proxyFailures to be 1, got %d", tc.proxyFailures)- }-- // Proxy should still be enabled (threshold not reached)- if !tc.useProxy {- t.Error("expected useProxy to remain true (threshold not reached)")- }-- // handleProxyHostFailure should NOT have been called- tc.proxyMu.Lock()- hostStateCount := len(tc.proxyHostStates)- tc.proxyMu.Unlock()-- if hostStateCount != 0 {- t.Errorf("expected proxyHostStates to remain empty, got %d entries", hostStateCount)- }-}--func TestHandleProxyFailure_ReachesThreshold_DisablesProxy(t *testing.T) {- stub := &stubTemperatureProxy{}-- tc := &TemperatureCollector{- proxyClient: stub,- proxyFailures: proxyFailureThreshold - 1, // one failure away from threshold- useProxy: true,- proxyHostStates: make(map[string]*proxyHostState),- }-- transportErr := &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "connection refused"}- before := time.Now()- tc.handleProxyFailure("192.168.1.100", transportErr)-- // Proxy should now be disabled- if tc.useProxy {- t.Error("expected useProxy to be false after reaching threshold")- }-- // proxyFailures should be reset to 0- if tc.proxyFailures != 0 {- t.Errorf("expected proxyFailures to be reset to 0, got %d", tc.proxyFailures)- }-- // proxyCooldownUntil should be set in the future- if !tc.proxyCooldownUntil.After(before) {- t.Errorf("expected proxyCooldownUntil to be in the future, got %s", tc.proxyCooldownUntil)- }-}--func TestHandleProxyFailure_ReachesThreshold_UseProxyFalse_NoDoubleDisable(t *testing.T) {- stub := &stubTemperatureProxy{}-- originalCooldown := time.Now().Add(10 * time.Minute)- tc := &TemperatureCollector{- proxyClient: stub,- proxyFailures: proxyFailureThreshold - 1, // one failure away from threshold- useProxy: false, // already disabled- proxyCooldownUntil: originalCooldown,- proxyHostStates: make(map[string]*proxyHostState),- }-- transportErr := &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "connection refused"}- tc.handleProxyFailure("192.168.1.100", transportErr)-- // proxyFailures should increment (we still track failures)- if tc.proxyFailures != proxyFailureThreshold {- t.Errorf("expected proxyFailures to be %d, got %d", proxyFailureThreshold, tc.proxyFailures)- }-- // useProxy should remain false- if tc.useProxy {- t.Error("expected useProxy to remain false")- }-- // proxyCooldownUntil should NOT be changed (no double-disable)- if !tc.proxyCooldownUntil.Equal(originalCooldown) {- t.Errorf("expected proxyCooldownUntil to remain %s, got %s", originalCooldown, tc.proxyCooldownUntil)- }-}--func TestHandleProxyFailure_PlainError_TriggersDisablePath(t *testing.T) {- stub := &stubTemperatureProxy{}-- tc := &TemperatureCollector{- proxyClient: stub,- proxyFailures: 0,- useProxy: true,- proxyHostStates: make(map[string]*proxyHostState),- }-- // Plain errors (not ProxyError) should trigger shouldDisableProxy (returns true)- plainErr := fmt.Errorf("connection refused")- tc.handleProxyFailure("192.168.1.100", plainErr)-- if tc.proxyFailures != 1 {- t.Errorf("expected proxyFailures to be 1, got %d", tc.proxyFailures)- }-- // handleProxyHostFailure should NOT be called- tc.proxyMu.Lock()- hostStateCount := len(tc.proxyHostStates)- tc.proxyMu.Unlock()-- if hostStateCount != 0 {- t.Errorf("expected proxyHostStates to remain empty, got %d entries", hostStateCount)- }-}--// =============================================================================-// Tests for handleProxyHostFailure-// =============================================================================--func TestHandleProxyHostFailure_EmptyHost(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: make(map[string]*proxyHostState),- }-- tc.handleProxyHostFailure("", fmt.Errorf("some error"))-- tc.proxyMu.Lock()- defer tc.proxyMu.Unlock()-- if len(tc.proxyHostStates) != 0 {- t.Errorf("expected no state change for empty host, got %d entries", len(tc.proxyHostStates))- }-}--func TestHandleProxyHostFailure_WhitespaceOnlyHost(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: make(map[string]*proxyHostState),- }-- tc.handleProxyHostFailure(" ", fmt.Errorf("some error"))-- tc.proxyMu.Lock()- defer tc.proxyMu.Unlock()-- if len(tc.proxyHostStates) != 0 {- t.Errorf("expected no state change for whitespace-only host, got %d entries", len(tc.proxyHostStates))- }-}--func TestHandleProxyHostFailure_FirstFailureCreatesState(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: make(map[string]*proxyHostState),- }-- tc.handleProxyHostFailure("192.168.1.100", fmt.Errorf("connection refused"))-- tc.proxyMu.Lock()- defer tc.proxyMu.Unlock()-- state, exists := tc.proxyHostStates["192.168.1.100"]- if !exists {- t.Fatal("expected host state to be created")- }- if state.failures != 1 {- t.Errorf("expected failures to be 1, got %d", state.failures)- }- if state.lastError != "connection refused" {- t.Errorf("expected lastError to be 'connection refused', got %q", state.lastError)- }- if !state.cooldownUntil.IsZero() {- t.Errorf("expected cooldownUntil to be zero (threshold not reached), got %s", state.cooldownUntil)- }-}--func TestHandleProxyHostFailure_SubsequentFailuresIncrement(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {- failures: 1,- lastError: "first error",- },- },- }-- tc.handleProxyHostFailure("192.168.1.100", fmt.Errorf("second error"))-- tc.proxyMu.Lock()- defer tc.proxyMu.Unlock()-- state := tc.proxyHostStates["192.168.1.100"]- if state.failures != 2 {- t.Errorf("expected failures to be 2, got %d", state.failures)- }- if state.lastError != "second error" {- t.Errorf("expected lastError to be 'second error', got %q", state.lastError)- }- if !state.cooldownUntil.IsZero() {- t.Errorf("expected cooldownUntil to remain zero (threshold not reached), got %s", state.cooldownUntil)- }-}--func TestHandleProxyHostFailure_ReachesThresholdSetsCooldown(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": {- failures: proxyFailureThreshold - 1, // one failure away- lastError: "previous error",- },- },- }-- before := time.Now()- tc.handleProxyHostFailure("192.168.1.100", fmt.Errorf("final error"))-- tc.proxyMu.Lock()- defer tc.proxyMu.Unlock()-- state := tc.proxyHostStates["192.168.1.100"]- // failures should be reset to 0 after reaching threshold- if state.failures != 0 {- t.Errorf("expected failures to be reset to 0 after reaching threshold, got %d", state.failures)- }- if state.lastError != "final error" {- t.Errorf("expected lastError to be 'final error', got %q", state.lastError)- }- // cooldownUntil should be set in the future- if !state.cooldownUntil.After(before) {- t.Errorf("expected cooldownUntil to be set in the future, got %s", state.cooldownUntil)- }- // cooldownUntil should be approximately proxyRetryInterval from now- expectedMin := before.Add(proxyRetryInterval - time.Second)- if state.cooldownUntil.Before(expectedMin) {- t.Errorf("expected cooldownUntil to be at least %s, got %s", expectedMin, state.cooldownUntil)- }-}--func TestHandleProxyHostFailure_LastErrorStored(t *testing.T) {- tests := []struct {- name string- err error- wantLastErr string- }{- {- name: "simple error message",- err: fmt.Errorf("connection refused"),- wantLastErr: "connection refused",- },- {- name: "error with whitespace is trimmed",- err: fmt.Errorf(" timeout waiting for response "),- wantLastErr: "timeout waiting for response",- },- {- name: "empty error message",- err: fmt.Errorf(""),- wantLastErr: "",- },- {- name: "multiline error gets first part after trim",- err: fmt.Errorf("network error\ndetails here"),- wantLastErr: "network error\ndetails here",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: make(map[string]*proxyHostState),- }-- tc.handleProxyHostFailure("192.168.1.100", tt.err)-- tc.proxyMu.Lock()- state := tc.proxyHostStates["192.168.1.100"]- tc.proxyMu.Unlock()-- if state.lastError != tt.wantLastErr {- t.Errorf("expected lastError to be %q, got %q", tt.wantLastErr, state.lastError)- }- })- }-}--func TestHandleProxyHostFailure_NilStateInMap(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: map[string]*proxyHostState{- "192.168.1.100": nil, // nil state in map- },- }-- tc.handleProxyHostFailure("192.168.1.100", fmt.Errorf("some error"))-- tc.proxyMu.Lock()- defer tc.proxyMu.Unlock()-- state := tc.proxyHostStates["192.168.1.100"]- if state == nil {- t.Fatal("expected new state to be created for nil entry")- }- if state.failures != 1 {- t.Errorf("expected failures to be 1, got %d", state.failures)- }-}--func TestHandleProxyHostFailure_TrimsHostWhitespace(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: make(map[string]*proxyHostState),- }-- tc.handleProxyHostFailure(" 192.168.1.100 ", fmt.Errorf("some error"))-- tc.proxyMu.Lock()- defer tc.proxyMu.Unlock()-- // State should be stored under trimmed key- if _, exists := tc.proxyHostStates["192.168.1.100"]; !exists {- t.Error("expected state to be stored under trimmed host key")- }- if _, exists := tc.proxyHostStates[" 192.168.1.100 "]; exists {- t.Error("state should not be stored under untrimmed host key")- }-}--func TestHandleProxyHostFailure_MultipleHostsIndependent(t *testing.T) {- tc := &TemperatureCollector{- proxyHostStates: make(map[string]*proxyHostState),- }-- // First host gets multiple failures- tc.handleProxyHostFailure("192.168.1.100", fmt.Errorf("error 1"))- tc.handleProxyHostFailure("192.168.1.100", fmt.Errorf("error 2"))-- // Second host gets one failure- tc.handleProxyHostFailure("192.168.1.101", fmt.Errorf("different error"))-- tc.proxyMu.Lock()- defer tc.proxyMu.Unlock()-- state1 := tc.proxyHostStates["192.168.1.100"]- state2 := tc.proxyHostStates["192.168.1.101"]-- if state1.failures != 2 {- t.Errorf("expected host 1 failures to be 2, got %d", state1.failures)- }- if state2.failures != 1 {- t.Errorf("expected host 2 failures to be 1, got %d", state2.failures)- }- if state1.lastError != "error 2" {- t.Errorf("expected host 1 lastError to be 'error 2', got %q", state1.lastError)- }- if state2.lastError != "different error" {- t.Errorf("expected host 2 lastError to be 'different error', got %q", state2.lastError)- }-}--// TestParseSensorsJSON_TableDriven tests parseSensorsJSON with table-driven test cases-func TestParseSensorsJSON_TableDriven(t *testing.T) {- tests := []struct {- name string- input string- wantErr bool- errContains string- wantAvail bool- wantHasCPU bool- wantHasNVMe bool- wantHasGPU bool- wantHasSMART bool- checkFunc func(t *testing.T, temp *models.Temperature)- }{- {- name: "empty string returns error",- input: "",- wantErr: true,- errContains: "empty sensors output",- },- {- name: "whitespace-only string returns error",- input: " \t\n ",- wantErr: true,- errContains: "empty sensors output",- },- {- name: "invalid JSON returns error",- input: "not valid json {",- wantErr: true,- errContains: "failed to parse sensors JSON",- },- {- name: "empty JSON object returns no error but unavailable",- input: "{}",- wantErr: false,- wantAvail: false,- wantHasCPU: false,- wantHasNVMe: false,- },- {- name: "wrapper format with sensors and smart data",- input: `{- "sensors": {- "coretemp-isa-0000": {- "Package id 0": {"temp1_input": 55.0},- "Core 0": {"temp2_input": 52.0}- }- },- "smart": [- {"device": "/dev/sda", "serial": "ABC123", "model": "TestDisk", "type": "sat", "temperature": 35}- ]- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- wantHasNVMe: false,- wantHasGPU: false,- wantHasSMART: true,- checkFunc: func(t *testing.T, temp *models.Temperature) {- if temp.CPUPackage != 55.0 {- t.Errorf("expected CPUPackage 55.0, got %.2f", temp.CPUPackage)- }- if len(temp.SMART) != 1 {- t.Errorf("expected 1 SMART entry, got %d", len(temp.SMART))- }- },- },- {- name: "legacy format (direct sensors JSON)",- input: `{- "coretemp-isa-0000": {- "Package id 0": {"temp1_input": 48.0},- "Core 0": {"temp2_input": 46.0}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- wantHasNVMe: false,- checkFunc: func(t *testing.T, temp *models.Temperature) {- if temp.CPUPackage != 48.0 {- t.Errorf("expected CPUPackage 48.0, got %.2f", temp.CPUPackage)- }- },- },- {- name: "k10temp chip type",- input: `{- "k10temp-pci-00c3": {- "Tctl": {"temp1_input": 58.5}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- checkFunc: func(t *testing.T, temp *models.Temperature) {- if temp.CPUPackage != 58.5 {- t.Errorf("expected CPUPackage 58.5 from Tctl, got %.2f", temp.CPUPackage)- }- },- },- {- name: "acpitz chip type",- input: `{- "acpitz-acpi-0": {- "temp1": {"temp1_input": 42.0}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- },- {- name: "nvme chip type",- input: `{- "nvme-pci-0100": {- "Composite": {"temp1_input": 41.85}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: false,- wantHasNVMe: true,- checkFunc: func(t *testing.T, temp *models.Temperature) {- if len(temp.NVMe) != 1 {- t.Fatalf("expected 1 NVMe temp, got %d", len(temp.NVMe))- }- if temp.NVMe[0].Temp != 41.85 {- t.Errorf("expected NVMe temp 41.85, got %.2f", temp.NVMe[0].Temp)- }- },- },- {- name: "amdgpu chip type",- input: `{- "amdgpu-pci-0300": {- "edge": {"temp1_input": 65.0},- "junction": {"temp2_input": 72.0},- "mem": {"temp3_input": 68.0}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: false,- wantHasGPU: true,- checkFunc: func(t *testing.T, temp *models.Temperature) {- if len(temp.GPU) == 0 {- t.Fatalf("expected GPU temps, got none")- }- },- },- {- name: "nouveau chip type (NVIDIA)",- input: `{- "nouveau-pci-0100": {- "GPU core": {"temp1_input": 55.0}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: false,- wantHasGPU: true,- checkFunc: func(t *testing.T, temp *models.Temperature) {- if len(temp.GPU) == 0 {- t.Fatalf("expected GPU temps for nouveau, got none")- }- },- },- {- name: "chip data that is not a map should continue",- input: `{- "coretemp-isa-0000": {- "Package id 0": {"temp1_input": 50.0}- },- "invalid-chip": "not a map"- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- checkFunc: func(t *testing.T, temp *models.Temperature) {- if temp.CPUPackage != 50.0 {- t.Errorf("expected CPUPackage 50.0 despite invalid chip, got %.2f", temp.CPUPackage)- }- },- },- {- name: "chip data that is an array should continue",- input: `{- "k10temp-pci-00c3": {- "Tctl": {"temp1_input": 60.0}- },- "array-chip": [1, 2, 3]- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- checkFunc: func(t *testing.T, temp *models.Temperature) {- if temp.CPUPackage != 60.0 {- t.Errorf("expected CPUPackage 60.0 despite array chip, got %.2f", temp.CPUPackage)- }- },- },- {- name: "zenpower chip type",- input: `{- "zenpower-pci-00c3": {- "Tdie": {"temp1_input": 62.5}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- },- {- name: "nct6795 SuperIO chip",- input: `{- "nct6795-isa-0290": {- "CPUTIN": {"temp1_input": 45.0}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- },- {- name: "it87 chip type",- input: `{- "it87-isa-0a40": {- "temp1": {"temp1_input": 38.0}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- },- {- name: "rp1_adc (Raspberry Pi RP1)",- input: `{- "rp1_adc-isa-0000": {- "temp1": {"temp1_input": 49.5}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- },- {- name: "CPUMax calculated from cores when no package temp",- input: `{- "coretemp-isa-0000": {- "Core 0": {"temp2_input": 45.0},- "Core 1": {"temp3_input": 52.0},- "Core 2": {"temp4_input": 48.0}- }- }`,- wantErr: false,- wantAvail: true,- wantHasCPU: true,- checkFunc: func(t *testing.T, temp *models.Temperature) {- if temp.CPUMax != 52.0 {- t.Errorf("expected CPUMax 52.0 (highest core), got %.2f", temp.CPUMax)- }- if len(temp.Cores) != 3 {- t.Errorf("expected 3 cores, got %d", len(temp.Cores))- }- },- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- tc := &TemperatureCollector{}- temp, err := tc.parseSensorsJSON(tt.input)-- if tt.wantErr {- if err == nil {- t.Fatalf("expected error containing %q, got nil", tt.errContains)- }- if tt.errContains != "" && !strings.Contains(err.Error(), tt.errContains) {- t.Fatalf("expected error containing %q, got %q", tt.errContains, err.Error())- }- return- }-- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if temp == nil {- t.Fatalf("expected temperature struct, got nil")- }- if temp.Available != tt.wantAvail {- t.Errorf("Available = %v, want %v", temp.Available, tt.wantAvail)- }- if temp.HasCPU != tt.wantHasCPU {- t.Errorf("HasCPU = %v, want %v", temp.HasCPU, tt.wantHasCPU)- }- if temp.HasNVMe != tt.wantHasNVMe {- t.Errorf("HasNVMe = %v, want %v", temp.HasNVMe, tt.wantHasNVMe)- }- if temp.HasGPU != tt.wantHasGPU {- t.Errorf("HasGPU = %v, want %v", temp.HasGPU, tt.wantHasGPU)- }- if temp.HasSMART != tt.wantHasSMART {- t.Errorf("HasSMART = %v, want %v", temp.HasSMART, tt.wantHasSMART)- }-- if tt.checkFunc != nil {- tt.checkFunc(t, temp)- }- })- }-}--// =============================================================================-// Tests for parseGPUTemps-// =============================================================================--func TestParseGPUTemps_EmptyChipMap(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- collector.parseGPUTemps("amdgpu-pci-0400", map[string]interface{}{}, temp)-- if len(temp.GPU) != 0 {- t.Errorf("expected no GPU entries for empty chipMap, got %d", len(temp.GPU))- }-}--func TestParseGPUTemps_EdgeOnly(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "edge": map[string]interface{}{- "temp1_input": 55.0,- },- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 1 {- t.Fatalf("expected 1 GPU entry, got %d", len(temp.GPU))- }- if temp.GPU[0].Device != "amdgpu-pci-0400" {- t.Errorf("Device = %q, want %q", temp.GPU[0].Device, "amdgpu-pci-0400")- }- if temp.GPU[0].Edge != 55.0 {- t.Errorf("Edge = %v, want 55.0", temp.GPU[0].Edge)- }- if temp.GPU[0].Junction != 0 {- t.Errorf("Junction = %v, want 0", temp.GPU[0].Junction)- }- if temp.GPU[0].Mem != 0 {- t.Errorf("Mem = %v, want 0", temp.GPU[0].Mem)- }-}--func TestParseGPUTemps_JunctionOnly(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "junction": map[string]interface{}{- "temp1_input": 72.5,- },- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 1 {- t.Fatalf("expected 1 GPU entry, got %d", len(temp.GPU))- }- if temp.GPU[0].Junction != 72.5 {- t.Errorf("Junction = %v, want 72.5", temp.GPU[0].Junction)- }- if temp.GPU[0].Edge != 0 {- t.Errorf("Edge = %v, want 0", temp.GPU[0].Edge)- }- if temp.GPU[0].Mem != 0 {- t.Errorf("Mem = %v, want 0", temp.GPU[0].Mem)- }-}--func TestParseGPUTemps_MemOnly(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "mem": map[string]interface{}{- "temp1_input": 68.0,- },- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 1 {- t.Fatalf("expected 1 GPU entry, got %d", len(temp.GPU))- }- if temp.GPU[0].Mem != 68.0 {- t.Errorf("Mem = %v, want 68.0", temp.GPU[0].Mem)- }- if temp.GPU[0].Edge != 0 {- t.Errorf("Edge = %v, want 0", temp.GPU[0].Edge)- }- if temp.GPU[0].Junction != 0 {- t.Errorf("Junction = %v, want 0", temp.GPU[0].Junction)- }-}--func TestParseGPUTemps_AllThreeTemperatures(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "edge": map[string]interface{}{- "temp1_input": 55.0,- },- "junction": map[string]interface{}{- "temp2_input": 72.5,- },- "mem": map[string]interface{}{- "temp3_input": 68.0,- },- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 1 {- t.Fatalf("expected 1 GPU entry, got %d", len(temp.GPU))- }- if temp.GPU[0].Edge != 55.0 {- t.Errorf("Edge = %v, want 55.0", temp.GPU[0].Edge)- }- if temp.GPU[0].Junction != 72.5 {- t.Errorf("Junction = %v, want 72.5", temp.GPU[0].Junction)- }- if temp.GPU[0].Mem != 68.0 {- t.Errorf("Mem = %v, want 68.0", temp.GPU[0].Mem)- }-}--func TestParseGPUTemps_SkipsInvalidSensorData(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "edge": "not a map",- "junction": 12345,- "mem": nil,- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 0 {- t.Errorf("expected no GPU entries when sensor data is invalid, got %d", len(temp.GPU))- }-}--func TestParseGPUTemps_SkipsZeroTemperatures(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "edge": map[string]interface{}{- "temp1_input": 0.0,- },- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 0 {- t.Errorf("expected no GPU entries when temperature is zero, got %d", len(temp.GPU))- }-}--func TestParseGPUTemps_SkipsNegativeTemperatures(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "edge": map[string]interface{}{- "temp1_input": -5.0,- },- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 0 {- t.Errorf("expected no GPU entries when temperature is negative, got %d", len(temp.GPU))- }-}--func TestParseGPUTemps_CaseInsensitiveSensorName(t *testing.T) {- tests := []struct {- name string- sensorName string- wantEdge float64- wantJunc float64- wantMem float64- }{- {"lowercase edge", "edge", 55.0, 0, 0},- {"uppercase EDGE", "EDGE", 55.0, 0, 0},- {"mixed case Edge", "Edge", 55.0, 0, 0},- {"edge in longer name", "GPU Edge Temp", 55.0, 0, 0},- {"lowercase junction", "junction", 0, 72.0, 0},- {"uppercase JUNCTION", "JUNCTION", 0, 72.0, 0},- {"mixed case Junction", "Junction", 0, 72.0, 0},- {"lowercase mem", "mem", 0, 0, 68.0},- {"uppercase MEM", "MEM", 0, 0, 68.0},- {"mem in longer name", "Memory Temp", 0, 0, 68.0},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- var tempValue float64- if tt.wantEdge > 0 {- tempValue = tt.wantEdge- } else if tt.wantJunc > 0 {- tempValue = tt.wantJunc- } else {- tempValue = tt.wantMem- }-- chipMap := map[string]interface{}{- tt.sensorName: map[string]interface{}{- "temp1_input": tempValue,- },- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 1 {- t.Fatalf("expected 1 GPU entry, got %d", len(temp.GPU))- }- if temp.GPU[0].Edge != tt.wantEdge {- t.Errorf("Edge = %v, want %v", temp.GPU[0].Edge, tt.wantEdge)- }- if temp.GPU[0].Junction != tt.wantJunc {- t.Errorf("Junction = %v, want %v", temp.GPU[0].Junction, tt.wantJunc)- }- if temp.GPU[0].Mem != tt.wantMem {- t.Errorf("Mem = %v, want %v", temp.GPU[0].Mem, tt.wantMem)- }- })- }-}--func TestParseGPUTemps_HotspotMapsToJunction(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "hotspot": map[string]interface{}{- "temp1_input": 85.0,- },- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 1 {- t.Fatalf("expected 1 GPU entry, got %d", len(temp.GPU))- }- if temp.GPU[0].Junction != 85.0 {- t.Errorf("Junction = %v, want 85.0 (hotspot should map to junction)", temp.GPU[0].Junction)- }-}--func TestParseGPUTemps_AppendsToExisting(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{- GPU: []models.GPUTemp{- {Device: "amdgpu-pci-0300", Edge: 50.0},- },- }-- chipMap := map[string]interface{}{- "edge": map[string]interface{}{- "temp1_input": 55.0,- },- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 2 {- t.Fatalf("expected 2 GPU entries, got %d", len(temp.GPU))- }- if temp.GPU[0].Device != "amdgpu-pci-0300" || temp.GPU[0].Edge != 50.0 {- t.Errorf("first GPU entry was modified: got %+v", temp.GPU[0])- }- if temp.GPU[1].Device != "amdgpu-pci-0400" || temp.GPU[1].Edge != 55.0 {- t.Errorf("second GPU entry incorrect: got %+v", temp.GPU[1])- }-}--func TestParseGPUTemps_MixedValidInvalidSensors(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "edge": map[string]interface{}{- "temp1_input": 55.0,- },- "junction": "invalid", // should be skipped- "mem": map[string]interface{}{- "temp1_input": 0.0, // should be skipped (zero)- },- }-- collector.parseGPUTemps("amdgpu-pci-0400", chipMap, temp)-- if len(temp.GPU) != 1 {- t.Fatalf("expected 1 GPU entry, got %d", len(temp.GPU))- }- if temp.GPU[0].Edge != 55.0 {- t.Errorf("Edge = %v, want 55.0", temp.GPU[0].Edge)- }- if temp.GPU[0].Junction != 0 {- t.Errorf("Junction = %v, want 0 (invalid data)", temp.GPU[0].Junction)- }- if temp.GPU[0].Mem != 0 {- t.Errorf("Mem = %v, want 0 (zero temp)", temp.GPU[0].Mem)- }-}--// =============================================================================-// Tests for parseNouveauGPUTemps-// =============================================================================--func TestParseNouveauGPUTemps_EmptyChipMap(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- collector.parseNouveauGPUTemps("nouveau-pci-0100", map[string]interface{}{}, temp)-- if len(temp.GPU) != 0 {- t.Errorf("expected no GPU entries for empty chipMap, got %d", len(temp.GPU))- }-}--func TestParseNouveauGPUTemps_GPUCoreSensor(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "GPU core": map[string]interface{}{- "temp1_input": 65.0,- },- }-- collector.parseNouveauGPUTemps("nouveau-pci-0100", chipMap, temp)-- if len(temp.GPU) != 1 {- t.Fatalf("expected 1 GPU entry, got %d", len(temp.GPU))- }- if temp.GPU[0].Device != "nouveau-pci-0100" {- t.Errorf("Device = %q, want %q", temp.GPU[0].Device, "nouveau-pci-0100")- }- if temp.GPU[0].Edge != 65.0 {- t.Errorf("Edge = %v, want 65.0", temp.GPU[0].Edge)- }-}--func TestParseNouveauGPUTemps_CaseInsensitiveSensorName(t *testing.T) {- tests := []struct {- name string- sensorName string- }{- {"lowercase gpu core", "gpu core"},- {"uppercase GPU CORE", "GPU CORE"},- {"mixed case GPU Core", "GPU Core"},- {"gpu only", "GPU"},- {"core only", "core"},- {"GPU temp", "GPU temp"},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- tt.sensorName: map[string]interface{}{- "temp1_input": 60.0,- },- }-- collector.parseNouveauGPUTemps("nouveau-pci-0100", chipMap, temp)-- if len(temp.GPU) != 1 {- t.Fatalf("expected 1 GPU entry, got %d", len(temp.GPU))- }- if temp.GPU[0].Edge != 60.0 {- t.Errorf("Edge = %v, want 60.0", temp.GPU[0].Edge)- }- })- }-}--func TestParseNouveauGPUTemps_SkipsInvalidSensorData(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "GPU core": "not a map",- }-- collector.parseNouveauGPUTemps("nouveau-pci-0100", chipMap, temp)-- if len(temp.GPU) != 0 {- t.Errorf("expected no GPU entries when sensor data is invalid, got %d", len(temp.GPU))- }-}--func TestParseNouveauGPUTemps_SkipsZeroTemperatures(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "GPU core": map[string]interface{}{- "temp1_input": 0.0,- },- }-- collector.parseNouveauGPUTemps("nouveau-pci-0100", chipMap, temp)-- if len(temp.GPU) != 0 {- t.Errorf("expected no GPU entries when temperature is zero, got %d", len(temp.GPU))- }-}--func TestParseNouveauGPUTemps_SkipsNegativeTemperatures(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "GPU core": map[string]interface{}{- "temp1_input": -10.0,- },- }-- collector.parseNouveauGPUTemps("nouveau-pci-0100", chipMap, temp)-- if len(temp.GPU) != 0 {- t.Errorf("expected no GPU entries when temperature is negative, got %d", len(temp.GPU))- }-}--func TestParseNouveauGPUTemps_AppendsToExisting(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{- GPU: []models.GPUTemp{- {Device: "amdgpu-pci-0300", Edge: 50.0},- },- }-- chipMap := map[string]interface{}{- "GPU core": map[string]interface{}{- "temp1_input": 65.0,- },- }-- collector.parseNouveauGPUTemps("nouveau-pci-0100", chipMap, temp)-- if len(temp.GPU) != 2 {- t.Fatalf("expected 2 GPU entries, got %d", len(temp.GPU))- }- if temp.GPU[0].Device != "amdgpu-pci-0300" || temp.GPU[0].Edge != 50.0 {- t.Errorf("first GPU entry was modified: got %+v", temp.GPU[0])- }- if temp.GPU[1].Device != "nouveau-pci-0100" || temp.GPU[1].Edge != 65.0 {- t.Errorf("second GPU entry incorrect: got %+v", temp.GPU[1])- }-}--func TestParseNouveauGPUTemps_OnlyEdgeIsSet(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "GPU core": map[string]interface{}{- "temp1_input": 70.0,- },- }-- collector.parseNouveauGPUTemps("nouveau-pci-0100", chipMap, temp)-- if len(temp.GPU) != 1 {- t.Fatalf("expected 1 GPU entry, got %d", len(temp.GPU))- }- if temp.GPU[0].Edge != 70.0 {- t.Errorf("Edge = %v, want 70.0", temp.GPU[0].Edge)- }- // Nouveau only sets Edge, Junction and Mem should remain zero- if temp.GPU[0].Junction != 0 {- t.Errorf("Junction = %v, want 0 (nouveau only sets edge)", temp.GPU[0].Junction)- }- if temp.GPU[0].Mem != 0 {- t.Errorf("Mem = %v, want 0 (nouveau only sets edge)", temp.GPU[0].Mem)- }-}--func TestParseNouveauGPUTemps_NilSensorData(t *testing.T) {- collector := &TemperatureCollector{}- temp := &models.Temperature{}-- chipMap := map[string]interface{}{- "GPU core": nil,- }-- collector.parseNouveauGPUTemps("nouveau-pci-0100", chipMap, temp)-- if len(temp.GPU) != 0 {- t.Errorf("expected no GPU entries when sensor data is nil, got %d", len(temp.GPU))- }-}--// Helper functions for test setup--func intPtr(i int) *int {- return &i-}--func mustParseTime(s string) time.Time {- t, err := time.Parse(time.RFC3339, s)- if err != nil {- panic(err)- }- return t-}diff --git a/internal/tempproxy/client.go b/internal/tempproxy/client.godeleted file mode 100644index 9da0d7618c..0000000000--- a/internal/tempproxy/client.go+++ /dev/null@@ -1,442 +0,0 @@-package tempproxy--import (- "context"- "encoding/json"- "fmt"- "math"- "math/rand"- "net"- "os"- "time"-)--const (- defaultSocketPath = "/run/pulse-sensor-proxy/pulse-sensor-proxy.sock"- containerSocketPath = "/mnt/pulse-proxy/pulse-sensor-proxy.sock"- defaultTimeout = 30 * time.Second // Increased to accommodate SSH operations-- // Exponential backoff constants- initialBackoff = 100 * time.Millisecond- maxBackoff = 10 * time.Second- backoffFactor = 2.0- jitterFraction = 0.1- maxRetries = 3-)--var statFn = os.Stat--var dialContextFn = func(ctx context.Context, network, address string, timeout time.Duration) (net.Conn, error) {- dialer := net.Dialer{Timeout: timeout}- return dialer.DialContext(ctx, network, address)-}--// ErrorType classifies proxy errors for better error handling-type ErrorType int--const (- ErrorTypeUnknown ErrorType = iota- ErrorTypeTransport // Socket connection/communication failures- ErrorTypeAuth // Authorization failures- ErrorTypeSSH // SSH connectivity issues- ErrorTypeSensor // Sensor command failures- ErrorTypeTimeout // Operation timeout- ErrorTypeNode // Node allowlist or validation failures-)--// ProxyError wraps errors with classification-type ProxyError struct {- Type ErrorType- Message string- Retryable bool- Wrapped error-}--func (e *ProxyError) Error() string {- if e.Wrapped != nil {- return fmt.Sprintf("%s: %v", e.Message, e.Wrapped)- }- return e.Message-}--func (e *ProxyError) Unwrap() error {- return e.Wrapped-}--// Client communicates with pulse-sensor-proxy via unix socket-type Client struct {- socketPath string- timeout time.Duration-}--// NewClient creates a new proxy client-func NewClient() *Client {- socketPath := os.Getenv("PULSE_SENSOR_PROXY_SOCKET")- if socketPath == "" {- if _, err := statFn(defaultSocketPath); err == nil {- socketPath = defaultSocketPath- } else if _, err := statFn(containerSocketPath); err == nil {- socketPath = containerSocketPath- } else {- socketPath = defaultSocketPath- }- }-- return &Client{- socketPath: socketPath,- timeout: defaultTimeout,- }-}--// IsAvailable checks if the proxy is running and accessible-func (c *Client) IsAvailable() bool {- _, err := statFn(c.socketPath)- return err == nil-}--// RPCRequest represents a request to the proxy-type RPCRequest struct {- Method string `json:"method"`- Params map[string]interface{} `json:"params"`-}--// RPCResponse represents a response from the proxy-type RPCResponse struct {- Success bool `json:"success"`- Data map[string]interface{} `json:"data,omitempty"`- Error string `json:"error,omitempty"`-}--// calculateBackoff calculates exponential backoff with jitter-func calculateBackoff(attempt int) time.Duration {- if attempt <= 0 {- return initialBackoff- }-- // Calculate base backoff: initialBackoff * (backoffFactor ^ attempt)- backoff := float64(initialBackoff) * math.Pow(backoffFactor, float64(attempt))-- // Cap at maxBackoff- if backoff > float64(maxBackoff) {- backoff = float64(maxBackoff)- }-- // Add jitter: ±10% randomization- jitter := backoff * jitterFraction * (rand.Float64()*2 - 1)- backoff += jitter-- return time.Duration(backoff)-}--// classifyError categorizes errors for retry logic-func classifyError(err error, respError string) *ProxyError {- // Check response error messages first (even if err is nil)- // This handles cases where the socket succeeds but the proxy returns an application error- if respError != "" {- // Node validator/allowlist rejections should not disable the proxy globally- if contains(respError, "rejected by validator", "not in allowlist", "node \"") {- return &ProxyError{- Type: ErrorTypeNode,- Message: respError,- Retryable: false,- Wrapped: fmt.Errorf("%s", respError),- }- }-- // Rate limiting - never retry- if contains(respError, "rate limit") {- return &ProxyError{- Type: ErrorTypeTransport,- Message: respError,- Retryable: false,- Wrapped: fmt.Errorf("%s", respError),- }- }-- // Authorization errors - never retry- if respError == "unauthorized" || respError == "method requires host-level privileges" || respError == "method requires admin capability" || contains(respError, "admin capability") {- return &ProxyError{- Type: ErrorTypeAuth,- Message: respError,- Retryable: false,- Wrapped: fmt.Errorf("%s", respError),- }- }-- // SSH-related errors - retryable- if contains(respError, "ssh", "connection", "timeout") {- return &ProxyError{- Type: ErrorTypeSSH,- Message: "SSH connectivity issue",- Retryable: true,- Wrapped: fmt.Errorf("%s", respError),- }- }-- // Sensor errors - never retry- if contains(respError, "sensor", "temperature") {- return &ProxyError{- Type: ErrorTypeSensor,- Message: "sensor command failed",- Retryable: false,- Wrapped: fmt.Errorf("%s", respError),- }- }- }-- // If no response error and no network error, nothing to classify- if err == nil {- return nil- }-- // Check for timeout- if netErr, ok := err.(net.Error); ok && netErr.Timeout() {- return &ProxyError{- Type: ErrorTypeTimeout,- Message: "operation timed out",- Retryable: true,- Wrapped: err,- }- }-- // Check for connection errors (socket unavailable)- if _, ok := err.(*net.OpError); ok {- return &ProxyError{- Type: ErrorTypeTransport,- Message: "failed to connect to proxy socket",- Retryable: true,- Wrapped: err,- }- }-- // Unknown error- return &ProxyError{- Type: ErrorTypeUnknown,- Message: "unknown proxy error",- Retryable: false,- Wrapped: err,- }-}--// contains checks if any of the substrings are in the main string (case-insensitive)-func contains(s string, substrs ...string) bool {- for _, substr := range substrs {- if len(s) >= len(substr) {- for i := 0; i <= len(s)-len(substr); i++ {- match := true- for j := 0; j < len(substr); j++ {- c1 := s[i+j]- c2 := substr[j]- if c1 >= 'A' && c1 <= 'Z' {- c1 += 32- }- if c2 >= 'A' && c2 <= 'Z' {- c2 += 32- }- if c1 != c2 {- match = false- break- }- }- if match {- return true- }- }- }- }- return false-}--// callWithContext sends an RPC request with context and retry support-func (c *Client) callWithContext(ctx context.Context, method string, params map[string]interface{}) (*RPCResponse, error) {- var lastErr error-- for attempt := 0; attempt <= maxRetries; attempt++ {- // Check if context is already cancelled- select {- case <-ctx.Done():- return nil, &ProxyError{- Type: ErrorTypeTimeout,- Message: "context cancelled before retry",- Retryable: false,- Wrapped: ctx.Err(),- }- default:- }-- // Try the call- resp, err := c.callOnce(ctx, method, params)-- // Success- if err == nil && resp != nil && resp.Success {- return resp, nil- }-- // Classify error- respError := ""- if resp != nil {- respError = resp.Error- }- proxyErr := classifyError(err, respError)-- // Don't retry non-retryable errors- if proxyErr != nil && !proxyErr.Retryable {- return resp, proxyErr- }-- if proxyErr != nil {- lastErr = proxyErr- } else {- lastErr = err- }-- // Don't sleep after last attempt- if attempt < maxRetries {- backoff := calculateBackoff(attempt)-- select {- case <-time.After(backoff):- // Continue to next attempt- case <-ctx.Done():- return nil, &ProxyError{- Type: ErrorTypeTimeout,- Message: "context cancelled during backoff",- Retryable: false,- Wrapped: ctx.Err(),- }- }- }- }-- // All retries exhausted- return nil, &ProxyError{- Type: ErrorTypeTransport,- Message: fmt.Sprintf("max retries (%d) exhausted", maxRetries),- Retryable: false,- Wrapped: lastErr,- }-}--// callOnce sends a single RPC request without retries-func (c *Client) callOnce(ctx context.Context, method string, params map[string]interface{}) (*RPCResponse, error) {- // Connect to unix socket with context- conn, err := dialContextFn(ctx, "unix", c.socketPath, c.timeout)- if err != nil {- return nil, fmt.Errorf("failed to connect to proxy: %w", err)- }- defer conn.Close()-- // Set deadline from context or use default timeout- deadline, ok := ctx.Deadline()- if !ok {- deadline = time.Now().Add(c.timeout)- }- conn.SetDeadline(deadline)-- // Send request- req := RPCRequest{- Method: method,- Params: params,- }-- encoder := json.NewEncoder(conn)- if err := encoder.Encode(req); err != nil {- return nil, fmt.Errorf("failed to encode request: %w", err)- }-- // Read response (server uses newline-delimited framing)- var resp RPCResponse- decoder := json.NewDecoder(conn)- if err := decoder.Decode(&resp); err != nil {- return nil, fmt.Errorf("failed to decode response: %w", err)- }-- return &resp, nil-}--// call sends an RPC request and returns the response (legacy method, uses default context)-func (c *Client) call(method string, params map[string]interface{}) (*RPCResponse, error) {- ctx, cancel := context.WithTimeout(context.Background(), c.timeout)- defer cancel()- return c.callWithContext(ctx, method, params)-}--// GetStatus returns proxy status-func (c *Client) GetStatus() (map[string]interface{}, error) {- resp, err := c.call("get_status", nil)- if err != nil {- return nil, err- }-- return resp.Data, nil-}--// RegisterNodes returns list of discovered nodes with SSH status-func (c *Client) RegisterNodes() ([]map[string]interface{}, error) {- resp, err := c.call("register_nodes", nil)- if err != nil {- return nil, err- }-- // Extract nodes array from data- nodesRaw, ok := resp.Data["nodes"]- if !ok {- return nil, fmt.Errorf("no nodes in response")- }-- // Type assertion to []interface{} first, then convert- nodesArray, ok := nodesRaw.([]interface{})- if !ok {- return nil, fmt.Errorf("nodes is not an array")- }-- nodes := make([]map[string]interface{}, len(nodesArray))- for i, nodeRaw := range nodesArray {- node, ok := nodeRaw.(map[string]interface{})- if !ok {- return nil, fmt.Errorf("node %d is not a map", i)- }- nodes[i] = node- }-- return nodes, nil-}--// GetTemperature fetches temperature data from a specific node-func (c *Client) GetTemperature(nodeHost string) (string, error) {- params := map[string]interface{}{- "node": nodeHost,- }-- resp, err := c.call("get_temperature", params)- if err != nil {- return "", err- }-- // Extract temperature JSON string- tempRaw, ok := resp.Data["temperature"]- if !ok {- return "", fmt.Errorf("no temperature data in response")- }-- tempStr, ok := tempRaw.(string)- if !ok {- return "", fmt.Errorf("temperature is not a string")- }-- return tempStr, nil-}--// RequestCleanup signals the proxy to trigger host-side cleanup workflow.-func (c *Client) RequestCleanup(host string) error {- params := make(map[string]interface{}, 1)- if host != "" {- params["host"] = host- }-- if _, err := c.call("request_cleanup", params); err != nil {- return err- }-- return nil-}diff --git a/internal/tempproxy/client_coverage_test.go b/internal/tempproxy/client_coverage_test.godeleted file mode 100644index fc27437fd9..0000000000--- a/internal/tempproxy/client_coverage_test.go+++ /dev/null@@ -1,488 +0,0 @@-package tempproxy--import (- "context"- "encoding/json"- "errors"- "net"- "os"- "path/filepath"- "strings"- "testing"- "time"-)--type writeErrConn struct {- net.Conn-}--func (c writeErrConn) Write(p []byte) (int, error) {- return 0, errors.New("write failed")-}--func startUnixServer(t *testing.T, handler func(net.Conn)) (string, func()) {- t.Helper()-- dir := t.TempDir()- socketPath := filepath.Join(dir, "proxy.sock")- ln, err := net.Listen("unix", socketPath)- if err != nil {- t.Fatalf("listen: %v", err)- }-- done := make(chan struct{})- go func() {- defer close(done)- for {- conn, err := ln.Accept()- if err != nil {- return- }- go handler(conn)- }- }()-- cleanup := func() {- ln.Close()- <-done- }- return socketPath, cleanup-}--func startRPCServer(t *testing.T, handler func(RPCRequest) RPCResponse) (string, func()) {- t.Helper()- return startUnixServer(t, func(conn net.Conn) {- defer conn.Close()- decoder := json.NewDecoder(conn)- var req RPCRequest- if err := decoder.Decode(&req); err != nil {- return- }- resp := handler(req)- encoder := json.NewEncoder(conn)- _ = encoder.Encode(resp)- })-}--func TestNewClientSocketSelection(t *testing.T) {- origStat := statFn- t.Cleanup(func() { statFn = origStat })-- t.Run("EnvOverride", func(t *testing.T) {- origEnv := os.Getenv("PULSE_SENSOR_PROXY_SOCKET")- t.Cleanup(func() {- if origEnv == "" {- os.Unsetenv("PULSE_SENSOR_PROXY_SOCKET")- } else {- os.Setenv("PULSE_SENSOR_PROXY_SOCKET", origEnv)- }- })- os.Setenv("PULSE_SENSOR_PROXY_SOCKET", "/tmp/custom.sock")- statFn = func(string) (os.FileInfo, error) { return nil, os.ErrNotExist }-- client := NewClient()- if client.socketPath != "/tmp/custom.sock" {- t.Fatalf("expected env socket, got %q", client.socketPath)- }- })-- t.Run("DefaultExists", func(t *testing.T) {- statFn = func(path string) (os.FileInfo, error) {- if path == defaultSocketPath {- return nil, nil- }- return nil, os.ErrNotExist- }-- client := NewClient()- if client.socketPath != defaultSocketPath {- t.Fatalf("expected default socket, got %q", client.socketPath)- }- })-- t.Run("ContainerExists", func(t *testing.T) {- statFn = func(path string) (os.FileInfo, error) {- if path == containerSocketPath {- return nil, nil- }- return nil, os.ErrNotExist- }-- client := NewClient()- if client.socketPath != containerSocketPath {- t.Fatalf("expected container socket, got %q", client.socketPath)- }- })-- t.Run("FallbackDefault", func(t *testing.T) {- statFn = func(string) (os.FileInfo, error) { return nil, os.ErrNotExist }- client := NewClient()- if client.socketPath != defaultSocketPath {- t.Fatalf("expected fallback socket, got %q", client.socketPath)- }- })-}--func TestClientIsAvailable(t *testing.T) {- origStat := statFn- t.Cleanup(func() { statFn = origStat })-- client := &Client{socketPath: "/tmp/socket"}- statFn = func(string) (os.FileInfo, error) { return nil, nil }- if !client.IsAvailable() {- t.Fatalf("expected available")- }-- statFn = func(string) (os.FileInfo, error) { return nil, os.ErrNotExist }- if client.IsAvailable() {- t.Fatalf("expected unavailable")- }-}--func TestCallOnceSuccessAndDeadline(t *testing.T) {- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- if req.Method != "ping" {- t.Fatalf("unexpected method: %s", req.Method)- }- return RPCResponse{Success: true}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}-- resp, err := client.callOnce(context.Background(), "ping", nil)- if err != nil || resp == nil || !resp.Success {- t.Fatalf("expected success: resp=%v err=%v", resp, err)- }-- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)- defer cancel()- resp, err = client.callOnce(ctx, "ping", nil)- if err != nil || resp == nil || !resp.Success {- t.Fatalf("expected success with deadline: resp=%v err=%v", resp, err)- }-}--func TestCallOnceErrors(t *testing.T) {- t.Run("ConnectError", func(t *testing.T) {- client := &Client{socketPath: "/tmp/missing.sock", timeout: 10 * time.Millisecond}- if _, err := client.callOnce(context.Background(), "ping", nil); err == nil {- t.Fatalf("expected connect error")- }- })-- t.Run("EncodeError", func(t *testing.T) {- socketPath, cleanup := startUnixServer(t, func(conn net.Conn) {- conn.Close()- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.callOnce(context.Background(), "ping", nil); err == nil {- t.Fatalf("expected encode error")- }- })-- t.Run("EncodeErrorDial", func(t *testing.T) {- origDial := dialContextFn- t.Cleanup(func() { dialContextFn = origDial })-- clientConn, serverConn := net.Pipe()- t.Cleanup(func() { _ = serverConn.Close() })-- dialContextFn = func(ctx context.Context, network, address string, timeout time.Duration) (net.Conn, error) {- return writeErrConn{Conn: clientConn}, nil- }-- client := &Client{socketPath: "/tmp/unused.sock", timeout: 50 * time.Millisecond}- if _, err := client.callOnce(context.Background(), "ping", nil); err == nil {- t.Fatalf("expected encode error")- }- })-- t.Run("DecodeError", func(t *testing.T) {- socketPath, cleanup := startUnixServer(t, func(conn net.Conn) {- defer conn.Close()- _, _ = conn.Write([]byte("{"))- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.callOnce(context.Background(), "ping", nil); err == nil {- t.Fatalf("expected decode error")- }- })-}--func TestCallWithContextBehavior(t *testing.T) {- t.Run("Success", func(t *testing.T) {- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: true}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- resp, err := client.callWithContext(context.Background(), "ping", nil)- if err != nil || resp == nil || !resp.Success {- t.Fatalf("expected success: resp=%v err=%v", resp, err)- }- })-- t.Run("NonRetryable", func(t *testing.T) {- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: false, Error: "unauthorized"}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.callWithContext(context.Background(), "ping", nil); err == nil {- t.Fatalf("expected auth error")- }- })-- t.Run("CancelledBeforeRetry", func(t *testing.T) {- client := &Client{socketPath: "/tmp/missing.sock", timeout: 10 * time.Millisecond}- ctx, cancel := context.WithCancel(context.Background())- cancel()-- if _, err := client.callWithContext(ctx, "ping", nil); err == nil {- t.Fatalf("expected cancelled error")- }- })-- t.Run("CancelledDuringBackoff", func(t *testing.T) {- client := &Client{socketPath: "/tmp/missing.sock", timeout: 10 * time.Millisecond}- ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)- defer cancel()-- if _, err := client.callWithContext(ctx, "ping", nil); err == nil {- t.Fatalf("expected backoff cancel error")- }- })-- t.Run("MaxRetriesExhausted", func(t *testing.T) {- client := &Client{socketPath: "/tmp/missing.sock", timeout: 10 * time.Millisecond}- if _, err := client.callWithContext(context.Background(), "ping", nil); err == nil {- t.Fatalf("expected retry error")- }- })-}--func TestGetStatus(t *testing.T) {- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: true, Data: map[string]interface{}{"ok": true}}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- data, err := client.GetStatus()- if err != nil || data["ok"] != true {- t.Fatalf("unexpected status: %v err=%v", data, err)- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: false, Error: "boom"}- })- t.Cleanup(cleanup)-- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.GetStatus(); err == nil {- t.Fatalf("expected status error")- }-}--func TestRegisterNodes(t *testing.T) {- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: true, Data: map[string]interface{}{- "nodes": []interface{}{map[string]interface{}{"name": "node1"}},- }}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- nodes, err := client.RegisterNodes()- if err != nil || len(nodes) != 1 || nodes[0]["name"] != "node1" {- t.Fatalf("unexpected nodes: %v err=%v", nodes, err)- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: false, Error: "unauthorized"}- })- t.Cleanup(cleanup)- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.RegisterNodes(); err == nil {- t.Fatalf("expected proxy error")- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: true, Data: map[string]interface{}{}}- })- t.Cleanup(cleanup)- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.RegisterNodes(); err == nil {- t.Fatalf("expected missing nodes error")- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: true, Data: map[string]interface{}{"nodes": "bad"}}- })- t.Cleanup(cleanup)- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.RegisterNodes(); err == nil {- t.Fatalf("expected nodes type error")- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: true, Data: map[string]interface{}{"nodes": []interface{}{"bad"}}}- })- t.Cleanup(cleanup)- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.RegisterNodes(); err == nil {- t.Fatalf("expected node map error")- }-}--func TestGetTemperature(t *testing.T) {- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: true, Data: map[string]interface{}{"temperature": "42"}}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- temp, err := client.GetTemperature("node1")- if err != nil || temp != "42" {- t.Fatalf("unexpected temp: %q err=%v", temp, err)- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: false, Error: "unauthorized"}- })- t.Cleanup(cleanup)- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.GetTemperature("node1"); err == nil {- t.Fatalf("expected proxy error")- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: false, Error: "boom"}- })- t.Cleanup(cleanup)- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.GetTemperature("node1"); err == nil {- t.Fatalf("expected unknown error")- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: true, Data: map[string]interface{}{}}- })- t.Cleanup(cleanup)- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.GetTemperature("node1"); err == nil {- t.Fatalf("expected missing temperature error")- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: true, Data: map[string]interface{}{"temperature": 12}}- })- t.Cleanup(cleanup)- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.GetTemperature("node1"); err == nil {- t.Fatalf("expected type error")- }-}--func TestRequestCleanup(t *testing.T) {- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- if req.Method != "request_cleanup" {- t.Fatalf("unexpected method: %s", req.Method)- }- if req.Params["host"] != "node1" {- t.Fatalf("unexpected params: %v", req.Params)- }- return RPCResponse{Success: true}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if err := client.RequestCleanup("node1"); err != nil {- t.Fatalf("unexpected cleanup error: %v", err)- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: false, Error: "boom"}- })- t.Cleanup(cleanup)- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if err := client.RequestCleanup(""); err == nil {- t.Fatalf("expected proxy error")- }-- socketPath, cleanup = startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: false, Error: ""}- })- t.Cleanup(cleanup)- client = &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if err := client.RequestCleanup(""); err == nil {- t.Fatalf("expected rejected error")- }-- client = &Client{socketPath: "/tmp/missing.sock", timeout: 10 * time.Millisecond}- if err := client.RequestCleanup(""); err == nil {- t.Fatalf("expected call error")- }-}--func TestCallWrapper(t *testing.T) {- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: true}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- resp, err := client.call("ping", nil)- if err != nil || resp == nil || !resp.Success {- t.Fatalf("expected call success: resp=%v err=%v", resp, err)- }-}--func TestCallWithContextRetryableResponseError(t *testing.T) {- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: false, Error: "ssh timeout"}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.callWithContext(context.Background(), "ping", nil); err == nil {- t.Fatalf("expected retry exhaustion")- }-}--func TestCallWithContextSuccessOnRetry(t *testing.T) {- count := 0- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- count++- if count == 1 {- return RPCResponse{Success: false, Error: "ssh timeout"}- }- return RPCResponse{Success: true}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- resp, err := client.callWithContext(context.Background(), "ping", nil)- if err != nil || resp == nil || !resp.Success {- t.Fatalf("expected retry success: resp=%v err=%v", resp, err)- }-}--func TestCallWithContextRespErrorString(t *testing.T) {- socketPath, cleanup := startRPCServer(t, func(req RPCRequest) RPCResponse {- return RPCResponse{Success: false, Error: strings.Repeat("x", 1)}- })- t.Cleanup(cleanup)-- client := &Client{socketPath: socketPath, timeout: 50 * time.Millisecond}- if _, err := client.callWithContext(context.Background(), "ping", nil); err == nil {- t.Fatalf("expected error")- }-}diff --git a/internal/tempproxy/client_test.go b/internal/tempproxy/client_test.godeleted file mode 100644index 5191c30506..0000000000--- a/internal/tempproxy/client_test.go+++ /dev/null@@ -1,522 +0,0 @@-package tempproxy--import (- "errors"- "net"- "testing"- "time"-)--func TestErrorType_Constants(t *testing.T) {- // Verify enum values are distinct- values := map[ErrorType]bool{}- errorTypes := []ErrorType{- ErrorTypeUnknown,- ErrorTypeTransport,- ErrorTypeAuth,- ErrorTypeSSH,- ErrorTypeSensor,- ErrorTypeTimeout,- ErrorTypeNode,- }-- for _, et := range errorTypes {- if values[et] {- t.Errorf("Duplicate ErrorType value: %d", et)- }- values[et] = true- }-- // ErrorTypeUnknown should be 0 (default)- if ErrorTypeUnknown != 0 {- t.Errorf("ErrorTypeUnknown = %d, want 0", ErrorTypeUnknown)- }-}--func TestProxyError_Error(t *testing.T) {- tests := []struct {- name string- err ProxyError- contains string- }{- {- name: "with wrapped error",- err: ProxyError{- Message: "connection failed",- Wrapped: errors.New("dial tcp: connection refused"),- },- contains: "connection failed: dial tcp: connection refused",- },- {- name: "without wrapped error",- err: ProxyError{- Message: "operation timed out",- },- contains: "operation timed out",- },- {- name: "with type and retryable",- err: ProxyError{- Type: ErrorTypeSSH,- Message: "SSH connectivity issue",- Retryable: true,- Wrapped: errors.New("ssh: handshake failed"),- },- contains: "SSH connectivity issue: ssh: handshake failed",- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := tc.err.Error()- if result != tc.contains {- t.Errorf("Error() = %q, want %q", result, tc.contains)- }- })- }-}--func TestProxyError_Unwrap(t *testing.T) {- inner := errors.New("inner error")- err := &ProxyError{- Message: "outer error",- Wrapped: inner,- }-- unwrapped := err.Unwrap()- if unwrapped != inner {- t.Errorf("Unwrap() = %v, want %v", unwrapped, inner)- }-}--func TestProxyError_Unwrap_Nil(t *testing.T) {- err := &ProxyError{- Message: "error without wrapped",- }-- unwrapped := err.Unwrap()- if unwrapped != nil {- t.Errorf("Unwrap() = %v, want nil", unwrapped)- }-}--func TestCalculateBackoff(t *testing.T) {- tests := []struct {- name string- attempt int- minExpected time.Duration- maxExpected time.Duration- }{- {- name: "attempt 0",- attempt: 0,- minExpected: 90 * time.Millisecond, // initialBackoff - 10% jitter- maxExpected: 110 * time.Millisecond, // initialBackoff + 10% jitter- },- {- name: "attempt 1",- attempt: 1,- minExpected: 180 * time.Millisecond, // 200ms * 0.9- maxExpected: 220 * time.Millisecond, // 200ms * 1.1- },- {- name: "attempt 2",- attempt: 2,- minExpected: 360 * time.Millisecond, // 400ms * 0.9- maxExpected: 440 * time.Millisecond, // 400ms * 1.1- },- {- name: "negative attempt (treated as 0)",- attempt: -1,- minExpected: 90 * time.Millisecond,- maxExpected: 110 * time.Millisecond,- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- // Run multiple times to account for jitter- for i := 0; i < 10; i++ {- result := calculateBackoff(tc.attempt)- if result < tc.minExpected || result > tc.maxExpected {- t.Errorf("calculateBackoff(%d) = %v, want between %v and %v",- tc.attempt, result, tc.minExpected, tc.maxExpected)- }- }- })- }-}--func TestCalculateBackoff_CappedAtMax(t *testing.T) {- // High attempt number should be capped at maxBackoff (10s) + jitter- result := calculateBackoff(100)-- maxWithJitter := maxBackoff + time.Duration(float64(maxBackoff)*jitterFraction)- if result > maxWithJitter {- t.Errorf("calculateBackoff(100) = %v, should be capped at ~%v", result, maxBackoff)- }-}--func TestContains(t *testing.T) {- tests := []struct {- name string- s string- substrs []string- expected bool- }{- {- name: "single match",- s: "connection refused",- substrs: []string{"refused"},- expected: true,- },- {- name: "multiple substrs first match",- s: "ssh connection failed",- substrs: []string{"ssh", "timeout"},- expected: true,- },- {- name: "multiple substrs second match",- s: "operation timeout",- substrs: []string{"ssh", "timeout"},- expected: true,- },- {- name: "no match",- s: "success",- substrs: []string{"error", "failed"},- expected: false,- },- {- name: "case insensitive upper",- s: "CONNECTION REFUSED",- substrs: []string{"connection"},- expected: true,- },- {- name: "case insensitive mixed",- s: "SSH Error",- substrs: []string{"ssh error"},- expected: true,- },- {- name: "case insensitive upper substr",- s: "connection refused",- substrs: []string{"REFUSED"},- expected: true,- },- {- name: "empty string",- s: "",- substrs: []string{"test"},- expected: false,- },- {- name: "empty substrs",- s: "test",- substrs: []string{},- expected: false,- },- {- name: "exact match",- s: "error",- substrs: []string{"error"},- expected: true,- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := contains(tc.s, tc.substrs...)- if result != tc.expected {- t.Errorf("contains(%q, %v) = %v, want %v", tc.s, tc.substrs, result, tc.expected)- }- })- }-}--func TestClassifyError_NodeErrors(t *testing.T) {- tests := []struct {- name string- respError string- expectType ErrorType- retryable bool- }{- {- name: "rejected by validator",- respError: "rejected by validator: invalid node",- expectType: ErrorTypeNode,- retryable: false,- },- {- name: "not in allowlist",- respError: "node not in allowlist",- expectType: ErrorTypeNode,- retryable: false,- },- {- name: "node quote pattern",- respError: "node \"server1\" not found",- expectType: ErrorTypeNode,- retryable: false,- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := classifyError(nil, tc.respError)- if result == nil {- t.Fatal("classifyError returned nil")- }- if result.Type != tc.expectType {- t.Errorf("Type = %v, want %v", result.Type, tc.expectType)- }- if result.Retryable != tc.retryable {- t.Errorf("Retryable = %v, want %v", result.Retryable, tc.retryable)- }- })- }-}--func TestClassifyError_AuthErrors(t *testing.T) {- tests := []struct {- respError string- }{- {"unauthorized"},- {"method requires host-level privileges"},- {"method requires admin capability"},- {"missing admin capability for operation"},- }-- for _, tc := range tests {- t.Run(tc.respError, func(t *testing.T) {- result := classifyError(nil, tc.respError)- if result == nil {- t.Fatal("classifyError returned nil")- }- if result.Type != ErrorTypeAuth {- t.Errorf("Type = %v, want ErrorTypeAuth", result.Type)- }- if result.Retryable {- t.Error("Auth errors should not be retryable")- }- })- }-}--func TestClassifyError_SSHErrors(t *testing.T) {- tests := []struct {- respError string- }{- {"ssh: handshake failed"},- {"connection reset by peer"},- {"operation timeout exceeded"},- }-- for _, tc := range tests {- t.Run(tc.respError, func(t *testing.T) {- result := classifyError(nil, tc.respError)- if result == nil {- t.Fatal("classifyError returned nil")- }- if result.Type != ErrorTypeSSH {- t.Errorf("Type = %v, want ErrorTypeSSH", result.Type)- }- if !result.Retryable {- t.Error("SSH errors should be retryable")- }- })- }-}--func TestClassifyError_SensorErrors(t *testing.T) {- tests := []struct {- respError string- }{- {"sensor command failed"},- {"temperature sensor unavailable"},- }-- for _, tc := range tests {- t.Run(tc.respError, func(t *testing.T) {- result := classifyError(nil, tc.respError)- if result == nil {- t.Fatal("classifyError returned nil")- }- if result.Type != ErrorTypeSensor {- t.Errorf("Type = %v, want ErrorTypeSensor", result.Type)- }- if result.Retryable {- t.Error("Sensor errors should not be retryable")- }- })- }-}--func TestClassifyError_RateLimitErrors(t *testing.T) {- result := classifyError(nil, "rate limit exceeded")- if result == nil {- t.Fatal("classifyError returned nil")- }- if result.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", result.Type)- }- if result.Retryable {- t.Error("Rate limit errors should not be retryable")- }-}--func TestClassifyError_TimeoutNetError(t *testing.T) {- // Create a mock timeout error- timeoutErr := &mockNetError{timeout: true}-- result := classifyError(timeoutErr, "")- if result == nil {- t.Fatal("classifyError returned nil")- }- if result.Type != ErrorTypeTimeout {- t.Errorf("Type = %v, want ErrorTypeTimeout", result.Type)- }- if !result.Retryable {- t.Error("Timeout errors should be retryable")- }-}--func TestClassifyError_OpError(t *testing.T) {- opErr := &net.OpError{- Op: "dial",- Net: "unix",- Err: errors.New("connection refused"),- }-- result := classifyError(opErr, "")- if result == nil {- t.Fatal("classifyError returned nil")- }- if result.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", result.Type)- }- if !result.Retryable {- t.Error("Transport errors should be retryable")- }-}--func TestClassifyError_NilInputs(t *testing.T) {- result := classifyError(nil, "")- if result != nil {- t.Errorf("classifyError(nil, \"\") = %v, want nil", result)- }-}--func TestClassifyError_UnknownError(t *testing.T) {- unknownErr := errors.New("some unknown error")-- result := classifyError(unknownErr, "")- if result == nil {- t.Fatal("classifyError returned nil")- }- if result.Type != ErrorTypeUnknown {- t.Errorf("Type = %v, want ErrorTypeUnknown", result.Type)- }- if result.Retryable {- t.Error("Unknown errors should not be retryable")- }-}--func TestRPCRequest_Fields(t *testing.T) {- req := RPCRequest{- Method: "get_temperature",- Params: map[string]interface{}{- "node": "server1",- },- }-- if req.Method != "get_temperature" {- t.Errorf("Method = %q, want get_temperature", req.Method)- }- if req.Params["node"] != "server1" {- t.Errorf("Params[node] = %v, want server1", req.Params["node"])- }-}--func TestRPCResponse_Fields(t *testing.T) {- resp := RPCResponse{- Success: true,- Data: map[string]interface{}{- "temperature": "45.0",- },- Error: "",- }-- if !resp.Success {- t.Error("Success should be true")- }- if resp.Data["temperature"] != "45.0" {- t.Errorf("Data[temperature] = %v, want 45.0", resp.Data["temperature"])- }- if resp.Error != "" {- t.Errorf("Error = %q, want empty", resp.Error)- }-}--func TestRPCResponse_ErrorCase(t *testing.T) {- resp := RPCResponse{- Success: false,- Error: "unauthorized",- }-- if resp.Success {- t.Error("Success should be false")- }- if resp.Error != "unauthorized" {- t.Errorf("Error = %q, want unauthorized", resp.Error)- }-}--func TestClient_Fields(t *testing.T) {- client := &Client{- socketPath: "/test/socket.sock",- timeout: 60 * time.Second,- }-- if client.socketPath != "/test/socket.sock" {- t.Errorf("socketPath = %q, want /test/socket.sock", client.socketPath)- }- if client.timeout != 60*time.Second {- t.Errorf("timeout = %v, want 60s", client.timeout)- }-}--func TestProxyError_AllFields(t *testing.T) {- wrapped := errors.New("wrapped error")- err := ProxyError{- Type: ErrorTypeSSH,- Message: "SSH connectivity issue",- Retryable: true,- Wrapped: wrapped,- }-- if err.Type != ErrorTypeSSH {- t.Errorf("Type = %v, want ErrorTypeSSH", err.Type)- }- if err.Message != "SSH connectivity issue" {- t.Errorf("Message = %q, want 'SSH connectivity issue'", err.Message)- }- if !err.Retryable {- t.Error("Retryable should be true")- }- if err.Wrapped != wrapped {- t.Errorf("Wrapped = %v, want %v", err.Wrapped, wrapped)- }-}--// mockNetError implements net.Error for testing-type mockNetError struct {- timeout bool- temporary bool-}--func (e *mockNetError) Error() string { return "mock network error" }-func (e *mockNetError) Timeout() bool { return e.timeout }-func (e *mockNetError) Temporary() bool { return e.temporary }diff --git a/internal/tempproxy/http_client.go b/internal/tempproxy/http_client.godeleted file mode 100644index a1d044e914..0000000000--- a/internal/tempproxy/http_client.go+++ /dev/null@@ -1,222 +0,0 @@-package tempproxy--import (- "crypto/tls"- "encoding/json"- "fmt"- "io"- "net/http"- "net/url"- "strings"- "time"-)--// HTTPClient communicates with pulse-sensor-proxy via HTTPS-type HTTPClient struct {- baseURL string- authToken string- httpClient *http.Client- timeout time.Duration-}--// NewHTTPClient creates a new HTTP-based proxy client-func NewHTTPClient(baseURL, authToken string) *HTTPClient {- // Create HTTP client with TLS and reasonable timeouts- httpClient := &http.Client{- Timeout: defaultTimeout,- Transport: &http.Transport{- TLSClientConfig: &tls.Config{- MinVersion: tls.VersionTLS12,- InsecureSkipVerify: true, // Accept self-signed certificates from sensor-proxy- },- MaxIdleConns: 10,- IdleConnTimeout: 90 * time.Second,- DisableCompression: false,- DisableKeepAlives: false,- MaxIdleConnsPerHost: 2,- },- }-- return &HTTPClient{- baseURL: strings.TrimSuffix(baseURL, "/"),- authToken: authToken,- httpClient: httpClient,- timeout: defaultTimeout,- }-}--// IsAvailable checks if the HTTP proxy is accessible-// For HTTP mode, we consider it available if URL and token are configured-func (c *HTTPClient) IsAvailable() bool {- return c.baseURL != "" && c.authToken != ""-}--// GetTemperature fetches temperature data from a node via HTTP-func (c *HTTPClient) GetTemperature(nodeHost string) (string, error) {- if !c.IsAvailable() {- return "", &ProxyError{- Type: ErrorTypeTransport,- Message: "HTTP proxy not configured",- Retryable: false,- }- }-- // Build request URL- reqURL := fmt.Sprintf("%s/temps?node=%s", c.baseURL, url.QueryEscape(nodeHost))-- // Create request- req, err := http.NewRequest(http.MethodGet, reqURL, nil)- if err != nil {- return "", &ProxyError{- Type: ErrorTypeTransport,- Message: "failed to create HTTP request",- Retryable: false,- Wrapped: err,- }- }-- // Add authorization header- req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.authToken))- req.Header.Set("Accept", "application/json")-- // Execute request with retries- var lastErr error = &ProxyError{- Type: ErrorTypeUnknown,- Message: "all retry attempts failed",- Retryable: false,- }- for attempt := 0; attempt < maxRetries; attempt++ {- if attempt > 0 {- backoff := calculateBackoff(attempt)- time.Sleep(backoff)- }-- resp, err := c.httpClient.Do(req)- if err != nil {- lastErr = &ProxyError{- Type: ErrorTypeTransport,- Message: fmt.Sprintf("HTTP request failed (attempt %d/%d)", attempt+1, maxRetries),- Retryable: true,- Wrapped: err,- }- continue- }-- // Read response body- body, err := io.ReadAll(resp.Body)- resp.Body.Close()-- if err != nil {- lastErr = &ProxyError{- Type: ErrorTypeTransport,- Message: "failed to read response body",- Retryable: true,- Wrapped: err,- }- continue- }-- // Check HTTP status- if resp.StatusCode == http.StatusUnauthorized {- return "", &ProxyError{- Type: ErrorTypeAuth,- Message: "authentication failed - invalid token",- Retryable: false,- }- }-- if resp.StatusCode == http.StatusForbidden {- return "", &ProxyError{- Type: ErrorTypeAuth,- Message: "node not allowed by proxy",- Retryable: false,- }- }-- if resp.StatusCode == http.StatusTooManyRequests {- lastErr = &ProxyError{- Type: ErrorTypeTransport,- Message: "rate limit exceeded",- Retryable: true,- }- continue- }-- if resp.StatusCode != http.StatusOK {- return "", &ProxyError{- Type: ErrorTypeTransport,- Message: fmt.Sprintf("HTTP %d: %s", resp.StatusCode, string(body)),- Retryable: resp.StatusCode >= 500,- }- }-- // Parse JSON response- var jsonResp struct {- Node string `json:"node"`- Temperature string `json:"temperature"` // This is a JSON-encoded string- }-- if err := json.Unmarshal(body, &jsonResp); err != nil {- return "", &ProxyError{- Type: ErrorTypeTransport,- Message: "failed to parse response JSON",- Retryable: false,- Wrapped: err,- }- }-- // The temperature field contains JSON-encoded sensor data as a string- // Return it as-is since the caller expects raw JSON- return jsonResp.Temperature, nil- }-- // All retries exhausted- return "", lastErr-}--// HealthCheck calls the proxy /health endpoint to verify connectivity.-func (c *HTTPClient) HealthCheck() error {- if !c.IsAvailable() {- return &ProxyError{- Type: ErrorTypeTransport,- Message: "HTTP proxy not configured",- Retryable: false,- }- }-- reqURL := fmt.Sprintf("%s/health", c.baseURL)- req, err := http.NewRequest(http.MethodGet, reqURL, nil)- if err != nil {- return &ProxyError{- Type: ErrorTypeTransport,- Message: "failed to create HTTP request",- Retryable: false,- Wrapped: err,- }- }- req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.authToken))- req.Header.Set("Accept", "application/json")-- resp, err := c.httpClient.Do(req)- if err != nil {- return &ProxyError{- Type: ErrorTypeTransport,- Message: "HTTP request failed",- Retryable: true,- Wrapped: err,- }- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))- return &ProxyError{- Type: ErrorTypeTransport,- Message: fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body))),- Retryable: resp.StatusCode >= 500,- }- }-- _, _ = io.Copy(io.Discard, resp.Body)- return nil-}diff --git a/internal/tempproxy/http_client_test.go b/internal/tempproxy/http_client_test.godeleted file mode 100644index 6bfe3eed58..0000000000--- a/internal/tempproxy/http_client_test.go+++ /dev/null@@ -1,582 +0,0 @@-package tempproxy--import (- "encoding/json"- "errors"- "io"- "net/http"- "net/http/httptest"- "strings"- "testing"- "time"-)--func TestNewHTTPClient(t *testing.T) {- client := NewHTTPClient("https://example.com/api", "test-token")-- if client.baseURL != "https://example.com/api" {- t.Errorf("baseURL = %q, want https://example.com/api", client.baseURL)- }- if client.authToken != "test-token" {- t.Errorf("authToken = %q, want test-token", client.authToken)- }- if client.httpClient == nil {- t.Error("httpClient should not be nil")- }- if client.timeout != defaultTimeout {- t.Errorf("timeout = %v, want %v", client.timeout, defaultTimeout)- }-}--func TestNewHTTPClient_TrimsTrailingSlash(t *testing.T) {- client := NewHTTPClient("https://example.com/api/", "token")-- if client.baseURL != "https://example.com/api" {- t.Errorf("baseURL = %q, want trailing slash removed", client.baseURL)- }-}--func TestHTTPClient_IsAvailable(t *testing.T) {- tests := []struct {- name string- baseURL string- token string- expected bool- }{- {- name: "both configured",- baseURL: "https://example.com",- token: "token",- expected: true,- },- {- name: "empty baseURL",- baseURL: "",- token: "token",- expected: false,- },- {- name: "empty token",- baseURL: "https://example.com",- token: "",- expected: false,- },- {- name: "both empty",- baseURL: "",- token: "",- expected: false,- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- client := NewHTTPClient(tc.baseURL, tc.token)- if client.IsAvailable() != tc.expected {- t.Errorf("IsAvailable() = %v, want %v", client.IsAvailable(), tc.expected)- }- })- }-}--func TestHTTPClient_GetTemperature_Success(t *testing.T) {- // Create a test server- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- // Verify request- if r.Method != http.MethodGet {- t.Errorf("Method = %q, want GET", r.Method)- }- if !strings.HasPrefix(r.URL.Path, "/temps") {- t.Errorf("Path = %q, want /temps", r.URL.Path)- }- if r.URL.Query().Get("node") != "node1" {- t.Errorf("node query param = %q, want node1", r.URL.Query().Get("node"))- }- if r.Header.Get("Authorization") != "Bearer test-token" {- t.Errorf("Authorization = %q, want Bearer test-token", r.Header.Get("Authorization"))- }- if r.Header.Get("Accept") != "application/json" {- t.Errorf("Accept = %q, want application/json", r.Header.Get("Accept"))- }-- // Return success response- resp := struct {- Node string `json:"node"`- Temperature string `json:"temperature"`- }{- Node: "node1",- Temperature: `{"cpu": 45.0}`,- }- w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(resp)- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "test-token")- temp, err := client.GetTemperature("node1")-- if err != nil {- t.Fatalf("GetTemperature() error = %v", err)- }- if temp != `{"cpu": 45.0}` {- t.Errorf("GetTemperature() = %q, want {\"cpu\": 45.0}", temp)- }-}--func TestHTTPClient_GetTemperature_NotConfigured(t *testing.T) {- client := NewHTTPClient("", "")- _, err := client.GetTemperature("node1")-- if err == nil {- t.Fatal("Expected error for unconfigured client")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", proxyErr.Type)- }- if proxyErr.Retryable {- t.Error("Should not be retryable")- }-}--func TestHTTPClient_GetTemperature_Unauthorized(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusUnauthorized)- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "bad-token")- _, err := client.GetTemperature("node1")-- if err == nil {- t.Fatal("Expected error for 401 response")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeAuth {- t.Errorf("Type = %v, want ErrorTypeAuth", proxyErr.Type)- }- if proxyErr.Retryable {- t.Error("Auth errors should not be retryable")- }-}--func TestHTTPClient_GetTemperature_Forbidden(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusForbidden)- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "token")- _, err := client.GetTemperature("node1")-- if err == nil {- t.Fatal("Expected error for 403 response")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeAuth {- t.Errorf("Type = %v, want ErrorTypeAuth", proxyErr.Type)- }- if proxyErr.Message != "node not allowed by proxy" {- t.Errorf("Message = %q, want 'node not allowed by proxy'", proxyErr.Message)- }-}--func TestHTTPClient_GetTemperature_RateLimit(t *testing.T) {- attempts := 0- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- attempts++- w.WriteHeader(http.StatusTooManyRequests)- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "token")- _, err := client.GetTemperature("node1")-- if err == nil {- t.Fatal("Expected error for 429 response")- }-- // Should have retried- if attempts < 2 {- t.Errorf("Expected retries, got %d attempts", attempts)- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", proxyErr.Type)- }-}--func TestHTTPClient_GetTemperature_ServerError(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusInternalServerError)- w.Write([]byte("internal error"))- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "token")- _, err := client.GetTemperature("node1")-- if err == nil {- t.Fatal("Expected error for 500 response")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", proxyErr.Type)- }- // 5xx errors should be retryable- if !proxyErr.Retryable {- t.Error("5xx errors should be retryable")- }-}--func TestHTTPClient_GetTemperature_ClientError(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusBadRequest)- w.Write([]byte("bad request"))- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "token")- _, err := client.GetTemperature("node1")-- if err == nil {- t.Fatal("Expected error for 400 response")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- // 4xx errors (except 401, 403, 429) should not be retryable- if proxyErr.Retryable {- t.Error("4xx errors should not be retryable")- }-}--func TestHTTPClient_GetTemperature_InvalidJSON(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Content-Type", "application/json")- w.Write([]byte("not valid json"))- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "token")- _, err := client.GetTemperature("node1")-- if err == nil {- t.Fatal("Expected error for invalid JSON")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", proxyErr.Type)- }- if !strings.Contains(proxyErr.Message, "parse response JSON") {- t.Errorf("Message = %q, should mention JSON parsing", proxyErr.Message)- }-}--func TestHTTPClient_GetTemperature_URLEncoding(t *testing.T) {- receivedNode := ""- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- receivedNode = r.URL.Query().Get("node")- resp := struct {- Node string `json:"node"`- Temperature string `json:"temperature"`- }{- Node: receivedNode,- Temperature: "{}",- }- json.NewEncoder(w).Encode(resp)- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "token")-- // Test with special characters that need URL encoding- nodeWithSpaces := "node with spaces"- _, err := client.GetTemperature(nodeWithSpaces)-- if err != nil {- t.Fatalf("GetTemperature() error = %v", err)- }- if receivedNode != nodeWithSpaces {- t.Errorf("Received node = %q, want %q", receivedNode, nodeWithSpaces)- }-}--func TestHTTPClient_GetTemperature_RetryOnTransportError(t *testing.T) {- attempts := 0- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- attempts++- if attempts < 3 {- // Force connection close to simulate transport error- hj, ok := w.(http.Hijacker)- if ok {- conn, _, _ := hj.Hijack()- conn.Close()- return- }- }- // Success on third attempt- resp := struct {- Node string `json:"node"`- Temperature string `json:"temperature"`- }{- Node: "node1",- Temperature: "{}",- }- json.NewEncoder(w).Encode(resp)- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "token")- _, _ = client.GetTemperature("node1")-- // Should have made multiple attempts- if attempts < 2 {- t.Errorf("Expected retries, got %d attempts", attempts)- }-}--func TestHTTPClient_GetTemperature_RequestBuildError(t *testing.T) {- client := NewHTTPClient("http://[::1", "token")- _, err := client.GetTemperature("node1")-- if err == nil {- t.Fatal("Expected error for request creation")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", proxyErr.Type)- }- if !strings.Contains(proxyErr.Message, "failed to create HTTP request") {- t.Errorf("Message = %q, want request creation failure", proxyErr.Message)- }-}--func TestHTTPClient_GetTemperature_ReadBodyError(t *testing.T) {- attempts := 0- client := NewHTTPClient("https://example.com", "token")- client.httpClient.Transport = roundTripperFunc(func(r *http.Request) (*http.Response, error) {- attempts++- if attempts == 1 {- return &http.Response{- StatusCode: http.StatusOK,- Body: errReadCloser{},- Header: make(http.Header),- }, nil- }- body := `{"node":"node1","temperature":"{}"}`- return &http.Response{- StatusCode: http.StatusOK,- Body: io.NopCloser(strings.NewReader(body)),- Header: make(http.Header),- }, nil- })-- _, err := client.GetTemperature("node1")- if err != nil {- t.Fatalf("Expected success after retry, got %v", err)- }- if attempts < 2 {- t.Fatalf("Expected retry after read error, got %d attempts", attempts)- }-}--func TestHTTPClient_HealthCheck_Success(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/health" {- t.Errorf("Path = %q, want /health", r.URL.Path)- }- if r.Header.Get("Authorization") != "Bearer test-token" {- t.Errorf("Authorization header missing or incorrect")- }- w.WriteHeader(http.StatusOK)- w.Write([]byte(`{"status":"ok"}`))- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "test-token")- err := client.HealthCheck()-- if err != nil {- t.Errorf("HealthCheck() error = %v", err)- }-}--func TestHTTPClient_HealthCheck_NotConfigured(t *testing.T) {- client := NewHTTPClient("", "")- err := client.HealthCheck()-- if err == nil {- t.Fatal("Expected error for unconfigured client")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", proxyErr.Type)- }-}--func TestHTTPClient_HealthCheck_RequestBuildError(t *testing.T) {- client := NewHTTPClient("http://[::1", "token")- err := client.HealthCheck()-- if err == nil {- t.Fatal("Expected error for request creation")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", proxyErr.Type)- }- if !strings.Contains(proxyErr.Message, "failed to create HTTP request") {- t.Errorf("Message = %q, want request creation failure", proxyErr.Message)- }-}--func TestHTTPClient_HealthCheck_ServerError(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusServiceUnavailable)- w.Write([]byte("service unavailable"))- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "token")- err := client.HealthCheck()-- if err == nil {- t.Fatal("Expected error for 503 response")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", proxyErr.Type)- }- // 5xx errors should be retryable- if !proxyErr.Retryable {- t.Error("5xx errors should be retryable")- }-}--func TestHTTPClient_HealthCheck_ConnectionRefused(t *testing.T) {- // Use a URL that will refuse connection- client := NewHTTPClient("http://127.0.0.1:1", "token")- client.httpClient.Timeout = 100 * time.Millisecond-- err := client.HealthCheck()-- if err == nil {- t.Fatal("Expected error for refused connection")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- if proxyErr.Type != ErrorTypeTransport {- t.Errorf("Type = %v, want ErrorTypeTransport", proxyErr.Type)- }- if !proxyErr.Retryable {- t.Error("Connection errors should be retryable")- }-}--func TestHTTPClient_HealthCheck_LongBody(t *testing.T) {- // Server returns a very long body that should be limited- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusBadGateway)- // Write more than 1024 bytes- for i := 0; i < 200; i++ {- w.Write([]byte("error message "))- }- }))- defer server.Close()-- client := NewHTTPClient(server.URL, "token")- err := client.HealthCheck()-- if err == nil {- t.Fatal("Expected error")- }-- proxyErr, ok := err.(*ProxyError)- if !ok {- t.Fatalf("Expected *ProxyError, got %T", err)- }- // Body should be limited to 1024 bytes- if len(proxyErr.Message) > 1100 { // Some overhead for HTTP status prefix- t.Errorf("Message too long: %d bytes", len(proxyErr.Message))- }-}--func TestHTTPClient_Fields(t *testing.T) {- client := &HTTPClient{- baseURL: "https://test.example.com",- authToken: "secret",- timeout: 60 * time.Second,- }-- if client.baseURL != "https://test.example.com" {- t.Errorf("baseURL = %q, want https://test.example.com", client.baseURL)- }- if client.authToken != "secret" {- t.Errorf("authToken = %q, want secret", client.authToken)- }- if client.timeout != 60*time.Second {- t.Errorf("timeout = %v, want 60s", client.timeout)- }-}--type roundTripperFunc func(*http.Request) (*http.Response, error)--func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) {- return f(r)-}--type errReadCloser struct{}--func (errReadCloser) Read(p []byte) (int, error) {- return 0, errors.New("read failed")-}--func (errReadCloser) Close() error {- return nil-}diff --git a/scripts/create-sensor-user.sh b/scripts/create-sensor-user.shdeleted file mode 100755index 9bdb2e238d..0000000000--- a/scripts/create-sensor-user.sh+++ /dev/null@@ -1,54 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--if [[ $EUID -ne 0 ]]; then- echo "Run as root." >&2- exit 1-fi--SERVICE_USER="pulse-sensor"-SERVICE_GROUP="$SERVICE_USER"-HOME_DIR="/opt/pulse/sensor-proxy"-BIN_DIR="$HOME_DIR/bin"-CONFIG_DIR="$HOME_DIR/etc"-SSH_DIR="$HOME_DIR/.ssh"-LOG_DIR="/var/log/pulse/sensor-proxy"-SUDOERS_FILE="/etc/sudoers.d/pulse-sensor-proxy"-NOLOGIN_SHELL="/usr/sbin/nologin"--if id -u "$SERVICE_USER" >/dev/null 2>&1; then- usermod --home "$HOME_DIR" --shell "$NOLOGIN_SHELL" "$SERVICE_USER"-else- useradd --system --home "$HOME_DIR" --shell "$NOLOGIN_SHELL" --user-group "$SERVICE_USER"-fi--install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 "$HOME_DIR"-install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 "$BIN_DIR"-install -d -o root -g "$SERVICE_GROUP" -m 0750 "$CONFIG_DIR"-install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0700 "$SSH_DIR"-install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 "$LOG_DIR"--TMP_SUDOERS="$(mktemp)"-trap 'rm -f "$TMP_SUDOERS"' EXIT--cat >"$TMP_SUDOERS" <<'EOF'-pulse-sensor ALL=(root) NOPASSWD: /usr/bin/sensors, /usr/sbin/ipmitool-EOF--install -o root -g root -m 0440 "$TMP_SUDOERS" "$SUDOERS_FILE"--if ! visudo -cf "$SUDOERS_FILE" >/dev/null; then- echo "sudoers validation failed" >&2- exit 1-fi--echo "User $(id "$SERVICE_USER")"-namei -om "$BIN_DIR" >/dev/null-namei -om "$CONFIG_DIR" >/dev/null-namei -om "$SSH_DIR" >/dev/null-namei -om "$LOG_DIR" >/dev/null--echo "Sudo privileges for $SERVICE_USER:"-sudo -l -U "$SERVICE_USER" || true--echo "pulse-sensor service account ready."diff --git a/scripts/harden-sensor-proxy.sh b/scripts/harden-sensor-proxy.shdeleted file mode 100755index 81f2b3f0cf..0000000000--- a/scripts/harden-sensor-proxy.sh+++ /dev/null@@ -1,38 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--FORCE_COMMAND="${FORCE_COMMAND:-/opt/pulse/bin/sensor-proxy-wrapper}"-CONF_PATH="/etc/ssh/sshd_config.d/pulse-sensor-proxy.conf"--if [[ ! -x "$FORCE_COMMAND" ]]; then- echo "Error: FORCE_COMMAND '$FORCE_COMMAND' not found or not executable" >&2- exit 1-fi--TMP_CONF="$(mktemp)"-trap 'rm -f "$TMP_CONF"' EXIT--cat >"$TMP_CONF" <<EOF-# Hardening for Pulse sensor proxy access-PasswordAuthentication no-KbdInteractiveAuthentication no-ChallengeResponseAuthentication no-PermitRootLogin no-AllowAgentForwarding no-AllowTcpForwarding no-PermitTunnel no-X11Forwarding no-PermitUserEnvironment no-ForceCommand $FORCE_COMMAND-EOF--install -o root -g root -m 0644 "$TMP_CONF" "$CONF_PATH"--sshd -t-systemctl reload sshd--echo "sshd hardening applied to $CONF_PATH"--# Verification-echo "Verifying hardening settings:"-sshd -T | grep -E 'passwordauthentication|allowagentforwarding|allowtcpforwarding|x11forwarding|permittunnel' || truediff --git a/scripts/install-sensor-proxy.sh b/scripts/install-sensor-proxy.shdeleted file mode 100755index d571ff3f7e..0000000000--- a/scripts/install-sensor-proxy.sh+++ /dev/null@@ -1,3680 +0,0 @@-#!/bin/bash--# install-sensor-proxy.sh - Installs pulse-sensor-proxy on Proxmox host for secure temperature monitoring-# Supports --uninstall [--purge] to remove the proxy and cleanup resources.-# This script is idempotent and can be safely re-run--set -euo pipefail--CONFIG_FILE="/etc/pulse-sensor-proxy/config.yaml"-ALLOWED_NODES_FILE="/etc/pulse-sensor-proxy/allowed_nodes.yaml"-MIN_ALLOWED_NODES_FILE_VERSION="v4.31.1"--ALLOWLIST_MODE="file"-INSTALLED_PROXY_VERSION=""--PENDING_CONTROL_PLANE_FILE="/etc/pulse-sensor-proxy/pending-control-plane.env"--# Colors for output-RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-NC='\033[0m' # No Color--print_info() {- if [ "$QUIET" != true ]; then- echo -e "${GREEN}[INFO]${NC} $1"- fi-}--print_warn() {- echo -e "${YELLOW}[WARN]${NC} $1"-}--print_error() {- echo -e "${RED}[ERROR]${NC} $1"-}--print_success() {- echo -e "${GREEN}✓${NC} $1"-}--normalize_semver() {- local ver="${1#v}"- ver="${ver%%+*}"- ver="${ver%%-*}"- printf '%s' "$ver"-}--semver_to_tuple() {- local ver- ver="$(normalize_semver "$1")"- IFS='.' read -r major minor patch <<< "$ver"- [[ -n "$major" ]] || major=0- [[ -n "$minor" ]] || minor=0- [[ -n "$patch" ]] || patch=0- printf '%s %s %s' "$major" "$minor" "$patch"-}--version_at_least() {- local current target- read -r c_major c_minor c_patch <<< "$(semver_to_tuple "$1")"- read -r t_major t_minor t_patch <<< "$(semver_to_tuple "$2")"-- if (( c_major > t_major )); then- return 0- elif (( c_major < t_major )); then- return 1- fi-- if (( c_minor > t_minor )); then- return 0- elif (( c_minor < t_minor )); then- return 1- fi-- if (( c_patch >= t_patch )); then- return 0- fi- return 1-}--detect_proxy_version() {- local binary="$1"- if [[ -x "$binary" ]]; then- "$binary" version 2>/dev/null | awk '/pulse-sensor-proxy/{print $2; exit}'- fi-}--config_command_supported() {- local subcommand="$1"- shift || true-- if [[ ! -x "$BINARY_PATH" ]]; then- return 1- fi-- local help_output- help_output="$("$BINARY_PATH" config --help 2>/dev/null || true)"- if ! grep -Eq "^[[:space:]]*${subcommand}([[:space:]]|$)" <<<"$help_output"; then- return 1- fi-- if [[ "$#" -eq 0 ]]; then- return 0- fi-- local sub_help- sub_help="$("$BINARY_PATH" config "$subcommand" --help 2>/dev/null || true)"- for flag in "$@"; do- if ! grep -q -- "$flag" <<<"$sub_help"; then- return 1- fi- done-- return 0-}--determine_allowlist_mode() {- INSTALLED_PROXY_VERSION="$(detect_proxy_version "$BINARY_PATH")"-- if [[ -z "$INSTALLED_PROXY_VERSION" ]]; then- # During initial install, version detection fails - that's expected- ALLOWLIST_MODE="file"- return- fi-- if version_at_least "$INSTALLED_PROXY_VERSION" "$MIN_ALLOWED_NODES_FILE_VERSION"; then- if [[ "$QUIET" != true ]]; then- print_info "Detected pulse-sensor-proxy ${INSTALLED_PROXY_VERSION} (allowed_nodes_file supported)"- fi- ALLOWLIST_MODE="file"- return- fi-- # Refuse to install/upgrade on unsupported versions- print_error "pulse-sensor-proxy ${INSTALLED_PROXY_VERSION} is too old (< ${MIN_ALLOWED_NODES_FILE_VERSION})"- print_error "File-based allowlist is now required. Please upgrade the proxy binary first."- print_error "Download latest from: https://github.com/rcourtman/Pulse/releases/latest"- exit 1-}--record_pending_control_plane() {- local mode="$1"- if [[ -z "$PULSE_SERVER" ]]; then- return- fi-- cat > "$PENDING_CONTROL_PLANE_FILE" <<EOF-PENDING_PULSE_SERVER="${PULSE_SERVER}"-PENDING_MODE="${mode}"-PENDING_STANDALONE="${STANDALONE}"-PENDING_HTTP_MODE="${HTTP_MODE}"-PENDING_HTTP_ADDR="${HTTP_ADDR}"-EOF- chmod 0600 "$PENDING_CONTROL_PLANE_FILE" 2>/dev/null || true-}--clear_pending_control_plane() {- rm -f "$PENDING_CONTROL_PLANE_FILE" 2>/dev/null || true-}--format_ip_to_cidr() {- local ip="$1"- if [[ -z "$ip" ]]; then- return- fi-- if [[ "$ip" == */* ]]; then- printf '%s' "$ip"- return- fi-- if [[ "$ip" == *:* ]]; then- printf '%s/128' "$ip"- else- printf '%s/32' "$ip"- fi-}--ensure_allowed_source_subnet() {- local subnet="$1"- if [[ -z "$subnet" || ! -f "$CONFIG_FILE" ]]; then- return- fi-- # Use robust binary config management if available- if config_command_supported "add-subnet"; then- if "$BINARY_PATH" config add-subnet "$subnet" --config "$CONFIG_FILE"; then- print_info "Added allowed_source_subnets entry ${subnet}"- return- else- print_warn "Failed to add subnet using binary; falling back to legacy method"- fi- fi-- local escaped_subnet="${subnet//\//\\/}"- if grep -Eq "^[[:space:]]+-[[:space:]]*${escaped_subnet}([[:space:]]|$)" "$CONFIG_FILE"; then- return- fi-- local tmp- tmp=$(mktemp)-- if grep -Eq "^[[:space:]]*allowed_source_subnets:" "$CONFIG_FILE"; then- awk -v subnet="$subnet" '-/^allowed_source_subnets:/ {print; in_block=1; indent=" "; next}-in_block && /^[[:space:]]+-/ {- # Capture indentation from existing items- if (!captured) {- match($0, /^[[:space:]]+/)- indent = substr($0, RSTART, RLENGTH)- captured = 1- }-}-in_block && /^[^[:space:]]/ {- if (!added) { printf("%s- %s\n", indent, subnet); added=1 }- in_block=0-}-{print}-END {- if (in_block && !added) {- printf("%s- %s\n", indent, subnet)- }-}-' "$CONFIG_FILE" > "$tmp"- else- cat "$CONFIG_FILE" > "$tmp"- {- echo ""- echo "allowed_source_subnets:"- echo " - $subnet"- } >> "$tmp"- fi-- if mv "$tmp" "$CONFIG_FILE"; then- print_info "Added allowed_source_subnets entry ${subnet}"- else- rm -f "$tmp"- print_warn "Failed to update allowed_source_subnets with ${subnet}"- fi-}---configure_local_authorized_key() {- local auth_line=$1- local auth_keys_file="/root/.ssh/authorized_keys"-- mkdir -p /root/.ssh- touch "$auth_keys_file"- chmod 600 "$auth_keys_file"-- # Extract just the key portion (without forced command prefix) for matching- # Format: command="...",options KEY_TYPE KEY_DATA COMMENT- local key_data- key_data=$(echo "$auth_line" | grep -oE 'ssh-[a-z0-9-]+ [A-Za-z0-9+/=]+')-- # Check if this exact key already exists (regardless of forced command)- if grep -qF "$key_data" "$auth_keys_file" 2>/dev/null; then- if [ "$QUIET" != true ]; then- print_success "SSH key already configured on localhost"- fi- return 0- fi-- # Key not present, add it- echo "${auth_line}" >>"$auth_keys_file"- if [ "$QUIET" != true ]; then- print_success "SSH key configured on localhost"- fi-}--configure_container_proxy_env() {- local socket_line="PULSE_SENSOR_PROXY_SOCKET=/mnt/pulse-proxy/pulse-sensor-proxy.sock"- if ! SOCKET_LINE="$socket_line" pct exec "$CTID" -- bash <<'EOF'-set -e-ENV_FILE="/etc/pulse/.env"-mkdir -p /etc/pulse-if [[ -f "$ENV_FILE" ]] && grep -q "^PULSE_SENSOR_PROXY_SOCKET=" "$ENV_FILE" 2>/dev/null; then- sed -i "s|^PULSE_SENSOR_PROXY_SOCKET=.*|$SOCKET_LINE|" "$ENV_FILE"-else- echo "$SOCKET_LINE" >> "$ENV_FILE"-fi-chmod 600 "$ENV_FILE" 2>/dev/null || true-chown pulse:pulse "$ENV_FILE" 2>/dev/null || true-EOF- then- print_warn "Unable to update /etc/pulse/.env inside container $CTID"- fi-}--ensure_allowed_nodes_file_reference() {- if [[ "$ALLOWLIST_MODE" != "file" ]]; then- if [[ -f "$CONFIG_FILE" ]]; then- sed -i '/^[[:space:]]*allowed_nodes_file:/d' "$CONFIG_FILE" 2>/dev/null || true- fi- return- fi-- normalize_allowed_nodes_section-}--remove_allowed_nodes_block() {- if [[ "$ALLOWLIST_MODE" != "file" ]]; then- return- fi-- normalize_allowed_nodes_section-}--normalize_allowed_nodes_section() {- if [[ ! -f "$CONFIG_FILE" ]]; then- return- fi-- if command -v python3 >/dev/null 2>&1; then- python3 - "$CONFIG_FILE" <<'PY'-import sys-from pathlib import Path--path = Path(sys.argv[1])-if not path.exists():- sys.exit(0)--lines = path.read_text().splitlines()-to_skip = set()-saved_comment = None--def capture_comment_block(idx: int):- global saved_comment- blanks = []- comments = []- j = idx - 1- while j >= 0 and lines[j].strip() == "":- blanks.append((j, lines[j]))- j -= 1- while j >= 0 and lines[j].lstrip().startswith("#"):- comments.append((j, lines[j]))- j -= 1- if not comments:- return []- blanks.reverse()- comments.reverse()- block = blanks + comments- for index, _ in block:- to_skip.add(index)- return [text for _, text in block]--i = 0-while i < len(lines):- line = lines[i]- stripped = line.lstrip()- if stripped.startswith("allowed_nodes_file:"):- comment_block = capture_comment_block(i)- if comment_block:- saved_comment = comment_block- to_skip.add(i)- i += 1- continue-- if stripped.startswith("allowed_nodes:"):- comment_block = capture_comment_block(i)- if comment_block:- saved_comment = comment_block- to_skip.add(i)- i += 1- while i < len(lines):- next_line = lines[i]- next_stripped = next_line.lstrip()- if (- next_stripped == ""- or next_stripped.startswith("#")- or next_stripped.startswith("-")- or next_line.startswith((" ", "\t"))- ):- to_skip.add(i)- i += 1- continue- break- continue-- i += 1--result = [text for idx, text in enumerate(lines) if idx not in to_skip]--default_comment = [- "# Cluster nodes (auto-discovered during installation)",- "# These nodes are allowed to request temperature data when cluster IPC validation is unavailable",-]--if saved_comment is None:- saved_comment = [""] + default_comment-else:- while saved_comment and saved_comment[-1].strip() == "":- saved_comment.pop()- if saved_comment and saved_comment[0].strip() != "":- saved_comment.insert(0, "")--if result and result[-1].strip() != "":- result.append("")--result.extend(saved_comment)-result.append('allowed_nodes_file: "/etc/pulse-sensor-proxy/allowed_nodes.yaml"')--path.write_text("\n".join(result).rstrip() + "\n")-PY- return- fi-- # Fallback when python3 is unavailable- sed -i '/^[[:space:]]*allowed_nodes:/,/^[^[:space:]]/d' "$CONFIG_FILE" 2>/dev/null || true- sed -i '/^[[:space:]]*allowed_nodes_file:/d' "$CONFIG_FILE" 2>/dev/null || true- if ! grep -q "allowed_nodes_file" "$CONFIG_FILE" 2>/dev/null; then- {- echo ""- echo "# Cluster nodes (auto-discovered during installation)"- echo "# These nodes are allowed to request temperature data when cluster IPC validation is unavailable"- echo 'allowed_nodes_file: "/etc/pulse-sensor-proxy/allowed_nodes.yaml"'- } >>"$CONFIG_FILE"- fi-}--migrate_inline_allowed_nodes_to_file() {- # Phase 2: Use config CLI for migration - no Python manipulation- if [[ ! -f "$CONFIG_FILE" ]]; then- return- fi-- if [[ ! -x "$BINARY_PATH" ]]; then- print_warn "Binary not available yet; skipping migration"- return- fi-- # Use CLI to atomically migrate inline nodes to file- if "$BINARY_PATH" config migrate-to-file --config "$CONFIG_FILE" --allowed-nodes "$ALLOWED_NODES_FILE"; then- print_success "Migration complete: inline allowed_nodes moved to file"- fi-}--write_inline_allowed_nodes() {- local comment_line="$1"- shift || true- local nodes=("$@")-- if [[ "$ALLOWLIST_MODE" != "inline" ]]; then- return- fi-- if ! command -v python3 >/dev/null 2>&1; then- print_warn "python3 is required to manage inline allowed_nodes; skipping update"- return- fi-- python3 - "$CONFIG_FILE" <<'PY'-import sys-from pathlib import Path--path = Path(sys.argv[1])-if not path.exists():- sys.exit(0)--lines = path.read_text().splitlines()-to_skip = set()--def capture_leading_comment(idx: int):- """Remove contiguous blank/comment lines immediately above idx."""- j = idx - 1- while j >= 0 and lines[j].strip() == "":- to_skip.add(j)- j -= 1- while j >= 0 and lines[j].lstrip().startswith("#"):- to_skip.add(j)- j -= 1--i = 0-while i < len(lines):- line = lines[i]- stripped = line.lstrip()- if stripped.startswith("allowed_nodes_file:"):- to_skip.add(i)- i += 1- continue- if stripped.startswith("allowed_nodes:"):- capture_leading_comment(i)- to_skip.add(i)- i += 1- while i < len(lines):- next_line = lines[i]- next_stripped = next_line.lstrip()- if (- next_stripped == ""- or next_stripped.startswith("#")- or next_stripped.startswith("-")- or next_line.startswith((" ", "\t"))- ):- to_skip.add(i)- i += 1- continue- break- continue- i += 1--result = [text for idx, text in enumerate(lines) if idx not in to_skip]-path.write_text("\n".join(result).rstrip() + "\n")-PY-- python3 - "$CONFIG_FILE" "$comment_line" "${nodes[@]}" <<'PY'-import sys-from pathlib import Path--path = Path(sys.argv[1])-comment = (sys.argv[2] or "").strip()-new_nodes = [n.strip() for n in sys.argv[3:] if n.strip()]--lines = []-if path.exists():- lines = path.read_text().splitlines()--skip = set()-existing = []-i = 0-while i < len(lines):- line = lines[i]- stripped = line.lstrip()- if stripped.startswith("allowed_nodes_file:"):- skip.add(i)- i += 1- continue- if stripped.startswith("allowed_nodes:"):- skip.add(i)- i += 1- while i < len(lines):- current = lines[i]- current_stripped = current.lstrip()- if current_stripped.startswith("-"):- value = current_stripped[1:].strip()- if value:- existing.append(value)- skip.add(i)- i += 1- continue- if (- current_stripped == "" or- current_stripped.startswith("#") or- current.startswith((" ", "\t"))- ):- skip.add(i)- i += 1- continue- break- continue- i += 1--result = [line for idx, line in enumerate(lines) if idx not in skip]--seen = set()-merged = []-for entry in existing + new_nodes:- normalized = entry.strip()- if not normalized:- continue- key = normalized.lower()- if key in seen:- continue- seen.add(key)- merged.append(normalized)--if merged:- if result and result[-1].strip() != "":- result.append("")- if comment:- result.append(f"# {comment}")- else:- result.append("# Cluster nodes (auto-discovered during installation)")- result.append("allowed_nodes:")- for entry in merged:- result.append(f" - {entry}")-- content = "\n".join(result).rstrip()- if content:- content += "\n"- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(content)-PY-}--cleanup_inline_allowed_nodes() {- if [[ "$ALLOWLIST_MODE" != "inline" ]]; then- return- fi- if ! command -v python3 >/dev/null 2>&1; then- return- fi- if [[ ! -f "$CONFIG_FILE" ]]; then- return- fi-- python3 - "$CONFIG_FILE" <<'PY'-import sys-from pathlib import Path--path = Path(sys.argv[1])-if not path.exists():- sys.exit(0)--lines = path.read_text().splitlines()-blocks = []-i = 0-while i < len(lines):- line = lines[i]- stripped = line.lstrip()- if stripped.startswith("allowed_nodes:"):- start = i- entries = []- j = i + 1- while j < len(lines):- nxt = lines[j]- nxt_stripped = nxt.lstrip()- if nxt_stripped.startswith("-"):- entries.append(nxt_stripped[1:].strip())- j += 1- continue- if (- nxt_stripped.startswith("#")- or nxt_stripped == ""- or nxt.startswith((" ", "\t"))- ):- j += 1- continue- break-- comment_indices = set()- comment_text = []- k = start - 1- while k >= 0 and lines[k].strip() == "":- comment_indices.add(k)- k -= 1- while k >= 0 and lines[k].lstrip().startswith("#"):- comment_indices.add(k)- comment_text.append(lines[k])- k -= 1- comment_text.reverse()-- blocks.append(- {- "start": start,- "end": j,- "comment_indices": comment_indices,- "comment_text": comment_text,- "entries": entries,- }- )- i = j- continue- i += 1--if len(blocks) <= 1:- sys.exit(0)--seen = set()-merged = []-for block in blocks:- for entry in block["entries"]:- key = entry.lower()- if not key or key in seen:- continue- seen.add(key)- merged.append(entry)--if not merged:- sys.exit(0)--first_block = blocks[0]-insert_at = min(- [first_block["start"]] + list(first_block["comment_indices"])-) if first_block["comment_indices"] else first_block["start"]--def build_comment():- if first_block["comment_text"]:- return first_block["comment_text"]- return ["# Cluster nodes (auto-discovered during installation)"]--comment_block = build_comment()-replacement = []-replacement.extend(comment_block)-if replacement and replacement[-1].strip() != "":- replacement.append("")-replacement.append("allowed_nodes:")-for entry in merged:- replacement.append(f" - {entry}")-replacement.append("")--indices_to_remove = set()-for block in blocks:- indices_to_remove.update(range(block["start"], block["end"]))- indices_to_remove.update(block["comment_indices"])--result = []-inserted = False-for idx, line in enumerate(lines):- if not inserted and idx == insert_at:- result.extend(replacement)- inserted = True- if idx in indices_to_remove:- continue- result.append(line)--if not inserted:- if result and result[-1].strip() != "":- result.append("")- result.extend(replacement)--content = "\n".join(result).rstrip() + "\n"-path.write_text(content)-PY-}--update_allowed_nodes() {- local comment_line="$1"- shift- local nodes=("$@")-- # Phase 2: Use config CLI exclusively - no shell/Python manipulation- # First, migrate any inline allowed_nodes to file mode (failures are fatal)- if ! "$BINARY_PATH" config migrate-to-file --config "$CONFIG_FILE" --allowed-nodes "$ALLOWED_NODES_FILE"; then- print_error "Failed to migrate config to file mode"- return 1- fi-- # Build --merge flags for the CLI- local merge_args=()- for node in "${nodes[@]}"; do- if [[ -n "$node" ]]; then- merge_args+=(--merge "$node")- fi- done-- if [[ ${#merge_args[@]} -eq 0 ]]; then- return- fi-- # Use the config CLI for atomic, locked updates- if "$BINARY_PATH" config set-allowed-nodes --allowed-nodes "$ALLOWED_NODES_FILE" "${merge_args[@]}"; then- chmod 0644 "$ALLOWED_NODES_FILE" 2>/dev/null || true- chown pulse-sensor-proxy:pulse-sensor-proxy "$ALLOWED_NODES_FILE" 2>/dev/null || true- else- print_error "Failed to update allowed_nodes using config CLI"- return 1- fi-}----# Installation root - writable location that works on read-only /usr systems-INSTALL_ROOT="/opt/pulse/sensor-proxy"--# Binaries and scripts (in writable location)-BINARY_PATH="${INSTALL_ROOT}/bin/pulse-sensor-proxy"-WRAPPER_SCRIPT="${INSTALL_ROOT}/bin/pulse-sensor-wrapper.sh"-CLEANUP_SCRIPT_PATH="${INSTALL_ROOT}/bin/pulse-sensor-cleanup.sh"-SELFHEAL_SCRIPT="${INSTALL_ROOT}/bin/pulse-sensor-proxy-selfheal.sh"-STORED_INSTALLER="${INSTALL_ROOT}/install-sensor-proxy.sh"--# System configuration (standard locations)-SERVICE_PATH="/etc/systemd/system/pulse-sensor-proxy.service"-RUNTIME_DIR="/run/pulse-sensor-proxy"-SOCKET_PATH="${RUNTIME_DIR}/pulse-sensor-proxy.sock"-WORK_DIR="/var/lib/pulse-sensor-proxy"-SSH_DIR="${WORK_DIR}/ssh"-CONFIG_DIR="/etc/pulse-sensor-proxy"-CTID_FILE="${CONFIG_DIR}/ctid"-CLEANUP_PATH_UNIT="/etc/systemd/system/pulse-sensor-cleanup.path"-CLEANUP_SERVICE_UNIT="/etc/systemd/system/pulse-sensor-cleanup.service"-CLEANUP_REQUEST_PATH="${WORK_DIR}/cleanup-request.json"-SERVICE_USER="pulse-sensor-proxy"-LOG_DIR="/var/log/pulse/sensor-proxy"-SELFHEAL_SERVICE_UNIT="/etc/systemd/system/pulse-sensor-proxy-selfheal.service"-SELFHEAL_TIMER_UNIT="/etc/systemd/system/pulse-sensor-proxy-selfheal.timer"-SCRIPT_SOURCE="$(readlink -f "${BASH_SOURCE[0]:-$0}" 2>/dev/null || printf '%s' "${BASH_SOURCE[0]:-$0}")"-SKIP_SELF_HEAL_SETUP="${PULSE_SENSOR_PROXY_SELFHEAL:-false}"-GITHUB_REPO="rcourtman/Pulse"-LATEST_RELEASE_TAG=""-REQUESTED_VERSION=""-INSTALLER_CACHE_REASON=""-DEFER_SOCKET_VERIFICATION=false--# Get cluster node names via Proxmox API (pvesh) - returns one hostname per line-# Falls back to pvecm CLI parsing if pvesh unavailable-get_cluster_node_names() {- # Try pvesh API first (structured JSON, version-stable)- if command -v pvesh >/dev/null 2>&1; then- local json_output- if json_output=$(pvesh get /cluster/status --output-format json 2>/dev/null); then- # Parse JSON: extract "name" from entries where "type" is "node"- # Using python3 for reliable JSON parsing (always available on Proxmox)- if command -v python3 >/dev/null 2>&1; then- local names- names=$(echo "$json_output" | python3 -c '-import sys, json-try:- data = json.load(sys.stdin)- for item in data:- if item.get("type") == "node" and item.get("name"):- print(item["name"])-except:- pass-' 2>/dev/null)- if [[ -n "$names" ]]; then- echo "$names"- return 0- fi- fi- fi- fi-- # Fallback: parse pvecm nodes CLI output (fragile, position-dependent)- if command -v pvecm >/dev/null 2>&1; then- pvecm nodes 2>/dev/null | awk '/^[[:space:]]+[0-9]/ && !/Qdevice/ {print $4}' || true- return 0- fi-- return 1-}--cleanup_local_authorized_keys() {- local auth_keys_file="/root/.ssh/authorized_keys"- if [[ ! -f "$auth_keys_file" ]]; then- return- fi-- if grep -q '# pulse-\(managed\|proxy\)-key$' "$auth_keys_file"; then- if sed -i -e '/# pulse-managed-key$/d' -e '/# pulse-proxy-key$/d' "$auth_keys_file"; then- print_info "Removed Pulse SSH keys from ${auth_keys_file}"- else- print_warn "Failed to clean Pulse SSH keys from ${auth_keys_file}"- fi- fi-}--cleanup_cluster_authorized_keys_manual() {- local nodes=()- # Use get_cluster_node_names helper (prefers pvesh API, falls back to pvecm CLI)- while IFS= read -r nodename; do- [[ -z "$nodename" ]] && continue- local resolved_ip- resolved_ip=$(getent hosts "$nodename" 2>/dev/null | awk '{print $1; exit}')- [[ -n "$resolved_ip" ]] && nodes+=("$resolved_ip")- done < <(get_cluster_node_names 2>/dev/null || true)- # Fallback to pvecm status if hostname resolution didn't work- if [[ ${#nodes[@]} -eq 0 ]] && command -v pvecm >/dev/null 2>&1; then- while IFS= read -r node_ip; do- [[ -n "$node_ip" ]] && nodes+=("$node_ip")- done < <(pvecm status 2>/dev/null | grep -vEi "qdevice" | awk '/0x[0-9a-f]+.*[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ {for(i=1;i<=NF;i++) if($i ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) print $i}' || true)- fi-- if [[ ${#nodes[@]} -eq 0 ]]; then- cleanup_local_authorized_keys- return- fi-- local local_ips- local_ips="$(hostname -I 2>/dev/null || echo "")"- local local_hostnames- local_hostnames="$(hostname 2>/dev/null || echo "") $(hostname -f 2>/dev/null || echo "")"-- for node_ip in "${nodes[@]}"; do- local is_local=false- for local_ip in $local_ips; do- if [[ "$node_ip" == "$local_ip" ]]; then- is_local=true- break- fi- done-- if [[ " $local_hostnames " == *" $node_ip "* ]]; then- is_local=true- fi-- if [[ "$node_ip" == "127.0.0.1" || "$node_ip" == "localhost" ]]; then- is_local=true- fi-- if [[ "$is_local" == true ]]; then- cleanup_local_authorized_keys- continue- fi-- print_info "Removing Pulse SSH keys from node ${node_ip}"- if ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 root@"$node_ip" \- "sed -i -e '/# pulse-managed-key\$/d' -e '/# pulse-proxy-key\$/d' /root/.ssh/authorized_keys" 2>/dev/null; then- print_info " SSH keys cleaned on ${node_ip}"- else- print_warn " Unable to clean Pulse SSH keys on ${node_ip}"- fi- done-- cleanup_local_authorized_keys-}--determine_installer_ref() {- if [[ -n "$REQUESTED_VERSION" && "$REQUESTED_VERSION" != "latest" && "$REQUESTED_VERSION" != "main" ]]; then- printf '%s' "$REQUESTED_VERSION"- return 0- fi-- if [[ -n "$LATEST_RELEASE_TAG" ]]; then- printf '%s' "$LATEST_RELEASE_TAG"- return 0- fi-- if [[ "$REQUESTED_VERSION" == "main" ]]; then- printf 'main'- return 0- fi-- printf 'main'-}--cache_installer_for_self_heal() {- INSTALLER_CACHE_REASON=""- install -d "${INSTALL_ROOT}"-- local source_issue=""- if [[ -n "$SCRIPT_SOURCE" && -f "$SCRIPT_SOURCE" ]]; then- if install -m 0755 "$SCRIPT_SOURCE" "$STORED_INSTALLER"; then- return 0- fi- source_issue="failed to copy ${SCRIPT_SOURCE}"- else- source_issue="no readable source"- fi-- local repo="${GITHUB_REPO:-rcourtman/Pulse}"- local ref- ref="$(determine_installer_ref)"- [[ -z "$ref" ]] && ref="main"-- local candidate_urls=()- if [[ "$ref" != "main" ]]; then- # Try specific version from releases first- candidate_urls+=("https://github.com/${repo}/releases/download/${ref}/install-sensor-proxy.sh")- fi- # Fall back to latest release- candidate_urls+=("https://github.com/${repo}/releases/latest/download/install-sensor-proxy.sh")-- local tmp_file- tmp_file=$(mktemp)- local tmp_err- tmp_err=$(mktemp)- local last_error=""-- for url in "${candidate_urls[@]}"; do- if curl --fail --silent --location --connect-timeout 10 --max-time 60 "$url" -o "$tmp_file" 2>"$tmp_err"; then- if install -m 0755 "$tmp_file" "$STORED_INSTALLER"; then- rm -f "$tmp_file" "$tmp_err"- if [[ "$QUIET" != true ]]; then- print_info "Cached installer script for self-heal from ${url}"- fi- return 0- fi- last_error="failed to write cached installer to ${STORED_INSTALLER}"- break- fi-- if [[ -s "$tmp_err" ]]; then- last_error="$(cat "$tmp_err")"- else- last_error="HTTP error"- fi- : >"$tmp_err"- done-- rm -f "$tmp_file" "$tmp_err"-- if [[ -n "$source_issue" && -n "$last_error" ]]; then- INSTALLER_CACHE_REASON="${source_issue}; download failed (${last_error})"- elif [[ -n "$source_issue" ]]; then- INSTALLER_CACHE_REASON="$source_issue"- elif [[ -n "$last_error" ]]; then- INSTALLER_CACHE_REASON="download failed (${last_error})"- else- INSTALLER_CACHE_REASON="unknown failure"- fi-- return 1-}--perform_uninstall() {- print_info "Starting pulse-sensor-proxy uninstall..."-- if command -v systemctl >/dev/null 2>&1; then- print_info "Stopping pulse-sensor-proxy service"- systemctl stop pulse-sensor-proxy 2>/dev/null || true- print_info "Disabling pulse-sensor-proxy service"- systemctl disable pulse-sensor-proxy 2>/dev/null || true-- print_info "Stopping cleanup path watcher"- systemctl stop pulse-sensor-cleanup.path 2>/dev/null || true- systemctl disable pulse-sensor-cleanup.path 2>/dev/null || true- systemctl stop pulse-sensor-cleanup.service 2>/dev/null || true- systemctl disable pulse-sensor-cleanup.service 2>/dev/null || true- else- print_warn "systemctl not available; skipping service disable"- fi-- if [[ -x "$CLEANUP_SCRIPT_PATH" ]]; then- print_info "Invoking cleanup script to remove Pulse SSH keys"- mkdir -p "$WORK_DIR"- cat > "$CLEANUP_REQUEST_PATH" <<'EOF'-{"host":""}-EOF- if "$CLEANUP_SCRIPT_PATH"; then- print_success "Cleanup script removed Pulse SSH keys"- else- print_warn "Cleanup script reported errors; attempting manual cleanup"- cleanup_cluster_authorized_keys_manual- fi- rm -f "$CLEANUP_REQUEST_PATH"- else- cleanup_cluster_authorized_keys_manual- fi-- if [[ -f "$BINARY_PATH" ]]; then- rm -f "$BINARY_PATH"- print_success "Removed binary ${BINARY_PATH}"- else- print_info "Binary already absent at ${BINARY_PATH}"- fi-- if [[ -f "$SERVICE_PATH" ]]; then- rm -f "$SERVICE_PATH"- print_success "Removed service unit ${SERVICE_PATH}"- fi-- if [[ -f "$CLEANUP_PATH_UNIT" ]]; then- rm -f "$CLEANUP_PATH_UNIT"- print_success "Removed cleanup path unit ${CLEANUP_PATH_UNIT}"- fi-- if [[ -f "$CLEANUP_SERVICE_UNIT" ]]; then- rm -f "$CLEANUP_SERVICE_UNIT"- print_success "Removed cleanup service unit ${CLEANUP_SERVICE_UNIT}"- fi-- if [[ -f "$SELFHEAL_TIMER_UNIT" ]]; then- systemctl stop pulse-sensor-proxy-selfheal.timer 2>/dev/null || true- systemctl disable pulse-sensor-proxy-selfheal.timer 2>/dev/null || true- rm -f "$SELFHEAL_TIMER_UNIT"- print_success "Removed self-heal timer ${SELFHEAL_TIMER_UNIT}"- fi-- if [[ -f "$SELFHEAL_SERVICE_UNIT" ]]; then- systemctl stop pulse-sensor-proxy-selfheal.service 2>/dev/null || true- systemctl disable pulse-sensor-proxy-selfheal.service 2>/dev/null || true- rm -f "$SELFHEAL_SERVICE_UNIT"- print_success "Removed self-heal service ${SELFHEAL_SERVICE_UNIT}"- fi-- if [[ -f "$SELFHEAL_SCRIPT" ]]; then- rm -f "$SELFHEAL_SCRIPT"- print_success "Removed self-heal helper ${SELFHEAL_SCRIPT}"- fi-- if [[ -f "$STORED_INSTALLER" ]]; then- rm -f "$STORED_INSTALLER"- print_success "Removed cached installer ${STORED_INSTALLER}"- fi-- if [[ -f "$CTID_FILE" ]]; then- rm -f "$CTID_FILE"- fi-- rm -f "$PENDING_CONTROL_PLANE_FILE" 2>/dev/null || true-- if command -v systemctl >/dev/null 2>&1; then- systemctl daemon-reload 2>/dev/null || true- fi-- rm -f "$CLEANUP_SCRIPT_PATH" "$CLEANUP_REQUEST_PATH" 2>/dev/null || true- rm -f "$SOCKET_PATH" 2>/dev/null || true- rm -rf "$RUNTIME_DIR" 2>/dev/null || true-- # Always remove HTTP secrets and TLS material (security best practice)- if [[ -f "/etc/pulse-sensor-proxy/.http-auth-token" ]]; then- rm -f "/etc/pulse-sensor-proxy/.http-auth-token"- print_success "Removed HTTP auth token"- fi- if [[ -d "/etc/pulse-sensor-proxy/tls" ]]; then- rm -rf "/etc/pulse-sensor-proxy/tls"- print_success "Removed TLS certificates"- fi-- # Check for and remove LXC bind mounts on any containers- if command -v pct >/dev/null 2>&1; then- print_info "Checking for LXC bind mounts..."- # Find all containers with pulse-sensor-proxy bind mounts- for ctid in $(pct list | awk 'NR>1 {print $1}'); do- if grep -q "pulse-sensor-proxy" /etc/pve/lxc/${ctid}.conf 2>/dev/null; then- CONTAINER_NAME=$(pct list | awk -v id="$ctid" '$1==id {print $3}')- print_info "Found bind mount in container $ctid ($CONTAINER_NAME)"- if sed -i '/pulse-sensor-proxy/d' /etc/pve/lxc/${ctid}.conf 2>/dev/null; then- print_success "Removed bind mount from container $ctid ($CONTAINER_NAME)"- print_warn "Container restart required for change to take effect"- else- print_warn "Failed to remove bind mount from container $ctid"- fi- fi- done- fi-- if [[ "$PURGE" == true ]]; then- print_info "Purging Pulse sensor proxy state"- rm -rf "$WORK_DIR" "$CONFIG_DIR" 2>/dev/null || true- if [[ -d "$LOG_DIR" ]]; then- print_info "Removing log directory ${LOG_DIR}"- fi- rm -rf "$LOG_DIR" 2>/dev/null || true-- if id -u "$SERVICE_USER" >/dev/null 2>&1; then- if userdel --remove "$SERVICE_USER" 2>/dev/null; then- print_success "Removed service user ${SERVICE_USER}"- elif userdel "$SERVICE_USER" 2>/dev/null; then- print_success "Removed service user ${SERVICE_USER}"- else- print_warn "Failed to remove service user ${SERVICE_USER}"- fi- fi-- if getent group "$SERVICE_USER" >/dev/null 2>&1; then- if groupdel "$SERVICE_USER" 2>/dev/null; then- print_success "Removed service group ${SERVICE_USER}"- else- print_warn "Failed to remove service group ${SERVICE_USER}"- fi- fi- else- if [[ -d "$WORK_DIR" ]]; then- print_info "Preserving data directory ${WORK_DIR} (use --purge to remove)"- fi- if [[ -d "$CONFIG_DIR" ]]; then- print_info "Preserving config directory ${CONFIG_DIR} (use --purge to remove)"- fi- if [[ -d "$LOG_DIR" ]]; then- print_info "Preserving log directory ${LOG_DIR} (use --purge to remove)"- fi- fi-- print_success "pulse-sensor-proxy uninstall complete"-}--# Parse arguments first to check for standalone mode-CTID=""-VERSION=""-LOCAL_BINARY=""-QUIET=false-PULSE_SERVER=""-STANDALONE=false-HTTP_MODE=false-HTTP_ADDR="0.0.0.0:8443" # Explicitly IPv4 to avoid IPv6-only binding on some systems-FALLBACK_BASE="${PULSE_SENSOR_PROXY_FALLBACK_URL:-}"-SKIP_RESTART=false-RESTART_PULSE=false-UNINSTALL=false-PURGE=false-CONTROL_PLANE_TOKEN=""-CONTROL_PLANE_REFRESH=""-PROXY_URL="" # Manual override for advertised proxy URL-SHORT_HOSTNAME=$(hostname -s 2>/dev/null || hostname | cut -d'.' -f1)--while [[ $# -gt 0 ]]; do- case $1 in- --ctid)- CTID="$2"- shift 2- ;;- --version)- VERSION="$2"- shift 2- ;;- --local-binary)- LOCAL_BINARY="$2"- shift 2- ;;- --pulse-server)- PULSE_SERVER="$2"- shift 2- ;;- --quiet)- QUIET=true- shift- ;;- --standalone)- STANDALONE=true- shift- ;;- --http-mode)- HTTP_MODE=true- shift- ;;- --http-addr)- HTTP_ADDR="$2"- shift 2- ;;- --skip-restart)- SKIP_RESTART=true- shift- ;;- --restart-pulse)- RESTART_PULSE=true- shift- ;;- --uninstall)- UNINSTALL=true- shift- ;;- --purge)- PURGE=true- shift- ;;- --proxy-url)- PROXY_URL="$2"- shift 2- ;;- *)- print_error "Unknown option: $1"- exit 1- ;;- esac-done--if [[ "$PURGE" == true && "$UNINSTALL" != true ]]; then- print_warn "--purge is only valid together with --uninstall; ignoring"- PURGE=false-fi--if [[ "$UNINSTALL" == true ]]; then- perform_uninstall- exit 0-fi--REQUESTED_VERSION="${VERSION:-latest}"--# If --pulse-server was provided, use it as the fallback base-if [[ -n "$PULSE_SERVER" ]]; then- FALLBACK_BASE="${PULSE_SERVER}/api/install/pulse-sensor-proxy"-fi--# Preflight checks-if [[ $EUID -ne 0 ]]; then- print_error "This script must be run as root"- print_error "Use: sudo $0 $*"- exit 1-fi--# Check required commands-REQUIRED_CMDS="curl openssl systemctl useradd groupadd install chmod chown mkdir jq"-if [[ "$HTTP_MODE" == true ]]; then- REQUIRED_CMDS="$REQUIRED_CMDS hostname awk"-fi-if [[ "$STANDALONE" == false ]]; then- REQUIRED_CMDS="$REQUIRED_CMDS pvecm"-fi--for cmd in $REQUIRED_CMDS; do- if ! command -v "$cmd" >/dev/null 2>&1; then- print_error "Required command not found: $cmd"- print_error "Please install it and try again"- exit 1- fi-done--# Check if running on Proxmox host (only required for LXC mode)-if [[ "$STANDALONE" == false ]]; then- if ! command -v pvecm >/dev/null 2>&1; then- print_error "This script must be run on a Proxmox VE host"- exit 1- fi-fi--# Validate arguments based on mode-CONTAINER_ON_THIS_NODE=true-if [[ "$STANDALONE" == false ]]; then- if [[ -z "$CTID" ]]; then- print_error "Missing required argument: --ctid <container-id>"- echo "Usage: $0 --ctid <container-id> [--pulse-server <url>] [--version <version>] [--local-binary <path>]"- echo " Or: $0 --standalone [--pulse-server <url>] [--version <version>] [--local-binary <path>]"- echo " Or: $0 --uninstall [--purge]"- exit 1- fi-- # Verify container exists on this node- if ! pct status "$CTID" >/dev/null 2>&1; then- # Container doesn't exist locally - might be on another cluster node- # Continue installation for host temperature monitoring, skip container-specific config- print_warn "Container $CTID does not exist on this node"- print_warn "Will install sensor-proxy for host temperature monitoring only"- print_warn "Container-specific socket mount configuration will be skipped"- CONTAINER_ON_THIS_NODE=false- fi-fi--if [[ "$STANDALONE" == true ]]; then- print_info "Installing pulse-sensor-proxy for standalone/Docker deployment"-elif [[ "$CONTAINER_ON_THIS_NODE" == true ]]; then- print_info "Installing pulse-sensor-proxy for container $CTID"-else- print_info "Installing pulse-sensor-proxy for host monitoring (container $CTID on another node)"-fi--# Create dedicated service account if it doesn't exist-if ! id -u pulse-sensor-proxy >/dev/null 2>&1; then- print_info "Creating pulse-sensor-proxy service account..."- useradd --system --user-group --no-create-home --shell /usr/sbin/nologin pulse-sensor-proxy- print_info "Service account created"-fi--# Ensure group exists (in case user was created without it)-if ! getent group pulse-sensor-proxy >/dev/null 2>&1; then- print_info "Creating pulse-sensor-proxy group..."- groupadd --system pulse-sensor-proxy- usermod -aG pulse-sensor-proxy pulse-sensor-proxy-fi--# Add pulse-sensor-proxy user to www-data group for Proxmox IPC access (pvecm commands)-if ! groups pulse-sensor-proxy | grep -q '\bwww-data\b'; then- print_info "Adding pulse-sensor-proxy to www-data group for Proxmox IPC access..."- usermod -aG www-data pulse-sensor-proxy-fi--# Create installation directories before binary installation (handles fresh installs and upgrades)-print_info "Setting up installation directories..."-install -d -o root -g root -m 0755 "${INSTALL_ROOT}"-install -d -o root -g root -m 0755 "${INSTALL_ROOT}/bin"--# Install binary - either from local file or download from GitHub-if [[ -n "$LOCAL_BINARY" ]]; then- # Use local binary for testing- print_info "Using local binary: $LOCAL_BINARY"- if [[ ! -f "$LOCAL_BINARY" ]]; then- print_error "Local binary not found: $LOCAL_BINARY"- exit 1- fi- cp "$LOCAL_BINARY" "$BINARY_PATH"- chmod +x "$BINARY_PATH"- print_info "Binary installed to $BINARY_PATH"-else- # Detect architecture- ARCH=$(uname -m)- case $ARCH in- x86_64)- BINARY_NAME="pulse-sensor-proxy-linux-amd64"- ARCH_LABEL="linux-amd64"- ;;- aarch64|arm64)- BINARY_NAME="pulse-sensor-proxy-linux-arm64"- ARCH_LABEL="linux-arm64"- ;;- armv7l|armhf)- BINARY_NAME="pulse-sensor-proxy-linux-armv7"- ARCH_LABEL="linux-armv7"- ;;- armv6l)- BINARY_NAME="pulse-sensor-proxy-linux-armv6"- ARCH_LABEL="linux-armv6"- ;;- i386|i686)- BINARY_NAME="pulse-sensor-proxy-linux-386"- ARCH_LABEL="linux-386"- ;;- *)- print_error "Unsupported architecture: $ARCH"- exit 1- ;;- esac-- DOWNLOAD_SUCCESS=false- ATTEMPTED_SOURCES=()-- fetch_latest_release_tag() {- local api_url="https://api.github.com/repos/$GITHUB_REPO/releases?per_page=25"- local tmp_err- tmp_err=$(mktemp)- local response- response=$(curl --fail --silent --location --connect-timeout 10 --max-time 30 "$api_url" 2>"$tmp_err")- local status=$?- if [[ $status -ne 0 ]]; then- if [[ -s "$tmp_err" ]]; then- print_warn "Failed to resolve latest GitHub release: $(cat "$tmp_err")"- else- print_warn "Failed to resolve latest GitHub release (HTTP $status)"- fi- rm -f "$tmp_err"- return 1- fi- rm -f "$tmp_err"-- local tag=""- if command -v python3 >/dev/null 2>&1; then- if ! tag=$(printf '%s' "$response" | python3 -c '-import json-import sys--binary_name = sys.argv[1]-arch_label = sys.argv[2]-tar_suffix = arch_label or ""--def has_sensor_assets(tag, assets):- names = {asset.get("name") for asset in assets if isinstance(asset, dict) and asset.get("name")}- if binary_name and binary_name in names:- return True- if tar_suffix:- tarball = f"pulse-{tag}-{tar_suffix}.tar.gz"- if tarball in names or f"{tarball}.sha256" in names:- return True- universal = f"pulse-{tag}.tar.gz"- if universal in names or f"{universal}.sha256" in names:- return True- return False--try:- releases = json.load(sys.stdin)-except json.JSONDecodeError:- sys.exit(1)--for release in releases:- if release.get("prerelease"):- continue- tag_name = (release.get("tag_name") or "").strip()- if not tag_name or tag_name.startswith("helm-chart"):- continue- assets = release.get("assets") or []- if has_sensor_assets(tag_name, assets):- sys.stdout.write(tag_name)- sys.exit(0)--sys.exit(0)-' "$BINARY_NAME" "$ARCH_LABEL"); then- print_warn "Failed to parse GitHub releases via python3; falling back to heuristic tag detection"- tag=""- fi- fi-- if [[ -z "$tag" ]]; then- # Fallback: use grep-based parsing, filtering out helm-chart and common prerelease patterns- tag=$(printf '%s\n' "$response" | grep -o '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' | cut -d'"' -f4 | grep -Ev '^helm-chart-|-rc\.|-(alpha|beta|rc)[0-9]*$' | head -n 1 || true)- fi-- if [[ -n "$tag" ]]; then- tag="${tag%%$'\n'*}"- fi-- if [[ -z "$tag" ]]; then- print_warn "Could not determine latest GitHub release for pulse-sensor-proxy"- return 1- fi- LATEST_RELEASE_TAG="$tag"- return 0- }-- attempt_github_asset_or_tarball() {- local tag="$1"- [[ -z "$tag" ]] && return 1-- local asset_url="https://github.com/$GITHUB_REPO/releases/download/${tag}/${BINARY_NAME}"- ATTEMPTED_SOURCES+=("GitHub release asset ${tag}")- print_info "Downloading $BINARY_NAME from GitHub release ${tag}..."- local tmp_err- tmp_err=$(mktemp)- if curl --fail --silent --location --connect-timeout 10 --max-time 120 "$asset_url" -o "$BINARY_PATH.tmp" 2>"$tmp_err"; then- rm -f "$tmp_err"- DOWNLOAD_SUCCESS=true- return 0- fi-- local asset_error=""- if [[ -s "$tmp_err" ]]; then- asset_error="$(cat "$tmp_err")"- fi- rm -f "$tmp_err"- rm -f "$BINARY_PATH.tmp" 2>/dev/null || true-- local tarball_name="pulse-${tag}-linux-${ARCH_LABEL#linux-}.tar.gz"- local tarball_url="https://github.com/$GITHUB_REPO/releases/download/${tag}/${tarball_name}"- ATTEMPTED_SOURCES+=("GitHub release tarball ${tarball_name}")- print_info "Downloading ${tarball_name} to extract pulse-sensor-proxy..."- tmp_err=$(mktemp)- local tarball_tmp- tarball_tmp=$(mktemp)- if curl --fail --silent --location --connect-timeout 10 --max-time 240 "$tarball_url" -o "$tarball_tmp" 2>"$tmp_err"; then- if tar -tzf "$tarball_tmp" >/dev/null 2>&1 && tar -xzf "$tarball_tmp" -C "$(dirname "$tarball_tmp")" ./bin/pulse-sensor-proxy >/dev/null 2>&1; then- mv "$(dirname "$tarball_tmp")/bin/pulse-sensor-proxy" "$BINARY_PATH.tmp"- rm -f "$tarball_tmp" "$tmp_err"- DOWNLOAD_SUCCESS=true- return 0- else- print_warn "Release tarball did not contain expected ./bin/pulse-sensor-proxy"- fi- else- if [[ -s "$tmp_err" ]]; then- print_warn "Tarball download failed: $(cat "$tmp_err")"- else- print_warn "Tarball download failed (HTTP error)"- fi- fi- rm -f "$tarball_tmp" "$tmp_err"- if [[ -n "$asset_error" ]]; then- print_warn "GitHub release asset error: $asset_error"- fi- return 1- }-- if [[ "$REQUESTED_VERSION" == "latest" || "$REQUESTED_VERSION" == "main" || -z "$REQUESTED_VERSION" ]]; then- if fetch_latest_release_tag; then- attempt_github_asset_or_tarball "$LATEST_RELEASE_TAG" || true- fi- else- attempt_github_asset_or_tarball "$REQUESTED_VERSION" || true- fi-- if [[ "$DOWNLOAD_SUCCESS" != true ]] && [[ -n "$FALLBACK_BASE" ]]; then- fallback_url="$FALLBACK_BASE"- if [[ "$fallback_url" == *"?"* ]]; then- fallback_url="$fallback_url"- elif [[ "$fallback_url" == *"pulse-sensor-proxy-"* ]]; then- fallback_url="${fallback_url}"- else- fallback_url="${fallback_url%/}?arch=${ARCH_LABEL}"- fi-- ATTEMPTED_SOURCES+=("Fallback ${fallback_url}")- print_info "Downloading $BINARY_NAME from fallback source..."- fallback_err=$(mktemp)- if curl --fail --silent --location --connect-timeout 10 --max-time 120 "$fallback_url" -o "$BINARY_PATH.tmp" 2>"$fallback_err"; then- rm -f "$fallback_err"- DOWNLOAD_SUCCESS=true- else- if [[ -s "$fallback_err" ]]; then- print_error "Fallback download failed: $(cat "$fallback_err")"- else- print_error "Fallback download failed (HTTP error)"- fi- rm -f "$fallback_err"- rm -f "$BINARY_PATH.tmp" 2>/dev/null || true- fi- fi-- # NOTE: Previous versions attempted pct pull from container paths like- # /opt/pulse/bin/pulse-sensor-proxy-linux-amd64, but these paths don't exist- # in Pulse containers. Removed to prevent spurious PVE task errors (#817).-- if [[ "$DOWNLOAD_SUCCESS" != true ]]; then- print_error "Unable to download pulse-sensor-proxy binary."- if [[ ${#ATTEMPTED_SOURCES[@]} -gt 0 ]]; then- print_error "Sources attempted:"- for src in "${ATTEMPTED_SOURCES[@]}"; do- print_error " - $src"- done- fi- print_error "Publish a GitHub release with binary assets or ensure a Pulse server is reachable."- exit 1- fi-- chmod +x "$BINARY_PATH.tmp"- mv "$BINARY_PATH.tmp" "$BINARY_PATH"- print_info "Binary installed to $BINARY_PATH"-fi--# Create remaining directories with proper ownership (handles fresh installs and upgrades)-print_info "Setting up service directories with proper ownership..."-if ! install -d -o pulse-sensor-proxy -g pulse-sensor-proxy -m 0750 /var/lib/pulse-sensor-proxy; then- print_error "Failed to create /var/lib/pulse-sensor-proxy"- exit 1-fi-if ! install -d -o pulse-sensor-proxy -g pulse-sensor-proxy -m 0700 "$SSH_DIR"; then- print_error "Failed to create $SSH_DIR"- exit 1-fi-if ! install -m 0600 -o pulse-sensor-proxy -g pulse-sensor-proxy /dev/null "$SSH_DIR/known_hosts"; then- print_error "Failed to create $SSH_DIR/known_hosts"- exit 1-fi-if ! install -d -o pulse-sensor-proxy -g pulse-sensor-proxy -m 0755 /etc/pulse-sensor-proxy; then- print_error "Failed to create /etc/pulse-sensor-proxy"- exit 1-fi--if [[ -n "$CTID" ]]; then- echo "$CTID" > "$CTID_FILE"- chmod 0644 "$CTID_FILE"-fi--# HTTP Mode Setup Functions-setup_tls_certificates() {- local cert_path="$1"- local key_path="$2"-- # Create TLS directory- install -d -o root -g pulse-sensor-proxy -m 0750 /etc/pulse-sensor-proxy/tls-- if [[ -n "$cert_path" && -n "$key_path" ]]; then- # Use provided certificates- print_info "Using provided TLS certificates..."- cp "$cert_path" /etc/pulse-sensor-proxy/tls/server.crt- cp "$key_path" /etc/pulse-sensor-proxy/tls/server.key- chmod 640 /etc/pulse-sensor-proxy/tls/server.crt- chmod 640 /etc/pulse-sensor-proxy/tls/server.key- chown root:pulse-sensor-proxy /etc/pulse-sensor-proxy/tls/server.crt- chown root:pulse-sensor-proxy /etc/pulse-sensor-proxy/tls/server.key- else- # Generate self-signed certificate- print_info "Generating self-signed TLS certificate..."-- # Get hostname and IPs for SAN- HOSTNAME=$(hostname -f 2>/dev/null || hostname)- IP_ADDRESSES=$(hostname -I 2>/dev/null | tr ' ' '\n' | grep -v '^$' | head -5)-- # Build SAN list- SAN="DNS:${HOSTNAME},DNS:localhost"- for ip in $IP_ADDRESSES; do- SAN="${SAN},IP:${ip}"- done-- # Generate 4096-bit RSA key and self-signed cert valid for 10 years- openssl req -newkey rsa:4096 -nodes -x509 -days 3650 \- -subj "/CN=${HOSTNAME}/O=Pulse Sensor Proxy" \- -addext "subjectAltName=${SAN}" \- -keyout /etc/pulse-sensor-proxy/tls/server.key \- -out /etc/pulse-sensor-proxy/tls/server.crt \- 2>/dev/null || {- print_error "Failed to generate TLS certificate"- exit 1- }-- chmod 640 /etc/pulse-sensor-proxy/tls/server.key- chmod 640 /etc/pulse-sensor-proxy/tls/server.crt- chown root:pulse-sensor-proxy /etc/pulse-sensor-proxy/tls/server.key- chown root:pulse-sensor-proxy /etc/pulse-sensor-proxy/tls/server.crt-- # Log certificate fingerprint for audit- CERT_FINGERPRINT=$(openssl x509 -in /etc/pulse-sensor-proxy/tls/server.crt -noout -fingerprint -sha256 2>/dev/null | cut -d= -f2)- print_success "TLS certificate generated (SHA256: ${CERT_FINGERPRINT})"- fi-}--register_with_pulse() {- local pulse_url="$1"- local hostname="$2"- local proxy_url="$3"- local mode="${4:-}"- if [[ -z "$mode" ]]; then- mode="socket"- fi-- # Output to stderr so it doesn't interfere with command substitution- print_info "Registering temperature proxy with Pulse at $pulse_url..." >&2-- # Build registration request with retry logic- local response body- local http_code- local attempt- local max_attempts=3- local register_url="${pulse_url}/api/temperature-proxy/register"-- for attempt in $(seq 1 $max_attempts); do- if [[ $attempt -gt 1 ]]; then- print_info "Retry attempt $attempt/$max_attempts..." >&2- sleep 2- fi-- response=$(curl -w "\n%{http_code}" -sS -X POST \- -H "Content-Type: application/json" \- -d "{\"hostname\":\"${hostname}\",\"proxy_url\":\"${proxy_url}\",\"mode\":\"${mode}\"}" \- "$register_url")-- local curl_exit=$?- http_code=$(echo "$response" | tail -1)- body=$(echo "$response" | head -n -1)-- # Retry network errors- if [[ $curl_exit -ne 0 && -z "$http_code" ]]; then- continue- fi-- if [[ "$http_code" =~ ^20 ]]; then- print_success "Registered successfully" >&2- echo "$body"- return 0- fi-- if [[ "$http_code" == "404" && "$body" == *'"pve_instance_not_found"'* ]]; then- print_warn "Pulse has not been configured with a Proxmox instance named '$hostname' yet." >&2- print_warn "Add the node in Pulse (Settings → Nodes) and re-run the sensor proxy installer to enable control-plane sync." >&2- return 0- fi- if [[ "$http_code" == "400" && "$body" == *'"missing_proxy_url"'* && "$mode" != "http" ]]; then- if [[ $attempt -lt $max_attempts ]]; then- print_warn "Pulse reported node '$hostname' is not ready yet; retrying..." >&2- sleep 2- continue- fi- print_warn "Pulse refused proxy registration because the node '$hostname' hasn't been added yet." >&2- print_warn "Control-plane sync will be deferred until the node exists in Pulse; temperature proxy will run with a local allow list." >&2- return 0- fi-- if [[ $attempt -eq $max_attempts ]]; then- print_error "Failed to register with Pulse API after $max_attempts attempts" >&2- print_error "" >&2- print_error "═══════════════════════════════════════════════════════" >&2- print_error "Registration Details:" >&2- print_error "═══════════════════════════════════════════════════════" >&2- print_error "URL: $register_url" >&2- print_error "HTTP Code: $http_code" >&2- print_error "Hostname: $hostname" >&2- print_error "Proxy URL: $proxy_url" >&2- print_error "Response: $body" >&2- print_error "" >&2- print_error "Troubleshooting:" >&2- print_error " 1. Ensure this PVE instance is added to Pulse first" >&2- print_error " 2. Verify hostname matches instance name: $hostname" >&2- print_error " 3. Check Pulse logs: docker logs pulse | tail -50" >&2- print_error " 4. Test registration manually:" >&2- print_error " curl -X POST -H 'Content-Type: application/json' \\" >&2- print_error " -d '{\"hostname\":\"${hostname}\",\"proxy_url\":\"${proxy_url}\"}' \\" >&2- print_error " $register_url" >&2- return 1- fi- done-- return 1-}--write_control_plane_token() {- local token="$1"- if [[ -z "$token" ]]; then- return- fi- print_info "Writing control plane token..."- echo "$token" > /etc/pulse-sensor-proxy/.pulse-control-token- chmod 600 /etc/pulse-sensor-proxy/.pulse-control-token- chown pulse-sensor-proxy:pulse-sensor-proxy /etc/pulse-sensor-proxy/.pulse-control-token-}--ensure_control_plane_config() {- local pulse_url="$1"- local refresh="$2"- local config_file="/etc/pulse-sensor-proxy/config.yaml"-- if [[ -z "$pulse_url" ]]; then- return- fi- if [[ -z "$refresh" ]]; then- refresh=60- fi-- # Use robust binary config management if available- if config_command_supported "set-control-plane" "--url" "--token-file" "--refresh"; then- if "$BINARY_PATH" config set-control-plane --url "$pulse_url" --token-file "/etc/pulse-sensor-proxy/.pulse-control-token" --refresh "$refresh" --config "$config_file"; then- chown pulse-sensor-proxy:pulse-sensor-proxy "$config_file"- chmod 0644 "$config_file"- return- else- print_warn "Failed to set control plane using binary; falling back to legacy method"- fi- fi-- if grep -q "^pulse_control_plane:" "$config_file" 2>/dev/null; then- # Re-write the existing control-plane block with the latest URL/token path.- local tmp- tmp=$(mktemp)- awk -v url="$pulse_url" -v refresh="$refresh" '- BEGIN { in_block = 0 }- /^pulse_control_plane:/ {- print "pulse_control_plane:"- print " url: " url- print " token_file: /etc/pulse-sensor-proxy/.pulse-control-token"- print " refresh_interval: " refresh- print ""- in_block = 1- next- }- # Exit the replacement block when we hit a non-indented line- in_block && /^[^[:space:]]/ { in_block = 0 }- in_block { next }- { print }- ' "$config_file" > "$tmp"- mv "$tmp" "$config_file"- chown pulse-sensor-proxy:pulse-sensor-proxy "$config_file"- chmod 0644 "$config_file"- return- fi-- cat >> "$config_file" << EOF--# Pulse control plane configuration (auto-generated)-pulse_control_plane:- url: "$pulse_url"- token_file: "/etc/pulse-sensor-proxy/.pulse-control-token"- refresh_interval: $refresh-EOF-}--declare -a CONTROL_PLANE_ALLOWED_NODE_LIST=()--apply_allowed_nodes_from_response() {- local response="$1"- if [[ -z "$response" ]]; then- return- fi- if ! command -v python3 >/dev/null 2>&1; then- return- fi-- local parsed_nodes- parsed_nodes=$(printf '%s' "$response" | python3 -c '-import json, sys-try:- payload = json.load(sys.stdin)-except Exception:- payload = {}-nodes = payload.get("allowed_nodes") or []-for entry in nodes:- ip = entry.get("ip") or ""- name = entry.get("name") or ""- value = (ip or name).strip()- if value:- print(value)-')-- if [[ -z "$parsed_nodes" ]]; then- return- fi-- mapfile -t __allowed_nodes <<<"$parsed_nodes"- if [[ ${#__allowed_nodes[@]} -gt 0 ]]; then- CONTROL_PLANE_ALLOWED_NODE_LIST=("${__allowed_nodes[@]}")- fi-}--determine_allowlist_mode--# Migrate any existing inline allowed_nodes to file (Phase 1 hotfix for config corruption)-migrate_inline_allowed_nodes_to_file--cleanup_inline_allowed_nodes--# Create base config file if it doesn't exist-if [[ ! -f /etc/pulse-sensor-proxy/config.yaml ]]; then- print_info "Creating base configuration file..."- cat > /etc/pulse-sensor-proxy/config.yaml << 'EOF'-# Pulse Temperature Proxy Configuration-allowed_peer_uids: [1000]--# Allow ID-mapped root (LXC containers with sub-UID mapping)-allow_idmapped_root: true-allowed_idmap_users:- - root--metrics_address: "127.0.0.1:9127"--rate_limit:- per_peer_interval_ms: 333- per_peer_burst: 10-EOF- chown pulse-sensor-proxy:pulse-sensor-proxy /etc/pulse-sensor-proxy/config.yaml- chmod 0644 /etc/pulse-sensor-proxy/config.yaml-fi--# Phase 2: Migration handled by update_allowed_nodes() -> config migrate-to-file-# No need to call ensure_allowed_nodes_file_reference anymore--# Register socket-mode proxy with Pulse if server provided-if [[ "$HTTP_MODE" != true ]]; then- if [[ -z "$PULSE_SERVER" ]]; then- print_warn "PULSE_SERVER not provided; control plane sync disabled. Temperatures will only work on this host."- else- print_info "Registering socket proxy with Pulse server ${PULSE_SERVER}..."- registration_response=$(register_with_pulse "$PULSE_SERVER" "$SHORT_HOSTNAME" "" "socket")- if [[ $? -eq 0 && -n "$registration_response" ]]; then- CONTROL_PLANE_TOKEN=$(echo "$registration_response" | grep -o '"control_token":"[^"]*"' | head -1 | cut -d'"' -f4)- CONTROL_PLANE_REFRESH=$(echo "$registration_response" | grep -o '"refresh_interval":[0-9]*' | head -1 | awk -F: '{print $2}')- if [[ -z "$CONTROL_PLANE_REFRESH" ]]; then- CONTROL_PLANE_REFRESH="60"- fi- apply_allowed_nodes_from_response "$registration_response"- clear_pending_control_plane- else- print_warn "Failed to register socket proxy with Pulse; continuing without control plane sync"- record_pending_control_plane "socket"- fi- fi-fi--# HTTP Mode Configuration-if [[ "$HTTP_MODE" == true ]]; then- echo ""- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo " HTTP Mode Setup (External PVE Host)"- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo ""-- # Validate required parameters- if [[ -z "$PULSE_SERVER" ]]; then- print_error "HTTP mode requires --pulse-server parameter"- print_error "Example: --pulse-server https://pulse.example.com:7655"- exit 1- fi-- # Test Pulse server reachability before proceeding- print_info "Testing connection to Pulse server..."- if ! curl -f -s -m 5 "${PULSE_SERVER}/api/health" >/dev/null 2>&1; then- print_error "Cannot reach Pulse server at: $PULSE_SERVER"- print_error ""- print_error "Troubleshooting:"- print_error " 1. Verify Pulse is running: docker ps | grep pulse"- print_error " 2. Check URL is correct (include protocol and port)"- print_error " 3. Test connectivity: curl -v ${PULSE_SERVER}/api/health"- print_error " 4. Check firewall allows access from this host"- print_error ""- print_error "Installation aborted to prevent incomplete setup"- exit 1- fi- print_success "Pulse server is reachable"-- # Check if port is already in use- # Extract port from HTTP_ADDR which can be ":8443" or "0.0.0.0:8443"- PORT_NUMBER="${HTTP_ADDR##*:}"- if ss -ltn | grep -q ":${PORT_NUMBER} "; then- # Port is in use - check if it's our own service (refresh scenario)- if systemctl is-active --quiet pulse-sensor-proxy 2>/dev/null; then- # Check if the process using the port is pulse-sensor-proxy- PORT_OWNER=$(ss -ltnp | grep ":${PORT_NUMBER} " | grep -o 'pulse-sensor-pr' || true)- if [[ -n "$PORT_OWNER" ]]; then- # Our service is using the port - this is a refresh, continue- print_info "Existing pulse-sensor-proxy detected on port ${PORT_NUMBER} - will refresh configuration"- else- # Service is active but something else is using the port- print_error "Port ${PORT_NUMBER} is already in use by another process"- print_error ""- print_error "Currently using port ${PORT_NUMBER}:"- ss -ltnp | grep ":${PORT_NUMBER} " || true- exit 1- fi- else- # Service not active, port conflict with something else- print_error "Port ${PORT_NUMBER} is already in use"- print_error ""- print_error "Currently using port ${PORT_NUMBER}:"- ss -ltnp | grep ":${PORT_NUMBER} " || true- print_error ""- print_error "Options:"- print_error " 1. Stop the conflicting service"- print_error " 2. Use a different port: --http-addr :PORT"- print_error " 3. If this is a previous sensor-proxy, uninstall first:"- print_error " $0 --uninstall"- exit 1- fi- fi-- # Setup TLS certificates- setup_tls_certificates "" "" # Empty params = auto-generate-- # Determine proxy URL - use provided URL or auto-detect IP address- if [[ -n "$PROXY_URL" ]]; then- # User provided --proxy-url, use it directly- print_info "Using manually specified proxy URL: $PROXY_URL"- else- # Auto-detect from primary IP- PRIMARY_IP=$(hostname -I 2>/dev/null | awk '{print $1}')- if [[ -z "$PRIMARY_IP" ]]; then- print_error "Failed to determine primary IP address"- print_error "Use --proxy-url to specify manually"- exit 1- fi-- # Validate it's an IPv4 address (not IPv6)- if [[ ! "$PRIMARY_IP" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then- print_warn "Primary IP appears to be IPv6 or invalid: $PRIMARY_IP"- print_warn "Attempting to find first IPv4 address..."- PRIMARY_IP=$(hostname -I 2>/dev/null | tr ' ' '\n' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -1)- if [[ -z "$PRIMARY_IP" ]]; then- print_error "No IPv4 address found"- print_error "Use --proxy-url https://YOUR_IP:${PORT_NUMBER} to specify manually"- exit 1- fi- print_info "Using IPv4 address: $PRIMARY_IP"- fi-- # Warn if using loopback- if [[ "$PRIMARY_IP" == "127.0.0.1" ]]; then- print_warn "Primary IP is loopback (127.0.0.1)"- print_warn "Pulse will not be able to reach this proxy!"- print_error "Use --proxy-url https://YOUR_REAL_IP:${PORT_NUMBER} to specify a reachable address"- exit 1- fi-- PROXY_URL="https://${PRIMARY_IP}:${PORT_NUMBER}"- print_info "Proxy will be accessible at: $PROXY_URL"- fi-- # Register with Pulse and get auth/control tokens- registration_response=$(register_with_pulse "$PULSE_SERVER" "$SHORT_HOSTNAME" "$PROXY_URL" "http")- if [[ $? -ne 0 || -z "$registration_response" ]]; then- print_error "Failed to register with Pulse - aborting installation"- print_error "Fix the issue and re-run the installer"- record_pending_control_plane "http"- exit 1- fi-- HTTP_AUTH_TOKEN=$(echo "$registration_response" | grep -o '"token":"[^"]*"' | head -1 | cut -d'"' -f4)- CONTROL_PLANE_TOKEN=$(echo "$registration_response" | grep -o '"control_token":"[^"]*"' | head -1 | cut -d'"' -f4)- CONTROL_PLANE_REFRESH=$(echo "$registration_response" | grep -o '"refresh_interval":[0-9]*' | head -1 | awk -F: '{print $2}')- if [[ -z "$CONTROL_PLANE_REFRESH" ]]; then- CONTROL_PLANE_REFRESH="60"- fi- apply_allowed_nodes_from_response "$registration_response"- clear_pending_control_plane-- if [[ -z "$HTTP_AUTH_TOKEN" ]]; then- print_error "Registration succeeded but Pulse did not return an auth token"- print_error "Response: $registration_response"- exit 1- fi-- echo "$HTTP_AUTH_TOKEN" > /etc/pulse-sensor-proxy/.http-auth-token- chmod 600 /etc/pulse-sensor-proxy/.http-auth-token- chown pulse-sensor-proxy:pulse-sensor-proxy /etc/pulse-sensor-proxy/.http-auth-token-- # Backup config and token files before modifying- if [[ -f "$CONFIG_FILE" ]]; then- BACKUP_TIMESTAMP="$(date +%s)"- BACKUP_CONFIG="${CONFIG_FILE}.backup.$BACKUP_TIMESTAMP"- cp "$CONFIG_FILE" "$BACKUP_CONFIG"- print_info "Config backed up to: $BACKUP_CONFIG"-- # Also backup token files so rollback restores matching secrets- if [[ -f /etc/pulse-sensor-proxy/.pulse-control-token ]]; then- BACKUP_CONTROL_TOKEN="/etc/pulse-sensor-proxy/.pulse-control-token.backup.$BACKUP_TIMESTAMP"- cp /etc/pulse-sensor-proxy/.pulse-control-token "$BACKUP_CONTROL_TOKEN"- fi-- # Remove any existing HTTP configuration to prevent duplicates- if grep -q "^# HTTP Mode Configuration" "$CONFIG_FILE"; then- print_info "Removing existing HTTP configuration..."- # Remove from "# HTTP Mode Configuration" to end of file- sed -i '/^# HTTP Mode Configuration/,$ d' "$CONFIG_FILE"- fi- fi-- # Extract Pulse server IP/hostname for allowed_source_subnets- # Remove protocol and port to get just the host- PULSE_HOST=$(echo "$PULSE_SERVER" | sed -E 's#^https?://##' | sed -E 's#:[0-9]+$##')-- # Try to resolve to IP if it's a hostname- PULSE_IP=$(getent hosts "$PULSE_HOST" 2>/dev/null | awk '{print $1; exit}')- if [[ -z "$PULSE_IP" ]]; then- # Fallback: assume PULSE_HOST is already an IP or use it as-is- PULSE_IP="$PULSE_HOST"- fi-- print_info "Pulse server detected at: $PULSE_IP"-- HTTP_ALLOWED_SUBNETS=()- PULSE_HTTP_SUBNET="$(format_ip_to_cidr "$PULSE_IP")"- LOCAL_HTTP_SUBNET="$(format_ip_to_cidr "$PRIMARY_IP")"- LOOPBACK_HTTP_SUBNET="127.0.0.1/32"-- [[ -n "$PULSE_HTTP_SUBNET" ]] && HTTP_ALLOWED_SUBNETS+=("$PULSE_HTTP_SUBNET")- HTTP_ALLOWED_SUBNETS+=("$LOOPBACK_HTTP_SUBNET")- [[ -n "$LOCAL_HTTP_SUBNET" ]] && HTTP_ALLOWED_SUBNETS+=("$LOCAL_HTTP_SUBNET")-- declare -A HTTP_SUBNET_SEEN=()- deduped_http_subnets=()- for subnet in "${HTTP_ALLOWED_SUBNETS[@]}"; do- [[ -z "$subnet" ]] && continue- if [[ -z "${HTTP_SUBNET_SEEN[$subnet]+x}" ]]; then- HTTP_SUBNET_SEEN[$subnet]=1- deduped_http_subnets+=("$subnet")- fi- done- HTTP_ALLOWED_SUBNETS=("${deduped_http_subnets[@]}")-- # Configure HTTP mode - check if already configured to avoid duplicates- print_info "Configuring HTTP mode..."- if config_command_supported "set-http" "--enabled" "--listen-addr" "--auth-token" "--tls-cert" "--tls-key"; then- if "$BINARY_PATH" config set-http \- --enabled=true \- --listen-addr="$HTTP_ADDR" \- --auth-token="$HTTP_AUTH_TOKEN" \- --tls-cert="/etc/pulse-sensor-proxy/tls/server.crt" \- --tls-key="/etc/pulse-sensor-proxy/tls/server.key" \- --config="$CONFIG_FILE"; then-- for subnet in "${HTTP_ALLOWED_SUBNETS[@]}"; do- ensure_allowed_source_subnet "$subnet"- done- print_info "HTTP mode configured successfully (using binary)"- else- print_warn "Failed to set HTTP config using binary; falling back to legacy method"- # Fallback to legacy logic- if grep -q "^http_enabled:" "$CONFIG_FILE" 2>/dev/null; then- sed -i "s|^http_auth_token:.*|http_auth_token: $HTTP_AUTH_TOKEN|" "$CONFIG_FILE"- for subnet in "${HTTP_ALLOWED_SUBNETS[@]}"; do- ensure_allowed_source_subnet "$subnet"- done- print_info "Updated HTTP auth token (existing HTTP mode configuration kept)"- else- cat >> "$CONFIG_FILE" << EOF--# HTTP Mode Configuration (External PVE Host)-http_enabled: true-http_listen_addr: "$HTTP_ADDR"-http_tls_cert: /etc/pulse-sensor-proxy/tls/server.crt-http_tls_key: /etc/pulse-sensor-proxy/tls/server.key-http_auth_token: "$HTTP_AUTH_TOKEN"--# Allow HTTP connections from Pulse server, localhost, and this host-allowed_source_subnets:-EOF- for subnet in "${HTTP_ALLOWED_SUBNETS[@]}"; do- echo " - $subnet" >> "$CONFIG_FILE"- done- fi- fi- else- if grep -q "^http_enabled:" "$CONFIG_FILE" 2>/dev/null; then- # HTTP mode already configured - only update the token (avoid duplicates)- sed -i "s|^http_auth_token:.*|http_auth_token: $HTTP_AUTH_TOKEN|" "$CONFIG_FILE"- for subnet in "${HTTP_ALLOWED_SUBNETS[@]}"; do- ensure_allowed_source_subnet "$subnet"- done- print_info "Updated HTTP auth token (existing HTTP mode configuration kept)"- else- # Fresh HTTP mode configuration - append to file- cat >> "$CONFIG_FILE" << EOF--# HTTP Mode Configuration (External PVE Host)-http_enabled: true-http_listen_addr: "$HTTP_ADDR"-http_tls_cert: /etc/pulse-sensor-proxy/tls/server.crt-http_tls_key: /etc/pulse-sensor-proxy/tls/server.key-http_auth_token: "$HTTP_AUTH_TOKEN"--# Allow HTTP connections from Pulse server, localhost, and this host-allowed_source_subnets:-EOF- for subnet in "${HTTP_ALLOWED_SUBNETS[@]}"; do- echo " - $subnet" >> "$CONFIG_FILE"- done- fi- fi- chown pulse-sensor-proxy:pulse-sensor-proxy "$CONFIG_FILE"- chmod 0644 "$CONFIG_FILE"-- print_success "HTTP mode configured successfully"- echo ""- # Extract port number correctly from HTTP_ADDR (handles both ":8443" and "0.0.0.0:8443")- HTTP_PORT="${HTTP_ADDR##*:}"- print_info "Firewall configuration required:"- print_info " Allow inbound TCP connections on port ${HTTP_PORT} from Pulse server"- print_info " Command: ufw allow from <pulse-server-ip> to any port ${HTTP_PORT}"- echo ""-fi--if [[ -n "$CONTROL_PLANE_TOKEN" && -n "$PULSE_SERVER" ]]; then- write_control_plane_token "$CONTROL_PLANE_TOKEN"- ensure_control_plane_config "$PULSE_SERVER" "$CONTROL_PLANE_REFRESH"-fi--# Stop existing service if running (for upgrades)-if systemctl is-active --quiet pulse-sensor-proxy 2>/dev/null; then- print_info "Stopping existing service for upgrade..."- # Tolerate timeout from slow HTTPS shutdown (can take 30s)- systemctl stop pulse-sensor-proxy || true- # Clear any failed state from the stop- systemctl reset-failed pulse-sensor-proxy 2>/dev/null || true-fi--# Install hardened systemd service-print_info "Installing hardened systemd service..."--# Generate service file based on mode (Proxmox vs standalone)-if [[ "$STANDALONE" == true ]]; then- # Standalone/Docker mode - no Proxmox-specific paths- cat > "$SERVICE_PATH" <<EOF-[Unit]-Description=Pulse Temperature Proxy-Documentation=https://github.com/rcourtman/Pulse-After=network.target--[Service]-Type=simple-User=pulse-sensor-proxy-Group=pulse-sensor-proxy-WorkingDirectory=/var/lib/pulse-sensor-proxy-# Validate config before starting (Phase 2: prevent corruption from starting service)-ExecStartPre=${BINARY_PATH} config validate --config /etc/pulse-sensor-proxy/config.yaml-ExecStart=${BINARY_PATH} --config /etc/pulse-sensor-proxy/config.yaml-Restart=on-failure-RestartSec=5s--# Runtime dirs/sockets-RuntimeDirectory=pulse-sensor-proxy-RuntimeDirectoryMode=0775-RuntimeDirectoryPreserve=yes-LogsDirectory=pulse/sensor-proxy-LogsDirectoryMode=0750-UMask=0007--# Core hardening-NoNewPrivileges=true-ProtectSystem=strict-ProtectHome=read-only-ReadWritePaths=/var/lib/pulse-sensor-proxy-ReadWritePaths=-/run/corosync-ProtectKernelTunables=true-ProtectKernelModules=true-ProtectControlGroups=true-ProtectClock=true-PrivateTmp=true-PrivateDevices=true-ProtectProc=invisible-ProcSubset=pid-LockPersonality=true-RestrictSUIDSGID=true-RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK-RestrictNamespaces=true-SystemCallFilter=@system-service-SystemCallErrorNumber=EPERM-CapabilityBoundingSet=-AmbientCapabilities=-KeyringMode=private-LimitNOFILE=1024--# Logging-StandardOutput=journal-StandardError=journal-SyslogIdentifier=pulse-sensor-proxy--[Install]-WantedBy=multi-user.target-EOF-else- # Proxmox mode - include Proxmox paths- cat > "$SERVICE_PATH" <<EOF-[Unit]-Description=Pulse Temperature Proxy-Documentation=https://github.com/rcourtman/Pulse-After=network.target--[Service]-Type=simple-User=pulse-sensor-proxy-Group=pulse-sensor-proxy-SupplementaryGroups=www-data-WorkingDirectory=/var/lib/pulse-sensor-proxy-# Validate config before starting (Phase 2: prevent corruption from starting service)-ExecStartPre=${BINARY_PATH} config validate --config /etc/pulse-sensor-proxy/config.yaml-ExecStart=${BINARY_PATH}-Restart=on-failure-RestartSec=5s--# Runtime dirs/sockets-RuntimeDirectory=pulse-sensor-proxy-RuntimeDirectoryMode=0775-RuntimeDirectoryPreserve=yes-LogsDirectory=pulse/sensor-proxy-LogsDirectoryMode=0750-UMask=0007--# Core hardening-NoNewPrivileges=true-ProtectSystem=strict-ProtectHome=read-only-ReadWritePaths=/var/lib/pulse-sensor-proxy-ReadWritePaths=-/run/corosync-ReadOnlyPaths=/run/pve-cluster /etc/pve-ProtectKernelTunables=true-ProtectKernelModules=true-ProtectControlGroups=true-ProtectClock=true-PrivateTmp=true-PrivateDevices=true-ProtectProc=invisible-ProcSubset=pid-LockPersonality=true-RestrictSUIDSGID=true-RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK-RestrictNamespaces=true-SystemCallFilter=@system-service-SystemCallErrorNumber=EPERM-CapabilityBoundingSet=-AmbientCapabilities=-KeyringMode=private-LimitNOFILE=1024--# Logging-StandardOutput=journal-StandardError=journal-SyslogIdentifier=pulse-sensor-proxy--[Install]-WantedBy=multi-user.target-EOF-fi--# Add HTTP mode paths to service file if needed-if [[ "$HTTP_MODE" == true ]]; then- print_info "Updating service file for HTTP mode..."-- # Add ReadOnlyPaths for TLS directory (after ReadWritePaths line)- sed -i '/^ReadWritePaths=\/var\/lib\/pulse-sensor-proxy/a ReadOnlyPaths=/etc/pulse-sensor-proxy/tls' "$SERVICE_PATH"-- print_success "Service file updated for HTTP mode"-fi--# Reload systemd and start service-print_info "Enabling and starting service..."-if ! systemctl daemon-reload; then- print_error "Failed to reload systemd daemon"- journalctl -u pulse-sensor-proxy -n 20 --no-pager- exit 1-fi--if ! systemctl enable pulse-sensor-proxy.service; then- print_error "Failed to enable pulse-sensor-proxy service"- journalctl -u pulse-sensor-proxy -n 20 --no-pager- exit 1-fi--if ! systemctl start pulse-sensor-proxy.service; then- print_error "Failed to start pulse-sensor-proxy service"- print_error ""-- # Attempt rollback if HTTP mode and we have a backup- if [[ "$HTTP_MODE" == true && -n "$BACKUP_CONFIG" && -f "$BACKUP_CONFIG" ]]; then- print_warn "Attempting to rollback to previous configuration..."- if cp "$BACKUP_CONFIG" /etc/pulse-sensor-proxy/config.yaml; then- print_info "Config restored from backup"- # Also restore token files to match the old config- if [[ -n "$BACKUP_CONTROL_TOKEN" && -f "$BACKUP_CONTROL_TOKEN" ]]; then- cp "$BACKUP_CONTROL_TOKEN" /etc/pulse-sensor-proxy/.pulse-control-token- print_info "Control plane token restored from backup"- fi- # Clear failed state before attempting rollback start- systemctl reset-failed pulse-sensor-proxy 2>/dev/null || true- if systemctl start pulse-sensor-proxy.service; then- print_success "Service restarted with previous configuration"- print_error ""- print_error "HTTP mode installation failed but previous config restored"- print_error "Temperature monitoring should still work via Unix socket"- print_error "Review the error above and fix before retrying"- exit 1- else- print_error "Rollback failed - service won't start even with old config"- fi- else- print_error "Failed to restore config from backup"- fi- fi-- print_error "═══════════════════════════════════════════════════════"- print_error "Service Status:"- print_error "═══════════════════════════════════════════════════════"- systemctl status pulse-sensor-proxy --no-pager --lines=0 2>&1 || true- print_error ""- print_error "═══════════════════════════════════════════════════════"- print_error "Recent Logs (last 40 lines):"- print_error "═══════════════════════════════════════════════════════"- journalctl -u pulse-sensor-proxy -n 40 --no-pager 2>&1 || true- print_error ""- print_error "═══════════════════════════════════════════════════════"- print_error "Common Issues:"- print_error "═══════════════════════════════════════════════════════"- print_error "1. Missing user: Run 'useradd --system --no-create-home --group pulse-sensor-proxy'"- print_error "2. Permission errors: Check ownership of /var/lib/pulse-sensor-proxy"- print_error "3. lm-sensors not installed: Run 'apt-get install lm-sensors && sensors-detect --auto'"- print_error "4. Standalone node detection: If you see 'pvecm' errors, this is expected for non-clustered hosts"- print_error "5. Port already in use: Check 'ss -tlnp | grep ${HTTP_ADDR##*:}'"- print_error ""- print_error "For more help: https://github.com/rcourtman/Pulse/blob/main/docs/TROUBLESHOOTING.md"- exit 1-fi--# Wait for socket to appear-print_info "Waiting for socket..."-for i in {1..10}; do- if [[ -S "$SOCKET_PATH" ]]; then- break- fi- sleep 1-done--if [[ ! -S "$SOCKET_PATH" ]]; then- print_error "Socket did not appear at $SOCKET_PATH after 10 seconds"- print_error ""- print_error "═══════════════════════════════════════════════════════"- print_error "Diagnostics:"- print_error "═══════════════════════════════════════════════════════"- print_error "Service Status:"- systemctl status pulse-sensor-proxy --no-pager 2>&1 || true- print_error ""- print_error "Socket Directory Permissions:"- ls -la /run/pulse-sensor-proxy/ 2>&1 || echo "Directory does not exist"- print_error ""- print_error "Recent Logs:"- journalctl -u pulse-sensor-proxy -n 20 --no-pager 2>&1 || true- print_error ""- print_error "Common Causes:"- print_error " • Service failed to start (check logs above)"- print_error " • RuntimeDirectory permissions issue"- print_error " • Systemd socket creation failed"- print_error ""- print_error "Try: systemctl restart pulse-sensor-proxy && watch -n 0.5 'ls -la /run/pulse-sensor-proxy/'"- exit 1-fi--print_info "Socket ready at $SOCKET_PATH"--# If socket verification was deferred because the runtime directory was-# missing earlier, test the container mount now that the proxy is running.-if [[ "$STANDALONE" == false && "$DEFER_SOCKET_VERIFICATION" = true ]]; then- print_info "Validating container socket visibility now that host proxy is running..."- if pct exec "$CTID" -- test -S "${MOUNT_TARGET}/pulse-sensor-proxy.sock"; then- print_info "✓ Secure socket communication ready"- DEFER_SOCKET_VERIFICATION=false- [ -n "$LXC_CONFIG_BACKUP" ] && rm -f "$LXC_CONFIG_BACKUP"- else- print_error "Socket not visible at ${MOUNT_TARGET}/pulse-sensor-proxy.sock"- print_error "Bind mount exists but container still cannot access the proxy socket"- print_error "This usually indicates the container needs a restart or the mount failed to attach"-- if [ -n "$LXC_CONFIG_BACKUP" ] && [ -f "$LXC_CONFIG_BACKUP" ]; then- print_warn "Rolling back container configuration changes..."- cp "$LXC_CONFIG_BACKUP" "$LXC_CONFIG"- rm -f "$LXC_CONFIG_BACKUP"- print_info "Container configuration restored to previous state"- fi- exit 1- fi-fi--# Validate HTTP endpoint if HTTP mode is enabled-if [[ "$HTTP_MODE" == true ]]; then- print_info "Validating HTTP endpoint..."-- # Wait a moment for HTTP server to fully start- sleep 2-- # Test HTTP endpoint- HTTP_CHECK_URL="https://${PRIMARY_IP}${HTTP_ADDR}/health"- if curl -f -s -k -m 5 \- -H "Authorization: Bearer ${HTTP_AUTH_TOKEN}" \- "$HTTP_CHECK_URL" >/dev/null 2>&1; then- print_success "HTTP endpoint validated successfully"- else- print_error "HTTP endpoint validation failed"- print_error "URL: $HTTP_CHECK_URL"- print_error ""- print_error "Troubleshooting:"- print_error " 1. Check if port ${HTTP_ADDR##*:} is listening: ss -tlnp | grep ${HTTP_ADDR##*:}"- print_error " 2. Check sensor-proxy logs: journalctl -u pulse-sensor-proxy -n 50"- print_error " 3. Test manually: curl -k -H 'Authorization: Bearer \$TOKEN' $HTTP_CHECK_URL"- print_error ""- print_warn "Service is running but HTTP endpoint may not be accessible"- print_warn "Temperature monitoring may not work properly"- fi-fi--# Install sensor wrapper script for combined sensor and SMART data collection-print_info "Installing sensor wrapper script..."-cat > "$WRAPPER_SCRIPT" << 'WRAPPER_EOF'-#!/bin/bash-#-# pulse-sensor-wrapper.sh-# Combined sensor and SMART temperature collection for Pulse monitoring-#-# This script is deployed as the SSH forced command for the sensor proxy.-# It collects CPU/GPU temps via sensors and disk temps via smartctl,-# returning a unified JSON payload.--set -euo pipefail--# Configuration-CACHE_DIR="/var/cache/pulse-sensor-proxy"-SMART_CACHE_TTL=1800 # 30 minutes-MAX_SMARTCTL_TIME=5 # seconds per disk--# Ensure cache directory exists-mkdir -p "$CACHE_DIR" 2>/dev/null || true--# Function to get cached SMART data-get_cached_smart() {- local cache_file="$CACHE_DIR/smart-temps.json"- local now=$(date +%s)-- # Check if cache exists and is fresh- if [[ -f "$cache_file" ]]; then- local mtime=$(stat -c %Y "$cache_file" 2>/dev/null || echo 0)- local age=$((now - mtime))-- if [[ $age -lt $SMART_CACHE_TTL ]]; then- cat "$cache_file"- return 0- fi- fi-- # Cache miss or stale - return empty array and trigger background refresh- echo "[]"-- # Trigger async refresh if not already running (use lock file)- local lock_file="$CACHE_DIR/smart-refresh.lock"- if ! [ -f "$lock_file" ]; then- (refresh_smart_cache &)- fi-- return 0-}--# Function to refresh SMART cache in background-refresh_smart_cache() {- local lock_file="$CACHE_DIR/smart-refresh.lock"- local cache_file="$CACHE_DIR/smart-temps.json"- local temp_file="${cache_file}.tmp.$$"-- # Create lock file and ensure cleanup on exit- touch "$lock_file" 2>/dev/null || return 1- trap "rm -f '$lock_file' '$temp_file'" EXIT-- local disks=()-- # Find all physical disks (skip partitions, loop devices, etc.)- while IFS= read -r dev; do- [[ -b "$dev" ]] && disks+=("$dev")- done < <(lsblk -nd -o NAME,TYPE | awk '$2=="disk" {print "/dev/"$1}')-- local results=()-- for dev in "${disks[@]}"; do- # Use smartctl with standby check to avoid waking sleeping drives- # -n standby: skip if drive is in standby/sleep mode- # -i: include identity data (serial/WWN/model)- # --json=o: output original smartctl JSON format- # timeout: prevent hanging on problematic drives-- local output- if output=$(timeout ${MAX_SMARTCTL_TIME}s smartctl -n standby -i -A --json=o "$dev" 2>/dev/null); then- # Parse the JSON output- local temp=$(echo "$output" | jq -r '- .temperature.current //- (.ata_smart_attributes.table[] | select(.id == 194) | .raw.value) //- (.nvme_smart_health_information_log.temperature // empty)- ' 2>/dev/null)-- local serial=$(echo "$output" | jq -r '.serial_number // empty' 2>/dev/null)- local wwn=$(echo "$output" | jq -r '.wwn.naa // .wwn.oui // empty' 2>/dev/null)- local model=$(echo "$output" | jq -r '.model_name // .model_family // empty' 2>/dev/null)- local transport=$(echo "$output" | jq -r '.device.type // empty' 2>/dev/null)-- # Only include if we got a valid temperature- if [[ -n "$temp" && "$temp" != "null" && "$temp" =~ ^[0-9]+$ ]]; then- local entry=$(jq -n \- --arg dev "$dev" \- --arg serial "$serial" \- --arg wwn "$wwn" \- --arg model "$model" \- --arg transport "$transport" \- --argjson temp "$temp" \- --arg updated "$(date -Iseconds)" \- '{- device: $dev,- serial: $serial,- wwn: $wwn,- model: $model,- type: $transport,- temperature: $temp,- lastUpdated: $updated,- standbySkipped: false- }')- results+=("$entry")- fi- elif echo "$output" | grep -q "standby"; then- # Drive is in standby - record it but don't wake it- local entry=$(jq -n \- --arg dev "$dev" \- --arg updated "$(date -Iseconds)" \- '{- device: $dev,- temperature: null,- lastUpdated: $updated,- standbySkipped: true- }')- results+=("$entry")- fi-- # Small delay between disks to avoid saturating SATA controller- sleep 0.1- done-- # Build final JSON array- if [[ ${#results[@]} -gt 0 ]]; then- local json=$(printf '%s\n' "${results[@]}" | jq -s '.')- else- local json="[]"- fi-- # Atomic write to cache- echo "$json" > "$temp_file"- mv "$temp_file" "$cache_file"- chmod 644 "$cache_file" 2>/dev/null || true-}--# Main execution--# Collect sensor data (CPU, GPU temps)-sensors_data=$(sensors -j 2>/dev/null || echo '{}')--# Get SMART data from cache-smart_data=$(get_cached_smart)--# Combine into unified payload-jq -n \- --argjson sensors "$sensors_data" \- --argjson smart "$smart_data" \- '{- sensors: $sensors,- smart: $smart- }'-WRAPPER_EOF--chmod +x "$WRAPPER_SCRIPT"-print_success "Sensor wrapper installed at $WRAPPER_SCRIPT"--# Install cleanup system for full Pulse removal when nodes are deleted-print_info "Installing cleanup system..."--# Install cleanup script-cat > "$CLEANUP_SCRIPT_PATH" <<'CLEANUP_EOF'-#!/bin/bash--# pulse-sensor-cleanup.sh - Complete Pulse footprint removal when nodes are removed-# Removes: SSH keys, proxy service, binaries, API tokens, and LXC bind mounts-# This script is triggered by systemd path unit when cleanup-request.json is created--set -euo pipefail--# Configuration-WORK_DIR="/var/lib/pulse-sensor-proxy"-CLEANUP_REQUEST="${WORK_DIR}/cleanup-request.json"-LOCKFILE="${WORK_DIR}/cleanup.lock"-LOG_TAG="pulse-sensor-cleanup"-INSTALLER_PATH="/opt/pulse/sensor-proxy/install-sensor-proxy.sh"--# Logging functions-log_info() {- logger -t "$LOG_TAG" -p user.info "$1"- echo "[INFO] $1"-}--log_warn() {- logger -t "$LOG_TAG" -p user.warning "$1"- echo "[WARN] $1"-}--log_error() {- logger -t "$LOG_TAG" -p user.err "$1"- echo "[ERROR] $1" >&2-}--# Acquire exclusive lock to prevent concurrent cleanup runs-exec 200>"$LOCKFILE"-if ! flock -n 200; then- log_info "Another cleanup instance is running, exiting"- exit 0-fi--# Check if cleanup request file exists-if [[ ! -f "$CLEANUP_REQUEST" ]]; then- log_info "No cleanup request found at $CLEANUP_REQUEST"- exit 0-fi--log_info "Processing cleanup request from $CLEANUP_REQUEST"--# Read and parse the cleanup request-CLEANUP_DATA=$(cat "$CLEANUP_REQUEST")-HOST=$(echo "$CLEANUP_DATA" | grep -o '"host":"[^"]*"' | cut -d'"' -f4 || echo "")-REQUESTED_AT=$(echo "$CLEANUP_DATA" | grep -o '"requestedAt":"[^"]*"' | cut -d'"' -f4 || echo "")--log_info "Cleanup requested at: ${REQUESTED_AT:-unknown}"--# Rename request file to .processing to prevent re-triggering while allowing retry on failure-PROCESSING_FILE="${CLEANUP_REQUEST}.processing"-mv "$CLEANUP_REQUEST" "$PROCESSING_FILE" 2>/dev/null || {- log_warn "Failed to rename cleanup request file, may have been processed by another instance"- exit 0-}--# If no specific host was provided, clean up all known nodes-if [[ -z "$HOST" ]]; then- log_info "No specific host provided - cleaning up all cluster nodes"-- # Discover cluster nodes (prefer hostname resolution for multi-network clusters)- # Use get_cluster_node_names helper (prefers pvesh API, falls back to pvecm CLI)- CLUSTER_NODES=""- while IFS= read -r nodename; do- [[ -z "$nodename" ]] && continue- resolved_ip=$(getent hosts "$nodename" 2>/dev/null | awk '{print $1; exit}')- if [[ -n "$resolved_ip" ]]; then- CLUSTER_NODES="${CLUSTER_NODES:+$CLUSTER_NODES }$resolved_ip"- fi- done < <(get_cluster_node_names 2>/dev/null || true)- # Fallback to pvecm status if hostname resolution didn't work- if [[ -z "$CLUSTER_NODES" ]] && command -v pvecm >/dev/null 2>&1; then- CLUSTER_NODES=$(pvecm status 2>/dev/null | grep -vEi "qdevice" | awk '/0x[0-9a-f]+.*[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ {for(i=1;i<=NF;i++) if($i ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) print $i}' || true)- fi-- if [[ -n "$CLUSTER_NODES" ]]; then- for node_ip in $CLUSTER_NODES; do- log_info "Cleaning up SSH keys on node $node_ip"-- # Remove both pulse-managed-key and pulse-proxy-key entries- ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 root@"$node_ip" \- "sed -i -e '/# pulse-managed-key\$/d' -e '/# pulse-proxy-key\$/d' /root/.ssh/authorized_keys" 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "Failed to clean up SSH keys on $node_ip"- done- log_info "Cluster cleanup completed"- else- # Standalone node - clean up localhost- log_info "Standalone node detected - cleaning up localhost"- sed -i -e '/# pulse-managed-key$/d' -e '/# pulse-proxy-key$/d' /root/.ssh/authorized_keys 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "Failed to clean up SSH keys on localhost"- fi-else- log_info "Cleaning up specific host: $HOST"-- # Extract hostname/IP from host URL- HOST_CLEAN=$(echo "$HOST" | sed -e 's|^https\?://||' -e 's|:.*$||')-- # Check if this is localhost (by IP, hostname, or FQDN)- LOCAL_IPS=$(hostname -I 2>/dev/null || echo "")- LOCAL_HOSTNAME=$(hostname 2>/dev/null || echo "")- LOCAL_FQDN=$(hostname -f 2>/dev/null || echo "")- IS_LOCAL=false-- # Check against all local IPs- for local_ip in $LOCAL_IPS; do- if [[ "$HOST_CLEAN" == "$local_ip" ]]; then- IS_LOCAL=true- break- fi- done-- # Check against hostname and FQDN- if [[ "$HOST_CLEAN" == "127.0.0.1" || "$HOST_CLEAN" == "localhost" || \- "$HOST_CLEAN" == "$LOCAL_HOSTNAME" || "$HOST_CLEAN" == "$LOCAL_FQDN" ]]; then- IS_LOCAL=true- fi-- if [[ "$IS_LOCAL" == true ]]; then- log_info "Performing full cleanup on localhost"-- # 1. Remove SSH keys- log_info "Removing SSH keys from authorized_keys"- sed -i -e '/# pulse-managed-key$/d' -e '/# pulse-proxy-key$/d' /root/.ssh/authorized_keys 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "Failed to clean up SSH keys"-- # 2. Delete API tokens and user- log_info "Removing Proxmox API tokens and pulse-monitor user"- if command -v pveum >/dev/null 2>&1; then- # Try JSON output first (pveum with --output-format json)- TOKEN_IDS=""- if command -v python3 >/dev/null 2>&1; then- # Try pveum with JSON output- if TOKEN_JSON=$(pveum user token list pulse-monitor@pam --output-format json 2>/dev/null); then- TOKEN_IDS=$(echo "$TOKEN_JSON" | python3 -c '-import sys, json-try:- data = json.load(sys.stdin)- if isinstance(data, list):- for item in data:- if "tokenid" in item:- print(item["tokenid"])-except: pass-' || true)- fi- fi-- # Fall back to pvesh JSON API if pveum JSON didn't work- if [[ -z "$TOKEN_IDS" ]] && command -v pvesh >/dev/null 2>&1; then- if TOKEN_JSON=$(pvesh get /access/users/pulse-monitor@pam/token 2>/dev/null); then- TOKEN_IDS=$(echo "$TOKEN_JSON" | python3 -c '-import sys, json-try:- data = json.load(sys.stdin)- if isinstance(data, dict) and "data" in data:- for item in data["data"]:- if "tokenid" in item:- print(item["tokenid"])-except: pass-' 2>/dev/null || true)- fi- fi-- # Last resort: parse table output with better filtering- if [[ -z "$TOKEN_IDS" ]]; then- TOKEN_IDS=$(pveum user token list pulse-monitor@pam 2>/dev/null | \- awk 'NR>1 && /^[[:space:]]*pulse/ {print $1}' | grep -v '^[│┌└╞─]' | grep -v '^$' || true)- fi-- if [[ -n "$TOKEN_IDS" ]]; then- for token_id in $TOKEN_IDS; do- log_info "Deleting API token: $token_id"- pveum user token remove pulse-monitor@pam "${token_id}" 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "Failed to delete token $token_id"- done- else- log_info "No API tokens found for pulse-monitor@pam"- fi-- # Remove the pulse-monitor user- log_info "Removing pulse-monitor@pam user"- pveum user delete pulse-monitor@pam 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "pulse-monitor@pam user not found or already removed"- else- log_warn "pveum command not available, skipping API token cleanup"- fi-- # 3. Remove LXC bind mounts- log_info "Removing LXC bind mounts from container configs"- if command -v pct >/dev/null 2>&1; then- for ctid in $(pct list 2>/dev/null | awk 'NR>1 {print $1}' || true); do- CONF_FILE="/etc/pve/lxc/${ctid}.conf"- if [[ -f "$CONF_FILE" ]]; then- # Find pulse-sensor-proxy mount points and remove them using pct- for mp_key in $(grep -o "^mp[0-9]\+:" "$CONF_FILE" | grep -f <(grep "pulse-sensor-proxy" "$CONF_FILE" | grep -o "^mp[0-9]\+:") || true); do- mp_num="${mp_key%:}"- log_info "Removing ${mp_num} (pulse-sensor-proxy) from container $ctid"- if pct set "$ctid" -delete "${mp_num}" 2>&1 | logger -t "$LOG_TAG" -p user.info; then- log_info "Successfully removed ${mp_num} from container $ctid"- else- log_warn "Failed to remove ${mp_num} from container $ctid"- fi- done- fi- done- fi-- # 4. Uninstall proxy service and remove binaries via isolated transient unit- log_info "Starting full uninstallation (service, binaries, configs)"- if [[ -x "$INSTALLER_PATH" ]]; then- # Use systemd-run to create isolated transient unit that won't be killed- # when we stop pulse-sensor-proxy.service- if command -v systemd-run >/dev/null 2>&1; then- # Use UUID for unique unit name (prevents same-second collisions)- UNINSTALL_UUID=$(cat /proc/sys/kernel/random/uuid 2>/dev/null || date +%s%N)- UNINSTALL_UNIT="pulse-uninstall-${UNINSTALL_UUID}"- log_info "Spawning isolated uninstaller unit: $UNINSTALL_UNIT"-- systemd-run \- --unit="${UNINSTALL_UNIT}" \- --property="Type=oneshot" \- --property="Conflicts=pulse-sensor-proxy.service" \- --collect \- --wait \- --quiet \- -- bash -c "$INSTALLER_PATH --uninstall --purge --quiet >> /var/log/pulse/sensor-proxy/uninstall.log 2>&1" \- 2>&1 | logger -t "$LOG_TAG" -p user.info-- UNINSTALL_EXIT=$?- if [[ $UNINSTALL_EXIT -eq 0 ]]; then- log_info "Uninstaller completed successfully"- else- log_error "Uninstaller failed with exit code $UNINSTALL_EXIT"- exit 1- fi- else- log_warn "systemd-run not available, attempting direct uninstall (may fail)"- bash "$INSTALLER_PATH" --uninstall --quiet >> /var/log/pulse/sensor-proxy/uninstall.log 2>&1 || \- log_error "Uninstaller failed - manual cleanup may be required"- fi- else- log_warn "Installer not found at $INSTALLER_PATH, cannot run uninstaller"- log_info "Manual cleanup required: systemctl stop pulse-sensor-proxy && systemctl disable pulse-sensor-proxy"- fi-- log_info "Localhost cleanup initiated (uninstaller running in background)"- else- log_info "Cleaning up remote host: $HOST_CLEAN"-- # Try to use proxy's SSH key first (for standalone nodes), fall back to default- PROXY_KEY="/var/lib/pulse-sensor-proxy/ssh/id_ed25519"- SSH_CMD="ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5"-- if [[ -f "$PROXY_KEY" ]]; then- log_info "Using proxy SSH key for cleanup"- SSH_CMD="$SSH_CMD -i $PROXY_KEY"- fi-- # Remove both pulse-managed-key and pulse-proxy-key entries from remote host- CLEANUP_OUTPUT=$($SSH_CMD root@"$HOST_CLEAN" \- "sed -i -e '/# pulse-managed-key\$/d' -e '/# pulse-proxy-key\$/d' /root/.ssh/authorized_keys && echo 'SUCCESS'" 2>&1)-- if echo "$CLEANUP_OUTPUT" | grep -q "SUCCESS"; then- log_info "Successfully cleaned up SSH keys on $HOST_CLEAN"- else- # Check if this is a standalone node with forced commands (common case)- if echo "$CLEANUP_OUTPUT" | grep -q "cpu_thermal\|coretemp\|k10temp"; then- log_warn "Cannot cleanup standalone node $HOST_CLEAN (forced command prevents cleanup)"- log_info "Standalone node keys are read-only (sensors -j) - low security risk"- log_info "Manual cleanup: ssh root@$HOST_CLEAN \"sed -i '/# pulse-proxy-key\$/d' /root/.ssh/authorized_keys\""- else- log_error "Failed to clean up SSH keys on $HOST_CLEAN: $CLEANUP_OUTPUT"- exit 1- fi- fi- fi-fi--# Remove processing file on success-rm -f "$PROCESSING_FILE"--log_info "Cleanup completed successfully"-exit 0-CLEANUP_EOF--chmod +x "$CLEANUP_SCRIPT_PATH"-print_info "Cleanup script installed"--# Install systemd path unit-CLEANUP_PATH_UNIT="/etc/systemd/system/pulse-sensor-cleanup.path"-cat > "$CLEANUP_PATH_UNIT" << 'PATH_EOF'-[Unit]-Description=Watch for Pulse sensor cleanup requests-Documentation=https://github.com/rcourtman/Pulse--[Path]-# Watch for the cleanup request file-PathChanged=/var/lib/pulse-sensor-proxy/cleanup-request.json-# Also watch for modifications-PathModified=/var/lib/pulse-sensor-proxy/cleanup-request.json--[Install]-WantedBy=multi-user.target-PATH_EOF--# Install systemd service unit-CLEANUP_SERVICE_UNIT="/etc/systemd/system/pulse-sensor-cleanup.service"-cat > "$CLEANUP_SERVICE_UNIT" <<SERVICE_EOF-[Unit]-Description=Pulse Sensor Cleanup Service-Documentation=https://github.com/rcourtman/Pulse-After=network.target--[Service]-Type=oneshot-ExecStart=${CLEANUP_SCRIPT_PATH}-User=root-Group=root-WorkingDirectory=/var/lib/pulse-sensor-proxy--# Logging-StandardOutput=journal-StandardError=journal-SyslogIdentifier=pulse-sensor-cleanup--# Security hardening (less restrictive than the proxy since we need SSH access and Proxmox config access)-NoNewPrivileges=true-ProtectSystem=strict-ReadWritePaths=/var/lib/pulse-sensor-proxy /root/.ssh /etc/pve /etc/systemd/system-ProtectKernelTunables=true-ProtectKernelModules=true-ProtectControlGroups=true-PrivateTmp=true-RestrictSUIDSGID=true-RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK-LimitNOFILE=1024--[Install]-# This service is triggered by the .path unit, no need to enable it directly-SERVICE_EOF--# Enable and start the path unit-systemctl daemon-reload || true-systemctl enable pulse-sensor-cleanup.path-systemctl start pulse-sensor-cleanup.path--print_info "Cleanup system installed and enabled"--# Configure SSH keys for cluster temperature monitoring-print_info "Configuring proxy SSH access to cluster nodes..."--# Wait for proxy to generate SSH keys-PROXY_KEY_FILE="$SSH_DIR/id_ed25519.pub"-for i in {1..10}; do- if [[ -f "$PROXY_KEY_FILE" ]]; then- break- fi- sleep 1-done--if [[ ! -f "$PROXY_KEY_FILE" ]]; then- print_error "Proxy SSH key not generated after 10 seconds"- print_info "Check service logs: journalctl -u pulse-sensor-proxy -n 50"- exit 1-fi--PROXY_PUBLIC_KEY=$(cat "$PROXY_KEY_FILE")-print_info "Proxy public key: ${PROXY_PUBLIC_KEY:0:50}..."--# Discover cluster nodes using get_cluster_node_names helper (prefers pvesh API, falls back to pvecm CLI)-# This prefers management IPs over corosync ring IPs for multi-network clusters-CLUSTER_NODES=""-while IFS= read -r nodename; do- [[ -z "$nodename" ]] && continue- # Try to resolve hostname to IP via getent (uses /etc/hosts, then DNS)- resolved_ip=$(getent hosts "$nodename" 2>/dev/null | awk '{print $1; exit}')- if [[ -n "$resolved_ip" ]]; then- CLUSTER_NODES="${CLUSTER_NODES:+$CLUSTER_NODES }$resolved_ip"- else- # Fallback: try extracting IP directly from pvecm status for this node- if command -v pvecm >/dev/null 2>&1; then- status_ip=$(pvecm status 2>/dev/null | grep -E "0x[0-9a-f]+.*$nodename" | awk '{for(i=1;i<=NF;i++) if($i ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) {print $i; exit}}')- if [[ -n "$status_ip" ]]; then- CLUSTER_NODES="${CLUSTER_NODES:+$CLUSTER_NODES }$status_ip"- fi- fi- fi-done < <(get_cluster_node_names 2>/dev/null || true)--# Fallback to pvecm status if get_cluster_node_names didn't yield results-if [[ -z "$CLUSTER_NODES" ]] && command -v pvecm >/dev/null 2>&1; then- CLUSTER_NODES=$(pvecm status 2>/dev/null | grep -vEi "qdevice" | awk '/0x[0-9a-f]+.*[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ {for(i=1;i<=NF;i++) if($i ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) print $i}' || true)-fi--if [[ -n "$CLUSTER_NODES" ]]; then- print_info "Discovered cluster nodes: $(echo $CLUSTER_NODES | tr '\n' ' ')"-- # Configure SSH key with forced command restriction- FORCED_CMD='command="/opt/pulse/sensor-proxy/bin/pulse-sensor-wrapper.sh",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty'- AUTH_LINE="${FORCED_CMD} ${PROXY_PUBLIC_KEY} # pulse-managed-key"-- # Track SSH key push results- SSH_SUCCESS_COUNT=0- SSH_FAILURE_COUNT=0- declare -a SSH_FAILED_NODES=()- LOCAL_IPS=$(hostname -I 2>/dev/null || echo "")- LOCAL_HOSTNAMES="$(hostname 2>/dev/null || echo "") $(hostname -f 2>/dev/null || echo "")"- LOCAL_HANDLED=false-- # Push key to each cluster node- for node_ip in $CLUSTER_NODES; do- print_info "Authorizing proxy key on node $node_ip..."-- IS_LOCAL=false- # Check if node_ip matches any of the local IPs (exact match with word boundaries)- for local_ip in $LOCAL_IPS; do- if [[ "$node_ip" == "$local_ip" ]]; then- IS_LOCAL=true- break- fi- done- if [[ " $LOCAL_HOSTNAMES " == *" $node_ip "* ]]; then- IS_LOCAL=true- fi- if [[ "$node_ip" == "127.0.0.1" || "$node_ip" == "localhost" ]]; then- IS_LOCAL=true- fi-- if [[ "$IS_LOCAL" = true ]]; then- configure_local_authorized_key "$AUTH_LINE"- LOCAL_HANDLED=true- ((SSH_SUCCESS_COUNT+=1))- continue- fi-- # Ensure wrapper compatibility on remote node (supports old installations)- # Create symlink if old wrapper exists but new path doesn't- ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 root@"$node_ip" \- "if [[ -f /usr/local/bin/pulse-sensor-wrapper.sh && ! -f /opt/pulse/sensor-proxy/bin/pulse-sensor-wrapper.sh ]]; then \- mkdir -p /opt/pulse/sensor-proxy/bin && \- ln -sf /usr/local/bin/pulse-sensor-wrapper.sh /opt/pulse/sensor-proxy/bin/pulse-sensor-wrapper.sh; \- fi" 2>/dev/null || true-- # Extract just the key portion for matching (ssh-TYPE KEY_DATA)- KEY_DATA=$(echo "$AUTH_LINE" | grep -oE 'ssh-[a-z0-9-]+ [A-Za-z0-9+/=]+')-- # Check if key already exists on remote node- KEY_EXISTS=$(ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 root@"$node_ip" \- "grep -qF '$KEY_DATA' /root/.ssh/authorized_keys 2>/dev/null && echo 'yes' || echo 'no'" 2>/dev/null)-- if [[ "$KEY_EXISTS" == "yes" ]]; then- print_success "SSH key already configured on $node_ip"- ((SSH_SUCCESS_COUNT+=1))- else- # Add new key with forced command (appends, does not remove existing keys)- SSH_ERROR=$(ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 root@"$node_ip" \- "echo '${AUTH_LINE}' >> /root/.ssh/authorized_keys" 2>&1)- if [[ $? -eq 0 ]]; then- print_success "SSH key configured on $node_ip"- ((SSH_SUCCESS_COUNT+=1))- else- print_warn "Failed to configure SSH key on $node_ip"- ((SSH_FAILURE_COUNT+=1))- SSH_FAILED_NODES+=("$node_ip")- # Log detailed error for debugging- if [[ -n "$SSH_ERROR" ]]; then- print_info " Error details: $(echo "$SSH_ERROR" | head -1)"- fi- fi- fi- done-- # Print summary- print_info ""- print_info "SSH key configuration summary:"- print_info " ✓ Success: $SSH_SUCCESS_COUNT node(s)"- if [[ $SSH_FAILURE_COUNT -gt 0 ]]; then- print_warn " ✗ Failed: $SSH_FAILURE_COUNT node(s) - ${SSH_FAILED_NODES[*]}"- print_info ""- print_info "To retry failed nodes, re-run this script or manually run:"- print_info " ssh root@<node> 'echo \"${AUTH_LINE}\" >> /root/.ssh/authorized_keys'"- fi- if [[ "$LOCAL_HANDLED" = false ]]; then- configure_local_authorized_key "$AUTH_LINE"- ((SSH_SUCCESS_COUNT+=1))- fi-- # Add discovered cluster nodes to config file for allowlist validation- print_info "Updating proxy configuration with discovered cluster nodes..."- # Collect only IPs (hostnames are not used for SSH temperature collection)- all_nodes=()- for node_ip in $CLUSTER_NODES; do- all_nodes+=("$node_ip")- done- if [[ ${#CONTROL_PLANE_ALLOWED_NODE_LIST[@]} -gt 0 ]]; then- all_nodes+=("${CONTROL_PLANE_ALLOWED_NODE_LIST[@]}")- fi- # Use helper function to safely update allowed_nodes (prevents duplicates on re-run)- if ! update_allowed_nodes "Cluster nodes (auto-discovered during installation)" "${all_nodes[@]}"; then- print_error "Failed to update allowed_nodes list"- exit 1- fi-else- # No cluster found - configure standalone node- print_info "No cluster detected, configuring standalone node..."-- # Configure SSH key with forced command restriction- FORCED_CMD='command="/opt/pulse/sensor-proxy/bin/pulse-sensor-wrapper.sh",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty'- AUTH_LINE="${FORCED_CMD} ${PROXY_PUBLIC_KEY} # pulse-managed-key"-- print_info "Authorizing proxy key on localhost..."- configure_local_authorized_key "$AUTH_LINE"- print_info ""- print_info "Standalone node configuration complete"-- # Add localhost to config file for allowlist validation- print_info "Updating proxy configuration for standalone mode..."- LOCAL_IPS=$(hostname -I 2>/dev/null | tr ' ' '\n' | grep -v '^$' || echo "127.0.0.1")- # Collect all local IPs and localhost variants into array- all_nodes=()- for local_ip in $LOCAL_IPS; do- all_nodes+=("$local_ip")- done- # Always include localhost variants- all_nodes+=("127.0.0.1" "localhost")- if [[ ${#CONTROL_PLANE_ALLOWED_NODE_LIST[@]} -gt 0 ]]; then- all_nodes+=("${CONTROL_PLANE_ALLOWED_NODE_LIST[@]}")- fi- # Use helper function to safely update allowed_nodes (prevents duplicates on re-run)- if ! update_allowed_nodes "Standalone node configuration (auto-configured during installation)" "${all_nodes[@]}"; then- print_error "Failed to update allowed_nodes list"- exit 1- fi-fi--cleanup_inline_allowed_nodes--# Container-specific configuration (skip for standalone mode or if container not on this node)-if [[ "$STANDALONE" == false && "$CONTAINER_ON_THIS_NODE" == true ]]; then- echo ""- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo " Secure Container Communication Setup"- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo ""- echo "Setting up secure socket mount for temperature monitoring:"- echo " • Container communicates with host proxy via Unix socket"- echo " • No SSH keys exposed inside container (enhanced security)"- echo " • Proxy on host manages all temperature collection"- echo ""-- print_info "Configuring socket bind mount..."- MOUNT_TARGET="/mnt/pulse-proxy"- HOST_SOCKET_SOURCE="/run/pulse-sensor-proxy"- LXC_CONFIG="/etc/pve/lxc/${CTID}.conf"- LOCAL_MOUNT_ENTRY="lxc.mount.entry: ${HOST_SOCKET_SOURCE} mnt/pulse-proxy none bind,create=dir 0 0"-- mkdir -p "$HOST_SOCKET_SOURCE"-- # Back up container config before modifying- # Use timeout since /etc/pve is a FUSE filesystem that can hang- LXC_CONFIG_BACKUP=$(mktemp)- if ! timeout 10 cp "$LXC_CONFIG" "$LXC_CONFIG_BACKUP" 2>/dev/null; then- print_warn "Could not back up container config (may not exist yet or pmxcfs slow)"- LXC_CONFIG_BACKUP=""- fi-- MOUNT_UPDATED=false- CT_RUNNING=false- SKIP_CONTAINER_POST_STEPS=false- if timeout 5 pct status "$CTID" 2>/dev/null | grep -q "running"; then- CT_RUNNING=true- fi-- # /etc/pve is a FUSE filesystem (pmxcfs) - direct sed/echo don't work reliably- # Must use temp file and copy back to trigger cluster sync- # Also, config file contains snapshots sections - only modify main section (before first [)- TEMP_CONFIG=$(mktemp)- print_info "Reading container config from $LXC_CONFIG..."- if ! timeout 10 cp "$LXC_CONFIG" "$TEMP_CONFIG" 2>/dev/null; then- print_error "Timed out or failed reading container config from $LXC_CONFIG"- print_error "The Proxmox cluster filesystem (pmxcfs) may be slow or unresponsive."- print_error "Try: pvecm status # to check cluster health"- rm -f "$TEMP_CONFIG"- exit 1- fi-- # Extract line number where snapshots start (first line starting with [)- # Note: grep returns 1 if no match, which fails with pipefail - use || true to suppress- SNAPSHOT_START=$(grep -n '^\[' "$TEMP_CONFIG" | head -1 | cut -d: -f1 || true)-- if grep -Eq '^mp[0-9]+:.*pulse-sensor-proxy|^mp[0-9]+:.*mnt/pulse-proxy' "$TEMP_CONFIG" 2>/dev/null; then- print_info "Removing mp mounts for pulse-sensor-proxy to keep snapshots and migrations working"- if [ -n "$SNAPSHOT_START" ]; then- # Only modify main section (before snapshots)- sed -i "1,$((SNAPSHOT_START-1)) { /^mp[0-9]\+:.*pulse-sensor-proxy/d; /^mp[0-9]\+:.*mnt\/pulse-proxy/d }" "$TEMP_CONFIG"- else- sed -i '/^mp[0-9]\+:.*pulse-sensor-proxy/d; /^mp[0-9]\+:.*mnt\/pulse-proxy/d' "$TEMP_CONFIG"- fi- MOUNT_UPDATED=true- fi-- if grep -q "^lxc.mount.entry: .*/pulse-sensor-proxy" "$TEMP_CONFIG" 2>/dev/null; then- if ! grep -qxF "$LOCAL_MOUNT_ENTRY" "$TEMP_CONFIG"; then- print_info "Updating existing lxc.mount.entry for pulse-sensor-proxy"- if [ -n "$SNAPSHOT_START" ]; then- sed -i "1,$((SNAPSHOT_START-1)) { s#^lxc.mount.entry: .*pulse-sensor-proxy.*#${LOCAL_MOUNT_ENTRY}# }" "$TEMP_CONFIG"- else- sed -i "s#^lxc.mount.entry: .*pulse-sensor-proxy.*#${LOCAL_MOUNT_ENTRY}#" "$TEMP_CONFIG"- fi- MOUNT_UPDATED=true- else- print_info "Container already has migration-safe lxc.mount.entry for proxy"- fi- else- print_info "Adding lxc.mount.entry for pulse-sensor-proxy"- # Insert before snapshot section if it exists, otherwise append- if [ -n "$SNAPSHOT_START" ]; then- sed -i "${SNAPSHOT_START}i ${LOCAL_MOUNT_ENTRY}" "$TEMP_CONFIG"- else- echo "$LOCAL_MOUNT_ENTRY" >> "$TEMP_CONFIG"- fi- MOUNT_UPDATED=true- fi-- # Copy back to trigger pmxcfs sync- if [[ "$MOUNT_UPDATED" = true ]]; then- print_info "Writing updated config to $LXC_CONFIG..."- if ! timeout 10 cp "$TEMP_CONFIG" "$LXC_CONFIG" 2>/dev/null; then- print_error "Timed out or failed writing container config to $LXC_CONFIG"- print_error "The Proxmox cluster filesystem (pmxcfs) may be slow or unresponsive."- rm -f "$TEMP_CONFIG"- exit 1- fi- fi- rm -f "$TEMP_CONFIG"-- if ! timeout 10 pct config "$CTID" 2>/dev/null | grep -qxF "$LOCAL_MOUNT_ENTRY"; then- print_error "Failed to persist migration-safe socket mount in container config"- if [ -n "$LXC_CONFIG_BACKUP" ] && [ -f "$LXC_CONFIG_BACKUP" ]; then- print_warn "Rolling back container configuration changes..."- timeout 10 cp "$LXC_CONFIG_BACKUP" "$LXC_CONFIG" 2>/dev/null || true- rm -f "$LXC_CONFIG_BACKUP"- fi- exit 1- fi- print_info "✓ Mount configuration recorded in container config"-- if [[ "$MOUNT_UPDATED" = true ]]; then- if [[ "$SKIP_RESTART" = true ]]; then- if [[ "$CT_RUNNING" = true ]]; then- print_info "Skipping container restart (--skip-restart provided). Changes apply on next restart."- else- print_info "Skipping automatic container start (--skip-restart provided)."- fi- else- print_info "Restarting container to activate secure communication..."- if [[ "$CT_RUNNING" = true ]]; then- pct stop "$CTID" && sleep 2 && pct start "$CTID"- else- pct start "$CTID"- fi- sleep 5- CT_RUNNING=true- fi- fi-- # Verify socket directory and file inside container- if [[ "$SKIP_RESTART" = true && "$CT_RUNNING" = true && "$MOUNT_UPDATED" = true ]]; then- print_warn "Skipping socket verification until container $CTID is restarted."- print_warn "Please restart container and verify socket manually:"- print_warn " pct stop $CTID && sleep 2 && pct start $CTID"- print_warn " pct exec $CTID -- test -S ${MOUNT_TARGET}/pulse-sensor-proxy.sock && echo 'Socket OK'"- elif [[ "$SKIP_RESTART" = true && "$CT_RUNNING" = false ]]; then- print_warn "Socket verification deferred. Start container $CTID and run:"- print_warn " pct exec $CTID -- test -S ${MOUNT_TARGET}/pulse-sensor-proxy.sock && echo 'Socket OK'"- SKIP_CONTAINER_POST_STEPS=true- elif [[ "$CT_RUNNING" = false ]]; then- print_warn "Container $CTID is stopped. Start it to verify the pulse-sensor-proxy socket:"- print_warn " pct start $CTID && pct exec $CTID -- test -S ${MOUNT_TARGET}/pulse-sensor-proxy.sock && echo 'Socket OK'"- SKIP_CONTAINER_POST_STEPS=true- else- if [[ ! -S "$SOCKET_PATH" ]]; then- print_warn "Host proxy socket not available yet; deferring container verification until service starts."- DEFER_SOCKET_VERIFICATION=true- else- print_info "Verifying secure communication channel..."- if pct exec "$CTID" -- test -S "${MOUNT_TARGET}/pulse-sensor-proxy.sock"; then- print_info "✓ Secure socket communication ready"- # Clean up backup since verification succeeded- [ -n "$LXC_CONFIG_BACKUP" ] && rm -f "$LXC_CONFIG_BACKUP"- else- print_error "Socket not visible at ${MOUNT_TARGET}/pulse-sensor-proxy.sock"- print_error "Mount configuration verified but socket not accessible in container"- print_error "This indicates a mount or restart issue"-- # Rollback container config changes- if [ -n "$LXC_CONFIG_BACKUP" ] && [ -f "$LXC_CONFIG_BACKUP" ]; then- print_warn "Rolling back container configuration changes..."- cp "$LXC_CONFIG_BACKUP" "$LXC_CONFIG"- rm -f "$LXC_CONFIG_BACKUP"- print_info "Container configuration restored to previous state"- fi- exit 1- fi- fi- fi-- if [[ "$SKIP_CONTAINER_POST_STEPS" != true ]]; then- # Configure Pulse backend environment override inside container- print_info "Configuring Pulse to use proxy..."-- # Always make sure the Pulse .env file contains the proxy socket override.- configure_container_proxy_env-- if ! pct exec "$CTID" -- systemctl status pulse >/dev/null 2>&1; then- print_warn "Pulse service not found in container $CTID; proxy socket configured but service restart deferred."- print_info "Install or restart Pulse inside the container to enable temperature monitoring."- else- pct exec "$CTID" -- bash -lc "mkdir -p /etc/systemd/system/pulse.service.d"- pct exec "$CTID" -- bash -lc "cat <<'EOF' >/etc/systemd/system/pulse.service.d/10-pulse-proxy.conf-[Service]-Environment=PULSE_SENSOR_PROXY_SOCKET=${MOUNT_TARGET}/pulse-sensor-proxy.sock-EOF"- pct exec "$CTID" -- systemctl daemon-reload || true-- # Restart Pulse service to apply the new environment variable- if pct exec "$CTID" -- systemctl is-active --quiet pulse 2>/dev/null; then- print_info "Restarting Pulse service to apply configuration..."- pct exec "$CTID" -- systemctl restart pulse- sleep 2- print_success "Pulse service restarted with proxy configuration"- fi- fi-- # Check for and remove legacy SSH keys from container- print_info "Checking for legacy SSH keys in container..."- LEGACY_KEYS_FOUND=false- for key_type in id_rsa id_dsa id_ecdsa id_ed25519; do- if pct exec "$CTID" -- test -f "/root/.ssh/$key_type" 2>/dev/null; then- LEGACY_KEYS_FOUND=true- if [ "$QUIET" != true ]; then- print_warn "Found legacy SSH key: /root/.ssh/$key_type"- fi- pct exec "$CTID" -- rm -f "/root/.ssh/$key_type" "/root/.ssh/${key_type}.pub"- print_info " Removed /root/.ssh/$key_type"- fi- done-- if [ "$LEGACY_KEYS_FOUND" = true ] && [ "$QUIET" != true ]; then- print_info ""- print_info "Legacy SSH keys removed from container for security"- print_info ""- fi- else- if [ -n "$LXC_CONFIG_BACKUP" ] && [ -f "$LXC_CONFIG_BACKUP" ]; then- rm -f "$LXC_CONFIG_BACKUP"- fi- print_warn "Skipping container-side configuration until container $CTID is running."- fi-- # Test proxy status- print_info "Testing proxy status..."- if systemctl is-active --quiet pulse-sensor-proxy; then- print_info "${GREEN}✓${NC} pulse-sensor-proxy is running"- else- print_error "pulse-sensor-proxy is not running"- print_info "Check logs: journalctl -u pulse-sensor-proxy -n 50"- exit 1- fi-fi # End of container-specific configuration--if [[ "$SKIP_SELF_HEAL_SETUP" == "true" || "$SKIP_SELF_HEAL_SETUP" == "1" ]]; then- print_info "Skipping self-heal safeguards during self-heal run"-else- # Install self-heal safeguards to keep proxy available- print_info "Configuring self-heal safeguards..."- if ! cache_installer_for_self_heal; then- if [[ -n "$INSTALLER_CACHE_REASON" ]]; then- print_warn "Unable to cache installer script for self-heal (${INSTALLER_CACHE_REASON})"- else- print_warn "Unable to cache installer script for self-heal"- fi- fi-- cat > "$SELFHEAL_SCRIPT" <<'EOF'-#!/bin/bash-set -euo pipefail--SERVICE="pulse-sensor-proxy"-BINARY_PATH="/opt/pulse/sensor-proxy/bin/pulse-sensor-proxy"-INSTALLER="/opt/pulse/sensor-proxy/install-sensor-proxy.sh"-CTID_FILE="/etc/pulse-sensor-proxy/ctid"-PENDING_FILE="/etc/pulse-sensor-proxy/pending-control-plane.env"-TOKEN_FILE="/etc/pulse-sensor-proxy/.pulse-control-token"-CONFIG_FILE="/etc/pulse-sensor-proxy/config.yaml"-LOG_TAG="pulse-sensor-proxy-selfheal"--log() {- logger -t "$LOG_TAG" "$1"-}--sanitize_allowed_nodes() {- # Phase 2: Use config CLI instead of Python manipulation- if [[ ! -f "$CONFIG_FILE" ]]; then- return- fi-- if [[ ! -x "$BINARY_PATH" ]]; then- log "Binary not available; skipping sanitization"- return- fi-- # Use CLI to atomically migrate any inline blocks to file mode- if "$BINARY_PATH" config migrate-to-file --config "$CONFIG_FILE" 2>&1 | grep -q "Migration complete"; then- log "Migrated inline allowed_nodes to file mode"- fi-}--attempt_control_plane_reconcile() {- if [[ ! -f "$PENDING_FILE" ]]; then- return- fi- if [[ -f "$TOKEN_FILE" ]]; then- return- fi- if [[ ! -x "$INSTALLER" ]]; then- return- fi-- # shellcheck disable=SC1090- source "$PENDING_FILE" || return- if [[ -z "${PENDING_PULSE_SERVER:-}" ]]; then- return- fi-- cmd=("$INSTALLER" "--skip-restart" "--quiet" "--pulse-server" "${PENDING_PULSE_SERVER}")- if [[ "${PENDING_STANDALONE:-false}" == "true" ]]; then- cmd+=("--standalone")- if [[ "${PENDING_HTTP_MODE:-false}" == "true" ]]; then- cmd+=("--http-mode")- if [[ -n "${PENDING_HTTP_ADDR:-}" ]]; then- cmd+=("--http-addr" "${PENDING_HTTP_ADDR}")- fi- fi- else- if [[ -f "$CTID_FILE" ]]; then- cmd+=("--ctid" "$(cat "$CTID_FILE")")- else- log "CTID file missing; cannot reconcile control plane"- return- fi- fi-- if PULSE_SENSOR_PROXY_SELFHEAL=1 bash "$INSTALLER" "${cmd[@]}"; then- rm -f "$PENDING_FILE"- sanitize_allowed_nodes- else- log "Control-plane reconciliation failed"- fi-}--sanitize_allowed_nodes--if ! command -v systemctl >/dev/null 2>&1; then- exit 0-fi--# Early exit if service is healthy - no work needed-if systemctl is-active --quiet "${SERVICE}.service" 2>/dev/null; then- # Service is running - only do control plane reconcile if needed, skip everything else- attempt_control_plane_reconcile- exit 0-fi--if ! systemctl list-unit-files 2>/dev/null | grep -q "^${SERVICE}\\.service"; then- if [[ -x "$INSTALLER" && -f "$CTID_FILE" ]]; then- log "Service unit missing; attempting reinstall"- if PULSE_SENSOR_PROXY_SELFHEAL=1 bash "$INSTALLER" --ctid "$(cat "$CTID_FILE")" --skip-restart --quiet; then- sanitize_allowed_nodes- else- log "Reinstall attempt failed"- fi- fi- exit 0-fi--if ! systemctl is-active --quiet "${SERVICE}.service"; then- systemctl start "${SERVICE}.service" || true- sleep 2-fi--if ! systemctl is-active --quiet "${SERVICE}.service"; then- if [[ -x "$INSTALLER" && -f "$CTID_FILE" ]]; then- log "Service failed to start; attempting reinstall"- if PULSE_SENSOR_PROXY_SELFHEAL=1 bash "$INSTALLER" --ctid "$(cat "$CTID_FILE")" --skip-restart --quiet; then- sanitize_allowed_nodes- else- log "Reinstall attempt failed"- fi- systemctl start "${SERVICE}.service" || true- fi-fi--attempt_control_plane_reconcile-EOF-chmod 0755 "$SELFHEAL_SCRIPT"--cat > "$SELFHEAL_SERVICE_UNIT" <<EOF-[Unit]-Description=Pulse Sensor Proxy Self-Heal-After=network-online.target-Wants=network-online.target--[Service]-Type=oneshot-ExecStart=${SELFHEAL_SCRIPT}-StandardOutput=journal-StandardError=journal--[Install]-WantedBy=multi-user.target-EOF--cat > "$SELFHEAL_TIMER_UNIT" <<'EOF'-[Unit]-Description=Ensure pulse-sensor-proxy stays installed and running--[Timer]-OnBootSec=2min-OnUnitActiveSec=5min-Unit=pulse-sensor-proxy-selfheal.service--[Install]-WantedBy=timers.target-EOF-- systemctl daemon-reload- systemctl enable --now pulse-sensor-proxy-selfheal.timer >/dev/null 2>&1 || true- if [[ -f "$PENDING_CONTROL_PLANE_FILE" ]]; then- if [[ "$QUIET" != true ]]; then- print_info "Pending control-plane sync detected; will retry in background..."- fi- # Use --no-block to avoid hanging the installer if sync takes a long time- systemctl start --no-block pulse-sensor-proxy-selfheal.service >/dev/null 2>&1 || true- fi-fi--if [ "$QUIET" = true ]; then- print_success "pulse-sensor-proxy installed and running"-else- print_info "${GREEN}Installation complete!${NC}"- print_info ""- print_info "Temperature monitoring will use the secure host-side proxy"- print_info ""-- # Only show Docker configuration instructions if Pulse is actually running in Docker on this host- IS_PULSE_DOCKER=false- if command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' 2>/dev/null | grep -q '^pulse$'; then- IS_PULSE_DOCKER=true- fi-- if [[ "$STANDALONE" == true ]] && [[ "$IS_PULSE_DOCKER" == true ]]; then- echo ""- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo " Docker Container Configuration Required"- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo ""- print_info "${YELLOW}IMPORTANT:${NC} If Pulse is running in Docker, add this bind mount to your docker-compose.yml:"- echo ""- echo " volumes:"- echo " - pulse-data:/data"- echo " - /run/pulse-sensor-proxy:/run/pulse-sensor-proxy:ro"- echo ""- print_info "Then restart your Pulse container:"- echo " docker-compose down && docker-compose up -d"- echo ""- print_info "Or if using Docker directly:"- echo " docker restart pulse"- echo ""- fi-- # Check if Pulse needs to be restarted to pick up the proxy registration- PULSE_RESTART_CMD=""- if systemctl is-active --quiet pulse 2>/dev/null; then- PULSE_RESTART_CMD="systemctl restart pulse"- elif systemctl is-active --quiet pulse-hot-dev 2>/dev/null; then- PULSE_RESTART_CMD="systemctl restart pulse-hot-dev"- elif command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' 2>/dev/null | grep -q '^pulse$'; then- PULSE_RESTART_CMD="docker restart pulse"- fi-- if [[ -n "$PULSE_RESTART_CMD" ]]; then- if [[ "$RESTART_PULSE" == true ]]; then- echo ""- print_info "Restarting Pulse to enable temperature monitoring..."- if eval "$PULSE_RESTART_CMD"; then- sleep 3- print_success "Pulse restarted successfully - temperature monitoring is now active"- else- print_warn "Failed to restart Pulse automatically. Please restart manually:"- echo " $PULSE_RESTART_CMD"- fi- echo ""- else- echo ""- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo " Pulse Restart Required"- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo ""- print_info "${YELLOW}IMPORTANT:${NC} Restart Pulse to enable temperature monitoring:"- echo " sudo $PULSE_RESTART_CMD"- echo ""- print_info "Or add --restart-pulse flag to restart automatically:"- echo " curl ... | bash -s -- ... --restart-pulse"- echo ""- fi- fi-- print_info "To check proxy status:"- print_info " systemctl status pulse-sensor-proxy"-- if [[ "$STANDALONE" == true ]]; then- echo ""- print_info "After restarting Pulse, verify the socket is accessible:"- print_info " docker exec pulse ls -l /run/pulse-sensor-proxy/pulse-sensor-proxy.sock"- echo ""- print_info "Check Pulse logs for temperature proxy detection:"- print_info " docker logs pulse | grep -i 'temperature.*proxy'"- echo ""- print_info "For detailed documentation, see:"- print_info " https://github.com/rcourtman/Pulse/blob/main/docs/TEMPERATURE_MONITORING.md"- fi-fi--exit 0diff --git a/scripts/migrate-sensor-proxy-control-plane.sh b/scripts/migrate-sensor-proxy-control-plane.shdeleted file mode 100755index 49fe10d87f..0000000000--- a/scripts/migrate-sensor-proxy-control-plane.sh+++ /dev/null@@ -1,171 +0,0 @@-#!/bin/bash--# migrate-sensor-proxy-control-plane.sh-# Adds control-plane sync to existing pulse-sensor-proxy installations.--set -euo pipefail--PULSE_SERVER=""-SKIP_RESTART=false--print_usage() {- cat <<'EOF'-Usage: migrate-sensor-proxy-control-plane.sh --pulse-server https://pulse.example.com:7655 [--skip-restart]--Adds the Pulse control-plane token/config to an existing proxy installation.-EOF-}--log() { echo "[INFO] $*"; }-warn() { echo "[WARN] $*" >&2; }-err() { echo "[ERROR] $*" >&2; }--while [[ $# -gt 0 ]]; do- case "$1" in- --pulse-server)- PULSE_SERVER="$2"- shift 2- ;;- --skip-restart)- SKIP_RESTART=true- shift- ;;- -h|--help)- print_usage- exit 0- ;;- *)- err "Unknown option: $1"- print_usage- exit 1- ;;- esac-done--if [[ $EUID -ne 0 ]]; then- err "This script must be run as root"- exit 1-fi--if [[ -z "$PULSE_SERVER" ]]; then- err "--pulse-server is required"- exit 1-fi--CONFIG_FILE="/etc/pulse-sensor-proxy/config.yaml"-TOKEN_FILE="/etc/pulse-sensor-proxy/.pulse-control-token"--if [[ ! -f "$CONFIG_FILE" ]]; then- err "Config file not found at $CONFIG_FILE"- exit 1-fi--SHORT_HOSTNAME=$(hostname -s 2>/dev/null || hostname | cut -d'.' -f1)-register_proxy() {- local mode="$1"- local payload="{\"hostname\":\"${SHORT_HOSTNAME}\",\"proxy_url\":\"\",\"mode\":\"${mode}\"}"- curl -fsSL -X POST \- -H "Content-Type: application/json" \- -d "$payload" \- "${PULSE_SERVER%/}/api/temperature-proxy/register"-}--log "Registering proxy with Pulse..."-REGISTRATION_RESPONSE=$(register_proxy "socket") || {- err "Registration failed"- exit 1-}--CONTROL_TOKEN=$(echo "$REGISTRATION_RESPONSE" | grep -o '"control_token":"[^"]*"' | head -1 | cut -d'"' -f4)-REFRESH_INTERVAL=$(echo "$REGISTRATION_RESPONSE" | grep -o '"refresh_interval":[0-9]*' | head -1 | awk -F: '{print $2}')-if [[ -z "$CONTROL_TOKEN" ]]; then- err "Pulse did not return a control token. Response: $REGISTRATION_RESPONSE"- exit 1-fi-if [[ -z "$REFRESH_INTERVAL" ]]; then- REFRESH_INTERVAL=60-fi--log "Writing control-plane token..."-mkdir -p "$(dirname "$TOKEN_FILE")"-echo "$CONTROL_TOKEN" > "$TOKEN_FILE"-chmod 600 "$TOKEN_FILE"-chown pulse-sensor-proxy:pulse-sensor-proxy "$TOKEN_FILE"--update_config_atomically() {- # Phase 2: Use atomic write to prevent corruption- # NOTE: This script is for one-time migration from v4.31 to v4.32+- # It uses atomic write but doesn't use config.yaml.lock (minor race risk)- # Future: Deprecate this script once all users are on v4.32+-- # Create temp file in same directory to ensure rename is atomic- local config_dir- config_dir=$(dirname "$CONFIG_FILE")- local temp_file- temp_file=$(mktemp "$config_dir/.config.XXXXXX")-- # Remove old control plane blocks and add new one atomically- python3 - "$CONFIG_FILE" "$temp_file" <<'PY'-from pathlib import Path-import sys-config_path = Path(sys.argv[1])-temp_path = Path(sys.argv[2])-if not config_path.exists():- sys.exit(0)-lines = config_path.read_text().splitlines(keepends=True)-result = []-i = 0-while i < len(lines):- line = lines[i]- if line.startswith("# Pulse control plane configuration"):- i += 1- while i < len(lines) and (lines[i].startswith(" ") or lines[i].startswith("\t") or lines[i].strip() == ""):- i += 1- continue- if line.startswith("pulse_control_plane:"):- i += 1- while i < len(lines) and (lines[i].startswith(" ") or lines[i].startswith("\t") or lines[i].strip() == ""):- i += 1- continue- result.append(line)- i += 1-temp_path.write_text("".join(result))-PY-- # Append new control plane config- cat >> "$temp_file" <<EOF--# Pulse control plane configuration (added by migrate-sensor-proxy-control-plane.sh)-pulse_control_plane:- url: "$PULSE_SERVER"- token_file: "$TOKEN_FILE"- refresh_interval: $REFRESH_INTERVAL-EOF-- # Atomic rename- mv "$temp_file" "$CONFIG_FILE"- chmod 644 "$CONFIG_FILE"- chown pulse-sensor-proxy:pulse-sensor-proxy "$CONFIG_FILE" 2>/dev/null || true-}--log "Stopping service to prevent config file races..."-if systemctl is-active --quiet pulse-sensor-proxy; then- systemctl stop pulse-sensor-proxy- SERVICE_WAS_RUNNING=true-else- SERVICE_WAS_RUNNING=false-fi--log "Updating config..."-update_config_atomically--if [[ "$SKIP_RESTART" == false ]] && [[ "$SERVICE_WAS_RUNNING" == true ]]; then- log "Starting pulse-sensor-proxy..."- systemctl start pulse-sensor-proxy-elif [[ "$SERVICE_WAS_RUNNING" == false ]]; then- log "Service was not running; leaving stopped"-else- warn "Skipping service restart; control-plane sync will start on next restart"-fi--log "Migration complete."diff --git a/scripts/migrate-temperature-proxy.sh b/scripts/migrate-temperature-proxy.shdeleted file mode 100755index 603cba0050..0000000000--- a/scripts/migrate-temperature-proxy.sh+++ /dev/null@@ -1,109 +0,0 @@-#!/bin/bash--# migrate-temperature-proxy.sh-# Converts SSH-based temperature collection to pulse-sensor-proxy on standalone hosts.--set -euo pipefail--PULSE_SERVER=""-KEEP_SSH_KEYS=false-SKIP_RESTART=false--print_usage() {- cat <<'EOF'-Usage: migrate-temperature-proxy.sh --pulse-server https://pulse.example.com:7655 [--keep-ssh-keys] [--skip-restart]--Installs pulse-sensor-proxy in standalone mode and removes legacy SSH fallback keys.-EOF-}--log() { echo "[INFO] $*"; }-warn() { echo "[WARN] $*" >&2; }-err() { echo "[ERROR] $*" >&2; }--while [[ $# -gt 0 ]]; do- case "$1" in- --pulse-server)- PULSE_SERVER="$2"- shift 2- ;;- --keep-ssh-keys)- KEEP_SSH_KEYS=true- shift- ;;- --skip-restart)- SKIP_RESTART=true- shift- ;;- -h|--help)- print_usage- exit 0- ;;- *)- err "Unknown option: $1"- print_usage- exit 1- ;;- esac-done--if [[ $EUID -ne 0 ]]; then- err "This script must be run as root"- exit 1-fi--if [[ -z "$PULSE_SERVER" ]]; then- err "--pulse-server is required"- exit 1-fi--INSTALLER_URL="${PULSE_SERVER%/}/api/install/install-sensor-proxy.sh"-INSTALLER=$(mktemp)-cleanup() {- rm -f "$INSTALLER"-}-trap cleanup EXIT--log "Downloading pulse-sensor-proxy installer from $INSTALLER_URL"-if ! curl -fsSL "$INSTALLER_URL" -o "$INSTALLER"; then- err "Failed to download installer script"- exit 1-fi-chmod +x "$INSTALLER"--INSTALL_ARGS=(--standalone --http-mode --pulse-server "$PULSE_SERVER")-if [[ "$SKIP_RESTART" == true ]]; then- INSTALL_ARGS+=(--skip-restart)-fi--log "Running pulse-sensor-proxy installer..."-if ! "$INSTALLER" "${INSTALL_ARGS[@]}"; then- err "pulse-sensor-proxy installation failed"- exit 1-fi--remove_legacy_keys() {- local auth="/root/.ssh/authorized_keys"- if [[ ! -f "$auth" ]]; then- return- fi- local tmp- tmp=$(mktemp)- if grep -v -E '# pulse-sensors|# pulse-proxy-key' "$auth" > "$tmp"; then- chmod --reference="$auth" "$tmp" 2>/dev/null || chmod 600 "$tmp"- chown --reference="$auth" "$tmp" 2>/dev/null || true- mv "$tmp" "$auth"- log "Removed legacy SSH fallback keys from $auth"- else- rm -f "$tmp"- fi-}--if [[ "$KEEP_SSH_KEYS" == false ]]; then- remove_legacy_keys-else- warn "Legacy SSH keys retained at user request (--keep-ssh-keys)"-fi--log "Migration complete. This host now uses pulse-sensor-proxy for temperature collection."-log "Verify status with: systemctl status pulse-sensor-proxy --no-pager"diff --git a/scripts/pulse-proxy-rotate-keys.sh b/scripts/pulse-proxy-rotate-keys.shdeleted file mode 100755index c448cf3360..0000000000--- a/scripts/pulse-proxy-rotate-keys.sh+++ /dev/null@@ -1,314 +0,0 @@-#!/usr/bin/env bash-# pulse-proxy-rotate-keys.sh-# Rotate pulse-sensor-proxy SSH keys with staging, verification, and rollback support.--set -euo pipefail--BASE_DIR="/var/lib/pulse-sensor-proxy"-ACTIVE_DIR="${BASE_DIR}/ssh"-POOL_DIR="${BASE_DIR}/ssh.d"-STAGING_DIR="${POOL_DIR}/next"-BACKUP_DIR="${POOL_DIR}/prev"-SOCKET_PATH="/run/pulse-sensor-proxy/pulse-sensor-proxy.sock"-SCRIPT_TAG="pulse-proxy-rotate"-SSH_KEY_TYPE="ed25519"-SSH_KEY_COMMENT="pulse-sensor-proxy"-SSH_KEY_FILE="id_${SSH_KEY_TYPE}"--dry_run=false-do_rollback=false--usage() {- cat <<'EOF'-Usage: pulse-proxy-rotate-keys.sh [--dry-run] [--rollback]--Options:- --dry-run Walk through all steps without modifying state or contacting nodes.- --rollback Restore the previously active keypair (requires ssh.d/prev).- -h, --help Show this help.--Examples:- ./pulse-proxy-rotate-keys.sh --dry-run- ./pulse-proxy-rotate-keys.sh- ./pulse-proxy-rotate-keys.sh --rollback-EOF-}--log_info() { logger -t "${SCRIPT_TAG}" "INFO: $*"; printf '[INFO] %s\n' "$*"; }-log_warn() { logger -t "${SCRIPT_TAG}" "WARN: $*"; printf '[WARN] %s\n' "$*"; }-log_error() { logger -t "${SCRIPT_TAG}" "ERROR: $*"; printf '[ERROR] %s\n' "$*" >&2; }--require_root() {- if (( EUID != 0 )); then- log_error "This script must be run as root."- exit 1- fi-}--require_cmds() {- local missing=()- for cmd in ssh-keygen ssh jq socat python3 stat mkdir; do- if ! command -v "$cmd" >/dev/null 2>&1; then- missing+=("$cmd")- fi- done- if ((${#missing[@]} > 0)); then- log_error "Missing required commands: ${missing[*]}"- exit 1- fi-}--parse_args() {- while (($#)); do- case "$1" in- --dry-run) dry_run=true ;;- --rollback) do_rollback=true ;;- -h|--help) usage; exit 0 ;;- *) log_error "Unknown option: $1"; usage; exit 1 ;;- esac- shift- done- if $dry_run && $do_rollback; then- log_error "Cannot combine --dry-run and --rollback."- exit 1- fi-}--ensure_socket() {- if [[ ! -S "$SOCKET_PATH" ]]; then- log_error "Proxy socket not found at $SOCKET_PATH. Is pulse-sensor-proxy running?"- exit 1- fi-}--run_cmd() {- if $dry_run; then- log_info "[dry-run] $*"- else- "$@"- fi-}--json_rpc() {- local method=$1- local params_json=${2:-"{}"}- local response- if $dry_run; then- log_info "[dry-run] would call RPC ${method} with params ${params_json}"- printf '{"success":true,"data":{}}'- return 0- fi-- response=$(SOCKET="$SOCKET_PATH" METHOD="$method" PARAMS="$params_json" python3 - <<'PY'-import json-import os-import socket-import sys-import uuid--sock_path = os.environ["SOCKET"]-method = os.environ["METHOD"]-params = json.loads(os.environ["PARAMS"]) if os.environ["PARAMS"] else {}-payload = {- "correlation_id": str(uuid.uuid4()),- "method": method,- "params": params,-}--data = (json.dumps(payload) + "\n").encode()-with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:- sock.connect(sock_path)- sock.sendall(data)- sock.shutdown(socket.SHUT_WR)- chunks = []- while True:- chunk = sock.recv(65536)- if not chunk:- break- chunks.append(chunk)- sys.stdout.write(b"".join(chunks).decode())-PY-) || {- log_error "RPC '${method}' failed to execute."- exit 1- }- echo "$response"-}--require_success() {- local resp=$1- local method=$2- local ok- ok=$(echo "$resp" | jq -r '.success // false')- if [[ "$ok" != "true" ]]; then- local err- err=$(echo "$resp" | jq -r '.error // empty')- log_error "RPC '${method}' failed: ${err:-unknown error}"- exit 1- fi-}--prepare_dirs() {- for dir in "$BASE_DIR" "$POOL_DIR" "$STAGING_DIR"; do- if $dry_run; then- log_info "[dry-run] ensure directory $dir owned by pulse-proxy:pulse-proxy"- continue- fi- mkdir -p "$dir"- chown pulse-proxy:pulse-proxy "$dir"- chmod 0750 "$dir"- done-}--clean_staging() {- if [[ -d "$STAGING_DIR" ]]; then- if $dry_run; then- log_info "[dry-run] would remove existing staging directory $STAGING_DIR"- else- rm -rf "$STAGING_DIR"- mkdir -p "$STAGING_DIR"- chown pulse-proxy:pulse-proxy "$STAGING_DIR"- chmod 0750 "$STAGING_DIR"- fi- fi-}--generate_keypair() {- local key_path="$STAGING_DIR/${SSH_KEY_FILE}"- if $dry_run; then- log_info "[dry-run] would generate new ${SSH_KEY_TYPE} keypair at $key_path"- return- fi- clean_staging- log_info "Generating new ${SSH_KEY_TYPE} keypair in staging..."- ssh-keygen -t "$SSH_KEY_TYPE" -N '' -C "$SSH_KEY_COMMENT rotation $(date -u +%Y%m%dT%H%M%SZ)" -f "$key_path" >/dev/null- chown pulse-proxy:pulse-proxy "$key_path" "${key_path}.pub"- chmod 0600 "$key_path"- chmod 0640 "${key_path}.pub"-}--ensure_cluster_keys() {- local key_dir=$1- local payload- payload=$(jq -cn --arg dir "$key_dir" '{key_dir: $dir}')- local resp- resp=$(json_rpc "ensure_cluster_keys" "$payload")- require_success "$resp" "ensure_cluster_keys"- log_info "Proxy reported successful key distribution."-}--list_nodes() {- local resp- resp=$(json_rpc "register_nodes")- require_success "$resp" "register_nodes"- echo "$resp" | jq -r '.data.nodes[]?.name // empty' | sort -u-}--verify_nodes() {- local key_file="$1"- local -a bad_nodes=()- local rc- while read -r node; do- [[ -z "$node" ]] && continue- log_info "Verifying SSH access on ${node}..."- if $dry_run; then- log_info "[dry-run] would run ssh -i $key_file root@${node} sensors -j"- continue- fi- if ssh -i "$key_file" -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=10 "root@${node}" "sensors -j" >/dev/null 2>&1; then- log_info "Verification succeeded for ${node}."- else- log_warn "Verification failed for ${node}."- bad_nodes+=("$node")- fi- done < <(list_nodes)-- if ((${#bad_nodes[@]} > 0)); then- log_error "Verification failed for: ${bad_nodes[*]}"- exit 1- fi-}--swap_keys() {- local timestamp- timestamp=$(date -u +%Y%m%dT%H%M%SZ)-- if $dry_run; then- log_info "[dry-run] would rotate directories:"- log_info "[dry-run] mv ${BACKUP_DIR} ${POOL_DIR}/prev.${timestamp} (if exists)"- log_info "[dry-run] mv ${ACTIVE_DIR} ${BACKUP_DIR}"- log_info "[dry-run] mv ${STAGING_DIR} ${ACTIVE_DIR}"- return- fi-- log_info "Activating new keypair..."- if [[ -d "$BACKUP_DIR" ]]; then- mv "$BACKUP_DIR" "${POOL_DIR}/prev.${timestamp}"- fi- mv "$ACTIVE_DIR" "$BACKUP_DIR"- mv "$STAGING_DIR" "$ACTIVE_DIR"- chown -R pulse-proxy:pulse-proxy "$ACTIVE_DIR" "$BACKUP_DIR"- chmod 0750 "$ACTIVE_DIR" "$BACKUP_DIR"- chmod 0600 "$ACTIVE_DIR/${SSH_KEY_FILE}"- chmod 0640 "$ACTIVE_DIR/${SSH_KEY_FILE}.pub"- log_info "Key rotation complete. Previous keys stored at ${BACKUP_DIR}."-}--rollback_keys() {- if [[ ! -d "$BACKUP_DIR" ]]; then- log_error "No backup directory (${BACKUP_DIR}) present. Cannot rollback."- exit 1- fi- local timestamp- timestamp=$(date -u +%Y%m%dT%H%M%SZ)-- if $dry_run; then- log_info "[dry-run] would rollback by swapping ${ACTIVE_DIR} with ${BACKUP_DIR}"- return- fi-- log_warn "Rolling back to previous keypair..."- local failed_dir="${POOL_DIR}/failed.${timestamp}"- if [[ -d "$ACTIVE_DIR" ]]; then- mv "$ACTIVE_DIR" "$failed_dir"- fi- mv "$BACKUP_DIR" "$ACTIVE_DIR"- chown -R pulse-proxy:pulse-proxy "$ACTIVE_DIR"- chmod 0600 "$ACTIVE_DIR/${SSH_KEY_FILE}"- chmod 0640 "$ACTIVE_DIR/${SSH_KEY_FILE}.pub"- log_info "Rollback complete. Old keys preserved at ${failed_dir}."-- log_info "Re-pushing restored keypair to cluster nodes..."- ensure_cluster_keys "$ACTIVE_DIR"-}--main() {- parse_args "$@"- require_root- require_cmds-- if $do_rollback; then- ensure_socket- rollback_keys- return- fi-- prepare_dirs- ensure_socket-- generate_keypair-- local staging_key="${STAGING_DIR}/${SSH_KEY_FILE}"- if [[ ! -f "${staging_key}" && $dry_run == false ]]; then- log_error "Staged private key missing at ${staging_key}"- exit 1- fi-- ensure_cluster_keys "$STAGING_DIR"- verify_nodes "$staging_key"- swap_keys-- log_info "Rotation workflow finished successfully."-}--main "$@"diff --git a/scripts/pulse-sensor-cleanup.sh b/scripts/pulse-sensor-cleanup.shdeleted file mode 100755index c6d831a1fb..0000000000--- a/scripts/pulse-sensor-cleanup.sh+++ /dev/null@@ -1,286 +0,0 @@-#!/bin/bash--# pulse-sensor-cleanup.sh - Complete Pulse footprint removal when nodes are removed-# Removes: SSH keys, proxy service, binaries, API tokens, and LXC bind mounts-# This script is triggered by systemd path unit when cleanup-request.json is created--set -euo pipefail--# Configuration-WORK_DIR="/var/lib/pulse-sensor-proxy"-CLEANUP_REQUEST="${WORK_DIR}/cleanup-request.json"-LOCKFILE="${WORK_DIR}/cleanup.lock"-LOG_TAG="pulse-sensor-cleanup"-INSTALLER_PATH="/opt/pulse/sensor-proxy/install-sensor-proxy.sh"--# Logging functions-log_info() {- logger -t "$LOG_TAG" -p user.info "$1"- echo "[INFO] $1"-}--log_warn() {- logger -t "$LOG_TAG" -p user.warning "$1"- echo "[WARN] $1"-}--log_error() {- logger -t "$LOG_TAG" -p user.err "$1"- echo "[ERROR] $1" >&2-}--# Acquire exclusive lock to prevent concurrent cleanup runs-exec 200>"$LOCKFILE"-if ! flock -n 200; then- log_info "Another cleanup instance is running, exiting"- exit 0-fi--# Check if cleanup request file exists-if [[ ! -f "$CLEANUP_REQUEST" ]]; then- log_info "No cleanup request found at $CLEANUP_REQUEST"- exit 0-fi--log_info "Processing cleanup request from $CLEANUP_REQUEST"--# Read and parse the cleanup request-CLEANUP_DATA=$(cat "$CLEANUP_REQUEST")-HOST=$(echo "$CLEANUP_DATA" | grep -o '"host":"[^"]*"' | cut -d'"' -f4 || echo "")-REQUESTED_AT=$(echo "$CLEANUP_DATA" | grep -o '"requestedAt":"[^"]*"' | cut -d'"' -f4 || echo "")--log_info "Cleanup requested at: ${REQUESTED_AT:-unknown}"--# Rename request file to .processing to prevent re-triggering while allowing retry on failure-PROCESSING_FILE="${CLEANUP_REQUEST}.processing"-mv "$CLEANUP_REQUEST" "$PROCESSING_FILE" 2>/dev/null || {- log_warn "Failed to rename cleanup request file, may have been processed by another instance"- exit 0-}--# If no specific host was provided, clean up all known nodes-if [[ -z "$HOST" ]]; then- log_info "No specific host provided - cleaning up all cluster nodes"-- # Discover cluster nodes- if command -v pvecm >/dev/null 2>&1; then- CLUSTER_NODES=$(pvecm status 2>/dev/null | grep -vEi "qdevice" | awk '/0x[0-9a-f]+.*[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ {for(i=1;i<=NF;i++) if($i ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) print $i}' || true)-- if [[ -n "$CLUSTER_NODES" ]]; then- for node_ip in $CLUSTER_NODES; do- log_info "Cleaning up SSH keys on node $node_ip"-- # Remove both pulse-managed-key and pulse-proxy-key entries- ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 root@"$node_ip" \- "sed -i -e '/# pulse-managed-key\$/d' -e '/# pulse-proxy-key\$/d' /root/.ssh/authorized_keys" 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "Failed to clean up SSH keys on $node_ip"- done- log_info "Cluster cleanup completed"- else- # Standalone node - clean up localhost- log_info "Standalone node detected - cleaning up localhost"- sed -i -e '/# pulse-managed-key$/d' -e '/# pulse-proxy-key$/d' /root/.ssh/authorized_keys 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "Failed to clean up SSH keys on localhost"- fi- else- log_warn "pvecm command not available - cleaning up localhost only"- sed -i -e '/# pulse-managed-key$/d' -e '/# pulse-proxy-key$/d' /root/.ssh/authorized_keys 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "Failed to clean up SSH keys on localhost"- fi-else- log_info "Cleaning up specific host: $HOST"-- # Extract hostname/IP from host URL- HOST_CLEAN=$(echo "$HOST" | sed -e 's|^https\?://||' -e 's|:.*$||')-- # Check if this is localhost (by IP, hostname, or FQDN)- LOCAL_IPS=$(hostname -I 2>/dev/null || echo "")- LOCAL_HOSTNAME=$(hostname 2>/dev/null || echo "")- LOCAL_FQDN=$(hostname -f 2>/dev/null || echo "")- IS_LOCAL=false-- # Check against all local IPs- for local_ip in $LOCAL_IPS; do- if [[ "$HOST_CLEAN" == "$local_ip" ]]; then- IS_LOCAL=true- break- fi- done-- # Check against hostname and FQDN- if [[ "$HOST_CLEAN" == "127.0.0.1" || "$HOST_CLEAN" == "localhost" || \- "$HOST_CLEAN" == "$LOCAL_HOSTNAME" || "$HOST_CLEAN" == "$LOCAL_FQDN" ]]; then- IS_LOCAL=true- fi-- if [[ "$IS_LOCAL" == true ]]; then- log_info "Performing full cleanup on localhost"-- # 1. Remove SSH keys- log_info "Removing SSH keys from authorized_keys"- sed -i -e '/# pulse-managed-key$/d' -e '/# pulse-proxy-key$/d' /root/.ssh/authorized_keys 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "Failed to clean up SSH keys"-- # 2. Delete API tokens and user- log_info "Removing Proxmox API tokens and pulse-monitor user"- if command -v pveum >/dev/null 2>&1; then- # Try JSON output first (pveum with --output-format json)- TOKEN_IDS=""- if command -v python3 >/dev/null 2>&1; then- # Try pveum with JSON output- if TOKEN_JSON=$(pveum user token list pulse-monitor@pam --output-format json 2>/dev/null); then- TOKEN_IDS=$(echo "$TOKEN_JSON" | python3 -c '-import sys, json-try:- data = json.load(sys.stdin)- if isinstance(data, list):- for item in data:- if "tokenid" in item:- print(item["tokenid"])-except: pass-' || true)- fi- fi-- # Fall back to pvesh JSON API if pveum JSON didn't work- if [[ -z "$TOKEN_IDS" ]] && command -v pvesh >/dev/null 2>&1; then- if TOKEN_JSON=$(pvesh get /access/users/pulse-monitor@pam/token 2>/dev/null); then- TOKEN_IDS=$(echo "$TOKEN_JSON" | python3 -c '-import sys, json-try:- data = json.load(sys.stdin)- if isinstance(data, dict) and "data" in data:- for item in data["data"]:- if "tokenid" in item:- print(item["tokenid"])-except: pass-' 2>/dev/null || true)- fi- fi-- # Last resort: parse table output with better filtering- if [[ -z "$TOKEN_IDS" ]]; then- TOKEN_IDS=$(pveum user token list pulse-monitor@pam 2>/dev/null | \- awk 'NR>1 && /^[[:space:]]*pulse/ {print $1}' | grep -v '^[│┌└╞─]' | grep -v '^$' || true)- fi-- if [[ -n "$TOKEN_IDS" ]]; then- for token_id in $TOKEN_IDS; do- log_info "Deleting API token: $token_id"- pveum user token remove pulse-monitor@pam "${token_id}" 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "Failed to delete token $token_id"- done- else- log_info "No API tokens found for pulse-monitor@pam"- fi-- # Remove the pulse-monitor user- log_info "Removing pulse-monitor@pam user"- pveum user delete pulse-monitor@pam 2>&1 | \- logger -t "$LOG_TAG" -p user.info || \- log_warn "pulse-monitor@pam user not found or already removed"- else- log_warn "pveum command not available, skipping API token cleanup"- fi-- # 3. Remove LXC bind mounts- log_info "Removing LXC bind mounts from container configs"- if command -v pct >/dev/null 2>&1; then- for ctid in $(pct list 2>/dev/null | awk 'NR>1 {print $1}' || true); do- CONF_FILE="/etc/pve/lxc/${ctid}.conf"- if [[ -f "$CONF_FILE" ]]; then- # Find pulse-sensor-proxy mount points and remove them using pct- for mp_key in $(grep -o "^mp[0-9]\+:" "$CONF_FILE" | grep -f <(grep "pulse-sensor-proxy" "$CONF_FILE" | grep -o "^mp[0-9]\+:") || true); do- mp_num="${mp_key%:}"- log_info "Removing ${mp_num} (pulse-sensor-proxy) from container $ctid"- if pct set "$ctid" -delete "${mp_num}" 2>&1 | logger -t "$LOG_TAG" -p user.info; then- log_info "Successfully removed ${mp_num} from container $ctid"- else- log_warn "Failed to remove ${mp_num} from container $ctid"- fi- done- fi- done- fi-- # 4. Uninstall proxy service and remove binaries via isolated transient unit- log_info "Starting full uninstallation (service, binaries, configs)"- if [[ -x "$INSTALLER_PATH" ]]; then- # Use systemd-run to create isolated transient unit that won't be killed- # when we stop pulse-sensor-proxy.service- if command -v systemd-run >/dev/null 2>&1; then- # Use UUID for unique unit name (prevents same-second collisions)- UNINSTALL_UUID=$(cat /proc/sys/kernel/random/uuid 2>/dev/null || date +%s%N)- UNINSTALL_UNIT="pulse-uninstall-${UNINSTALL_UUID}"- log_info "Spawning isolated uninstaller unit: $UNINSTALL_UNIT"-- systemd-run \- --unit="${UNINSTALL_UNIT}" \- --property="Type=oneshot" \- --property="Conflicts=pulse-sensor-proxy.service" \- --collect \- --wait \- --quiet \- -- bash -c "$INSTALLER_PATH --uninstall --purge --quiet >> /var/log/pulse/sensor-proxy/uninstall.log 2>&1" \- 2>&1 | logger -t "$LOG_TAG" -p user.info-- UNINSTALL_EXIT=$?- if [[ $UNINSTALL_EXIT -eq 0 ]]; then- log_info "Uninstaller completed successfully"- else- log_error "Uninstaller failed with exit code $UNINSTALL_EXIT"- exit 1- fi- else- log_warn "systemd-run not available, attempting direct uninstall (may fail)"- bash "$INSTALLER_PATH" --uninstall --quiet >> /var/log/pulse/sensor-proxy/uninstall.log 2>&1 || \- log_error "Uninstaller failed - manual cleanup may be required"- fi- else- log_warn "Installer not found at $INSTALLER_PATH, cannot run uninstaller"- log_info "Manual cleanup required: systemctl stop pulse-sensor-proxy && systemctl disable pulse-sensor-proxy"- fi-- log_info "Localhost cleanup initiated (uninstaller running in background)"- else- log_info "Cleaning up remote host: $HOST_CLEAN"-- # Try to use proxy's SSH key first (for standalone nodes), fall back to default- PROXY_KEY="/var/lib/pulse-sensor-proxy/ssh/id_ed25519"- SSH_CMD="ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5"-- if [[ -f "$PROXY_KEY" ]]; then- log_info "Using proxy SSH key for cleanup"- SSH_CMD="$SSH_CMD -i $PROXY_KEY"- fi-- # Remove both pulse-managed-key and pulse-proxy-key entries from remote host- CLEANUP_OUTPUT=$($SSH_CMD root@"$HOST_CLEAN" \- "sed -i -e '/# pulse-managed-key\$/d' -e '/# pulse-proxy-key\$/d' /root/.ssh/authorized_keys && echo 'SUCCESS'" 2>&1)-- if echo "$CLEANUP_OUTPUT" | grep -q "SUCCESS"; then- log_info "Successfully cleaned up SSH keys on $HOST_CLEAN"- else- # Check if this is a standalone node with forced commands (common case)- if echo "$CLEANUP_OUTPUT" | grep -q "cpu_thermal\|coretemp\|k10temp"; then- log_warn "Cannot cleanup standalone node $HOST_CLEAN (forced command prevents cleanup)"- log_info "Standalone node keys are read-only (sensors -j) - low security risk"- log_info "Manual cleanup: ssh root@$HOST_CLEAN \"sed -i '/# pulse-proxy-key\$/d' /root/.ssh/authorized_keys\""- else- log_error "Failed to clean up SSH keys on $HOST_CLEAN: $CLEANUP_OUTPUT"- exit 1- fi- fi- fi-fi--# Remove processing file on success-rm -f "$PROCESSING_FILE"--log_info "Cleanup completed successfully"-exit 0diff --git a/scripts/pulse-sensor-proxy.service b/scripts/pulse-sensor-proxy.servicedeleted file mode 100644index aad44d7e78..0000000000--- a/scripts/pulse-sensor-proxy.service+++ /dev/null@@ -1,58 +0,0 @@-[Unit]-Description=Pulse Sensor Proxy-Documentation=https://github.com/rcourtman/Pulse-After=network.target--[Service]-Type=simple-User=pulse-sensor-proxy-Group=pulse-sensor-proxy-WorkingDirectory=/var/lib/pulse-sensor-proxy-ExecStart=/usr/local/bin/pulse-sensor-proxy-Restart=on-failure-RestartSec=5s--# Runtime dirs/sockets-RuntimeDirectory=pulse-sensor-proxy-RuntimeDirectoryMode=0775-UMask=0007--# Core hardening-NoNewPrivileges=true-ProtectSystem=strict-ProtectHome=read-only-ReadWritePaths=/var/lib/pulse-sensor-proxy-ReadWritePaths=-/run/corosync-ProtectKernelTunables=true-ProtectKernelModules=true-ProtectControlGroups=true-ProtectClock=true-PrivateTmp=true-PrivateDevices=true-ProtectProc=invisible-ProcSubset=pid-LockPersonality=true-RestrictSUIDSGID=true-RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK-RestrictNamespaces=true-SystemCallFilter=@system-service-SystemCallErrorNumber=EPERM-CapabilityBoundingSet=-AmbientCapabilities=-KeyringMode=private-LimitNOFILE=1024--# Additional hardening (post-audit)-MemoryDenyWriteExecute=true-RestrictRealtime=true-ProtectHostname=true-ProtectKernelLogs=true-SystemCallArchitectures=native--# Logging-StandardOutput=journal-StandardError=journal-SyslogIdentifier=pulse-sensor-proxy--[Install]-WantedBy=multi-user.targetdiff --git a/scripts/secure-sensor-files.sh b/scripts/secure-sensor-files.shdeleted file mode 100755index 67a940bbb9..0000000000--- a/scripts/secure-sensor-files.sh+++ /dev/null@@ -1,89 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--if [[ $EUID -ne 0 ]]; then- echo "Run as root." >&2- exit 1-fi--SERVICE_USER="pulse-sensor"-SERVICE_GROUP="$SERVICE_USER"-HOME_DIR="/opt/pulse/sensor-proxy"-BIN_PATH="$HOME_DIR/bin/pulse-sensor-proxy"-SSH_DIR="$HOME_DIR/.ssh"-PRIVATE_KEY="$SSH_DIR/id_ed25519"-PUBLIC_KEY="$SSH_DIR/id_ed25519.pub"-KNOWN_HOSTS="$SSH_DIR/known_hosts"-LOG_DIR="/var/log/pulse/sensor-proxy"-LOG_FILE="$LOG_DIR/proxy.log"-AUDIT_LOG="$LOG_DIR/audit.log"--umask 077--install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0700 "$SSH_DIR"--if [[ ! -f "$PRIVATE_KEY" ]]; then- sudo -u "$SERVICE_USER" ssh-keygen -t ed25519 -N '' -C "pulse-sensor@$(hostname -f)" -f "$PRIVATE_KEY"-else- chown "$SERVICE_USER:$SERVICE_GROUP" "$PRIVATE_KEY"- chmod 0600 "$PRIVATE_KEY"-fi--chown "$SERVICE_USER:$SERVICE_GROUP" "$PRIVATE_KEY"-chmod 0600 "$PRIVATE_KEY"--if [[ -f "$PUBLIC_KEY" ]]; then- chown "$SERVICE_USER:$SERVICE_GROUP" "$PUBLIC_KEY"- chmod 0640 "$PUBLIC_KEY"-else- sudo -u "$SERVICE_USER" ssh-keygen -y -f "$PRIVATE_KEY" >"$PUBLIC_KEY"- chown "$SERVICE_USER:$SERVICE_GROUP" "$PUBLIC_KEY"- chmod 0640 "$PUBLIC_KEY"-fi--if [[ ! -f "$KNOWN_HOSTS" ]]; then- install -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0640 /dev/null "$KNOWN_HOSTS"-else- chown "$SERVICE_USER:$SERVICE_GROUP" "$KNOWN_HOSTS"- chmod 0640 "$KNOWN_HOSTS"-fi--install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 "$LOG_DIR"--for log_path in "$LOG_FILE" "$AUDIT_LOG"; do- if [[ ! -f "$log_path" ]]; then- install -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0640 /dev/null "$log_path"- else- chown "$SERVICE_USER:$SERVICE_GROUP" "$log_path"- chmod 0640 "$log_path"- fi-- if command -v chattr >/dev/null 2>&1; then- if ! lsattr "$log_path" 2>/dev/null | grep -q 'a'; then- chattr +a "$log_path" || echo "Warning: could not set append-only attribute on $log_path" >&2- fi- else- echo "Warning: chattr not available; skipping append-only for $log_path." >&2- fi-done--if [[ -f "$BIN_PATH" ]]; then- chown root:"$SERVICE_GROUP" "$BIN_PATH"- chmod 0750 "$BIN_PATH"-fi--echo "SSH artifacts:"-ls -l "$PRIVATE_KEY" "$PUBLIC_KEY" "$KNOWN_HOSTS"--echo "Log files:"-ls -l "$LOG_FILE" "$AUDIT_LOG"-if command -v lsattr >/dev/null 2>&1; then- lsattr "$LOG_FILE" "$AUDIT_LOG" || true-fi--if [[ -f "$BIN_PATH" ]]; then- echo "Binary permissions:"- ls -l "$BIN_PATH"-fi--echo "sensor proxy file permissions secured."diff --git a/scripts/setup-log-forwarding.sh b/scripts/setup-log-forwarding.shdeleted file mode 100755index 32f4087f83..0000000000--- a/scripts/setup-log-forwarding.sh+++ /dev/null@@ -1,68 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--if [[ $EUID -ne 0 ]]; then- echo "Run as root" >&2- exit 1-fi--REMOTE_HOST=${REMOTE_HOST:-logs.pulse.example}-REMOTE_PORT=${REMOTE_PORT:-6514}-CERT_DIR=${CERT_DIR:-/etc/pulse/log-forwarding}-CA_CERT=${CA_CERT:-$CERT_DIR/ca.crt}-CLIENT_CERT=${CLIENT_CERT:-$CERT_DIR/client.crt}-CLIENT_KEY=${CLIENT_KEY:-$CERT_DIR/client.key}--install -d -m 0750 "$CERT_DIR"--CONF_PATH=/etc/rsyslog.d/pulse-sensor-proxy.conf-cat <<EOF >"$CONF_PATH"-module(load="imfile" PollingInterval="5")--input(type="imfile"- File="/var/log/pulse/sensor-proxy/audit.log"- Tag="pulse.audit"- Facility="local4"- Severity="notice"- PersistStateInterval="100"- addMetadata="on")--input(type="imfile"- File="/var/log/pulse/sensor-proxy/proxy.log"- Tag="pulse.app"- Facility="local4"- Severity="info"- PersistStateInterval="100"- addMetadata="on")--action(type="omfile"- File="/var/log/pulse/sensor-proxy/forwarding.log"- Template="RSYSLOG_TraditionalFileFormat"- DirCreateMode="0750"- FileCreateMode="0640")--if (\$programname == 'pulse.audit' or \$programname == 'pulse.app') then {- action(type="omrelp"- target="$REMOTE_HOST"- port="$REMOTE_PORT"- tls="on"- tls.caCert="$CA_CERT"- tls.myCert="$CLIENT_CERT"- tls.myPrivKey="$CLIENT_KEY"- queue.type="LinkedList"- queue.size="50000"- queue.dequeuebatchsize="500"- queue.workerthreads="2"- action.resumeRetryCount="-1")- stop-}-EOF--systemctl restart rsyslog-echo "Log forwarding enabled to $REMOTE_HOST:$REMOTE_PORT"--# Verification checklist:-# 1. sudo rsyslogd -N1 (syntax check)-# 2. sudo systemctl status rsyslog --no-pager-# 3. tail -f /var/log/pulse/sensor-proxy/forwarding.log-# 4. Confirm new `pulse.audit` events arrive on the remote collectordiff --git a/scripts/systemd/pulse-sensor-cleanup.path b/scripts/systemd/pulse-sensor-cleanup.pathdeleted file mode 100644index 76fa4a2af0..0000000000--- a/scripts/systemd/pulse-sensor-cleanup.path+++ /dev/null@@ -1,12 +0,0 @@-[Unit]-Description=Watch for Pulse sensor cleanup requests-Documentation=https://github.com/rcourtman/Pulse--[Path]-# Watch for the cleanup request file-PathChanged=/var/lib/pulse-sensor-proxy/cleanup-request.json-# Also watch for modifications-PathModified=/var/lib/pulse-sensor-proxy/cleanup-request.json--[Install]-WantedBy=multi-user.targetdiff --git a/scripts/systemd/pulse-sensor-cleanup.service b/scripts/systemd/pulse-sensor-cleanup.servicedeleted file mode 100644index f06ab90a1c..0000000000--- a/scripts/systemd/pulse-sensor-cleanup.service+++ /dev/null@@ -1,31 +0,0 @@-[Unit]-Description=Pulse Sensor Cleanup Service-Documentation=https://github.com/rcourtman/Pulse-After=network.target--[Service]-Type=oneshot-ExecStart=/usr/local/bin/pulse-sensor-cleanup.sh-User=root-Group=root-WorkingDirectory=/var/lib/pulse-sensor-proxy--# Logging-StandardOutput=journal-StandardError=journal-SyslogIdentifier=pulse-sensor-cleanup--# Security hardening (less restrictive than the proxy since we need SSH access)-NoNewPrivileges=true-ProtectSystem=strict-ReadWritePaths=/var/lib/pulse-sensor-proxy /root/.ssh-ProtectKernelTunables=true-ProtectKernelModules=true-ProtectControlGroups=true-PrivateTmp=true-RestrictSUIDSGID=true-RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK-LimitNOFILE=1024--[Install]-# This service is triggered by the .path unit, no need to enable it directlydiff --git a/scripts/tests/test-sensor-proxy-http.sh b/scripts/tests/test-sensor-proxy-http.shdeleted file mode 100755index 26a8dc1012..0000000000--- a/scripts/tests/test-sensor-proxy-http.sh+++ /dev/null@@ -1,237 +0,0 @@-#!/usr/bin/env bash-#-# Smoke test: install-sensor-proxy HTTP mode (uninstall → install → health check)--set -euo pipefail--ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"-ARTIFACT_DIR="${ROOT_DIR}/tmp/sensor-proxy-test"-LOCAL_BINARY="${ARTIFACT_DIR}/pulse-sensor-proxy-linux-amd64"-DOCKER_IMAGE="${SENSOR_PROXY_TEST_IMAGE:-debian:12}"--log() {- printf '[sensor-proxy-test] %s\n' "$*"-}--require_cmd() {- if ! command -v "$1" >/dev/null 2>&1; then- log "Missing required command: $1"- return 1- fi-}--cleanup() {- [[ -n "${CONTAINER_SCRIPT:-}" && -f "${CONTAINER_SCRIPT}" ]] && rm -f "${CONTAINER_SCRIPT}"-}-trap cleanup EXIT--main() {- if ! require_cmd go; then- log "Go toolchain is required for this test. Skipping."- return 0- fi- if ! require_cmd docker; then- log "Docker not available. Skipping sensor-proxy installer test."- return 0- fi-- mkdir -p "${ARTIFACT_DIR}"- log "Building pulse-sensor-proxy binary for test harness..."- (- cd "${ROOT_DIR}"- CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o "${LOCAL_BINARY}" ./cmd/pulse-sensor-proxy- )-- CONTAINER_SCRIPT="$(mktemp -t sensor-proxy-http-XXXXXX.sh)"- cat <<'EOS' >"${CONTAINER_SCRIPT}"-#!/usr/bin/env bash-set -euo pipefail--export DEBIAN_FRONTEND=noninteractive-apt-get update >/dev/null-apt-get install -y --no-install-recommends ca-certificates curl openssl >/dev/null--INSTALLER="/workspace/scripts/install-sensor-proxy.sh"-LOCAL_BIN="${SENSOR_PROXY_LOCAL_BINARY:-/artifacts/pulse-sensor-proxy-linux-amd64}"-STUB_DIR=/tmp/sensor-proxy-stubs-mkdir -p "${STUB_DIR}"--create_curl_stub() {- cat <<'EOF' >"${STUB_DIR}/curl"-#!/usr/bin/env bash-set -eo pipefail--args="$*"-if [[ "${args}" == *"/api/temperature-proxy/register"* ]]; then- printf '{"success":true,"token":"INTEGRATION-TOKEN","pve_instance":"integration"}\n200\n'- exit 0-fi--if [[ "${args}" == *"/api/health"* ]]; then- printf '{"status":"ok"}\n'- exit 0-fi--exec /usr/bin/curl "$@"-EOF- chmod +x "${STUB_DIR}/curl"-}--create_systemctl_stub() {- cat <<'EOF' >"${STUB_DIR}/systemctl"-#!/usr/bin/env bash-set -eo pipefail--PID_FILE=/run/pulse-sensor-proxy-test.pid-LOG_FILE=/var/log/pulse/sensor-proxy/integration.log--cmd=""-declare -a units=()-for arg in "$@"; do- case "$arg" in- start|stop|restart|status|is-active|enable|disable|daemon-reload)- cmd="$arg"- ;;- --*) ;;- *)- units+=("$arg")- ;;- esac-done--if [[ -z "${cmd}" ]]; then- exit 0-fi-if [[ ${#units[@]} -eq 0 ]]; then- units=("pulse-sensor-proxy.service")-fi--is_proxy_unit() {- local unit="$1"- [[ "$unit" == "pulse-sensor-proxy" || "$unit" == "pulse-sensor-proxy.service" ]]-}--start_proxy() {- mkdir -p "$(dirname "${LOG_FILE}")"- if [[ -f "${PID_FILE}" ]]; then- local old_pid- old_pid="$(cat "${PID_FILE}")"- kill "${old_pid}" 2>/dev/null || true- rm -f "${PID_FILE}"- fi- /usr/local/bin/pulse-sensor-proxy --config /etc/pulse-sensor-proxy/config.yaml >>"${LOG_FILE}" 2>&1 &- echo $! >"${PID_FILE}"-}--stop_proxy() {- if [[ -f "${PID_FILE}" ]]; then- local pid- pid="$(cat "${PID_FILE}")"- kill "${pid}" 2>/dev/null || true- rm -f "${PID_FILE}"- fi-}--case "${cmd}" in- start)- for unit in "${units[@]}"; do- if is_proxy_unit "${unit}"; then- start_proxy- fi- done- ;;- stop)- for unit in "${units[@]}"; do- if is_proxy_unit "${unit}"; then- stop_proxy- fi- done- ;;- restart)- stop_proxy- start_proxy- ;;- status)- if [[ -f "${PID_FILE}" && -d "/proc/$(cat "${PID_FILE}")" ]]; then- echo "pulse-sensor-proxy.service active"- exit 0- fi- echo "pulse-sensor-proxy.service inactive"- exit 3- ;;- is-active)- if [[ -f "${PID_FILE}" && -d "/proc/$(cat "${PID_FILE}")" ]]; then- exit 0- fi- exit 3- ;;- *)- ;;-esac--exit 0-EOF- chmod +x "${STUB_DIR}/systemctl"-}--assert_file_contains() {- local file="$1"- local text="$2"- if ! grep -Fq "$text" "$file"; then- echo "Assertion failed: \"$text\" not found in $file" >&2- exit 1- fi-}--assert_not_exists() {- local target="$1"- if [[ -e "$target" ]]; then- echo "Assertion failed: expected $target to be absent" >&2- exit 1- fi-}--create_curl_stub-create_systemctl_stub-export PATH="${STUB_DIR}:$PATH"--if [[ ! -f "${LOCAL_BIN}" ]]; then- echo "Local binary not found at ${LOCAL_BIN}" >&2- exit 1-fi--PULSE_FORCE_INTERACTIVE=1 bash "${INSTALLER}" \- --standalone \- --http-mode \- --pulse-server http://pulse.local:7655 \- --local-binary "${LOCAL_BIN}" >/tmp/install.log 2>&1--CONFIG_FILE="/etc/pulse-sensor-proxy/config.yaml"-assert_file_contains "${CONFIG_FILE}" "http_enabled: true"-assert_file_contains "${CONFIG_FILE}" "http_auth_token: \"INTEGRATION-TOKEN\""-assert_file_contains "${CONFIG_FILE}" "127.0.0.1/32"--/usr/bin/curl -k -s \- -H "Authorization: Bearer INTEGRATION-TOKEN" \- https://127.0.0.1:8443/health >/tmp/health.json-assert_file_contains /tmp/health.json '"status":"ok"'--PULSE_FORCE_INTERACTIVE=1 bash "${INSTALLER}" --uninstall --purge >/tmp/uninstall.log 2>&1-assert_not_exists /usr/local/bin/pulse-sensor-proxy-assert_not_exists /etc/systemd/system/pulse-sensor-proxy.service--echo "Sensor proxy HTTP installation smoke test passed."-EOS- chmod +x "${CONTAINER_SCRIPT}"-- log "Running sensor-proxy installer test in ${DOCKER_IMAGE}"- docker run --rm \- -v "${ROOT_DIR}:/workspace:ro" \- -v "${ARTIFACT_DIR}:/artifacts:ro" \- -e SENSOR_PROXY_LOCAL_BINARY="/artifacts/pulse-sensor-proxy-linux-amd64" \- "${DOCKER_IMAGE}" bash -s <"${CONTAINER_SCRIPT}"-- log "Test completed successfully."-}--main "$@"diff --git a/security/apparmor/pulse-sensor-proxy.apparmor b/security/apparmor/pulse-sensor-proxy.apparmordeleted file mode 100644index adcbc2ebdc..0000000000--- a/security/apparmor/pulse-sensor-proxy.apparmor+++ /dev/null@@ -1,75 +0,0 @@-#include <tunables/global>--profile pulse-sensor-proxy /opt/pulse/sensor-proxy/bin/pulse-sensor-proxy flags=(attach_disconnected,mediate_deleted) {- capability chown,- capability dac_override,- capability dac_read_search,- capability setgid,- capability setuid,-- network inet stream,- network inet6 stream,- network unix stream,- deny network raw,-- @{PROC}/@{pid}/fd/** r,- @{PROC}/@{pid}/cmdline r,- @{PROC}/@{pid}/stat r,- @{PROC}/@{pid}/status r,-- /opt/pulse/sensor-proxy/bin/pulse-sensor-proxy mr,- /opt/pulse/sensor-proxy/bin/* mr,- /opt/pulse/sensor-proxy/.ssh/** rwk,- /opt/pulse/sensor-proxy/etc/** r,- /opt/pulse/sensor-proxy/** r,- /var/log/pulse/sensor-proxy/** rw,- /run/pulse-sensor-proxy/** rw,-- /etc/hosts r,- /etc/hostname r,- /etc/resolv.conf r,- /etc/pulse-sensor-proxy/** r,-- /usr/bin/ssh mr,- /usr/bin/socat mr,- /usr/bin/sensors mr,- /usr/sbin/ipmitool mr,- /bin/bash mr,- /bin/sh mr,- /bin/cat mr,- /bin/echo mr,- /usr/bin/tee mr,-- /usr/lib/** mr,- /lib/** mr,-- deny /etc/shadow rwl,- deny /root/** rwxl,-- ptrace (read) peer=pulse-sensor-proxy,-- signal (receive) set=(hup term int usr1 usr2),- signal (send) set=(term) peer=pulse-sensor-proxy,-- /usr/bin/ssh ixr,- /usr/bin/sensors ixr,- /usr/sbin/ipmitool ixr,- /bin/sh ixr,- /bin/cat ixr,- /bin/echo ixr,- /usr/bin/tee ixr,-- deny mount,- deny ptrace,- deny sys_module,- deny sys_rawio,- deny sys_admin,-- @{HOME}/.cache/** rw,-- include <abstractions/base>- include <abstractions/authentication>- include <abstractions/nameservice>- include <abstractions/openssl>- include <abstractions/user-tmp>-}diff --git a/security/seccomp/pulse-sensor-proxy.json b/security/seccomp/pulse-sensor-proxy.jsondeleted file mode 100644index e1e9b65e94..0000000000--- a/security/seccomp/pulse-sensor-proxy.json+++ /dev/null@@ -1,102 +0,0 @@-{- "defaultAction": "SCMP_ACT_ERRNO",- "architectures": [- "SCMP_ARCH_X86_64",- "SCMP_ARCH_AARCH64"- ],- "syscalls": [- {- "names": [- "accept",- "accept4",- "access",- "bind",- "brk",- "capget",- "capset",- "chdir",- "chmod",- "chown",- "clock_gettime",- "close",- "connect",- "dup",- "dup2",- "epoll_create1",- "epoll_ctl",- "epoll_wait",- "eventfd2",- "execve",- "exit",- "exit_group",- "fchmod",- "fchown",- "fcntl",- "fdatasync",- "fstat",- "fsync",- "ftruncate",- "futex",- "getdents64",- "getegid",- "geteuid",- "getgid",- "getpeername",- "getpid",- "getppid",- "getrandom",- "getrlimit",- "getsockname",- "getsockopt",- "gettid",- "getuid",- "ioctl",- "lseek",- "madvise",- "mkdir",- "mmap",- "mprotect",- "munmap",- "newfstatat",- "open",- "openat",- "pipe2",- "prctl",- "pread64",- "pwrite64",- "read",- "readlink",- "recvfrom",- "recvmmsg",- "recvmsg",- "rename",- "rt_sigaction",- "rt_sigprocmask",- "rt_sigreturn",- "sendmmsg",- "sendmsg",- "sendto",- "setgid",- "setgroups",- "setrlimit",- "setsid",- "setsockopt",- "setuid",- "shutdown",- "sigaltstack",- "socket",- "socketpair",- "stat",- "statx",- "symlink",- "tgkill",- "unlink",- "unlinkat",- "wait4",- "write",- "writev"- ],- "action": "SCMP_ACT_ALLOW"- }- ]-}