Просмотр исходного кода

fix: agent match retention, agent-down alerts for agent-only routers, TLS fingerprint in installer (#855)

fix: agent match retention, agent-down alerts for agent-only routers, TLS fingerprint in installer (#855)

Closes #852, closes #850, closes #851.
Nacho 2 месяцев назад
Родитель
Сommit
329e38025e

+ 6 - 1
agent/internal/tlspin/tlspin.go

@@ -13,6 +13,7 @@ import (
 	"encoding/hex"
 	"fmt"
 	"net/http"
+	"net/url"
 	"strings"
 )
 
@@ -34,7 +35,11 @@ func BuildTransport(serverURL, fp string) (*http.Transport, error) {
 	}
 	fp = Normalize(fp)
 	if fp == "" {
-		return nil, fmt.Errorf("HTTPS requiere NETPULSE_SERVER_FP (pinning SPKI, sin InsecureSkipVerify)")
+		host := serverURL
+		if u, err := url.Parse(serverURL); err == nil && u.Host != "" {
+			host = u.Host
+		}
+		return nil, fmt.Errorf("HTTPS requiere NETPULSE_SERVER_FP (pinning SPKI, sin InsecureSkipVerify); consíguelo con install-agent.sh (lo deriva del certificado automáticamente) o con: openssl s_client -connect %s </dev/null 2>/dev/null | openssl x509 -pubkey -noout | openssl pkey -pubin -outform DER | sha256sum", host)
 	}
 	want := fp
 	t.TLSClientConfig = &tls.Config{

+ 29 - 1
install-agent.sh

@@ -20,7 +20,8 @@
 #   --token X       token del equipo (obligatorio salvo --uninstall y --pairing-token)
 #   --pairing-token X  token de pairing (bootstrap: el agente contacta al servidor
 #                   y obtiene el token real automáticamente; Fase 9 R3)
-#   --server-fp X   SHA-256 SPKI del servidor en hex (obligatorio si --server es https://)
+#   --server-fp X   SHA-256 SPKI del servidor en hex (https). Opcional: si no
+#                   se pasa, el script lo deriva del propio certificado (#851)
 #   --ssh-user X    usuario SSH del router (default: root)
 #   --ssh-key X     ruta a la identidad privada SSH (opción -i). OBLIGATORIA en
 #                   el server para routers que solo autorizan la llave del
@@ -128,6 +129,33 @@ if [ -z "$TOKEN" ] && [ -z "$PAIRING_TOKEN" ]; then
 fi
 SERVER="${SERVER%/}"
 
+# ------------------------------------------------------- TLS fingerprint ---
+# HTTPS exige pinning SPKI: el agente falla en bucle fatal sin
+# NETPULSE_SERVER_FP (#851). Si no se pasó --server-fp, lo derivamos del
+# propio certificado del servidor: quien instala ya confía en ese servidor
+# (le entrega el token) y este paso es puramente mecánico.
+case "$SERVER" in
+    https://*)
+        SERVER_FP=$(printf '%s' "$SERVER_FP" | sed -e 's|^sha256/||' -e 's|[^0-9a-fA-F]||g' | tr 'A-F' 'a-f')
+        if [ -z "$SERVER_FP" ]; then
+            HOSTPORT=${SERVER#https://}
+            HOSTPORT=${HOSTPORT%%/*}
+            SNI=${HOSTPORT%%:*}
+            case "$HOSTPORT" in *:*) : ;; *) HOSTPORT="$HOSTPORT:443" ;; esac
+            info "derivando NETPULSE_SERVER_FP del certificado de $SERVER"
+            if command -v openssl >/dev/null 2>&1; then
+                SERVER_FP=$(echo | openssl s_client -connect "$HOSTPORT" -servername "$SNI" 2>/dev/null \
+                    | openssl x509 -pubkey -noout 2>/dev/null \
+                    | openssl pkey -pubin -outform DER 2>/dev/null \
+                    | { command -v sha256sum >/dev/null 2>&1 && sha256sum || shasum -a 256; } \
+                    | cut -d' ' -f1)
+            fi
+            [ -n "$SERVER_FP" ] || fatal 14 "servidor HTTPS sin --server-fp y no pude derivarlo (¿openssl disponible? ¿SNI correcto?). Obtén el SPKI sha256 del cert y repite con --server-fp X"
+            ok "NETPULSE_SERVER_FP=$SERVER_FP"
+        fi
+        ;;
+esac
+
 ssh -o ConnectTimeout=8 -o BatchMode=yes "$SSH" true \
     || fatal 13 "no hay SSH a $SSH (¿dropbear + clave autorizada?)"
 

+ 63 - 18
server-go/internal/adapters/agent.go

@@ -37,6 +37,13 @@ type AgentState struct {
 	Version  string
 	Kind     string // "" | "native" | "external" (#288)
 	Interval int    // cadencia declarada en segundos; 0 = default nativo
+	// Host/BridgeMAC: última identidad conocida del agente (#852). Un push
+	// wireless-only (evento nl80211, BuildWireless) no lleva sección system;
+	// sin este recuerdo, MatchRouter perdería al agente hasta el próximo
+	// push completo y cada roam de un cliente provocaría un "sin cliente"
+	// transitorio en routers agent-only emparejados por hostname/MAC.
+	Host      string
+	BridgeMAC string
 }
 
 // effectiveTTL devuelve la ventana de frescura del estado: el TTL base, o
@@ -79,10 +86,27 @@ func (r *AgentRegistry) SetClock(f func() time.Time) {
 func (r *AgentRegistry) Ingest(p *probe.Payload) {
 	r.mu.Lock()
 	defer r.mu.Unlock()
-	r.states[p.Router] = &AgentState{
+	st := &AgentState{
 		Payload: p, LastSeen: r.now(), Version: p.Version,
 		Kind: p.Kind, Interval: p.Interval,
 	}
+	if sd := p.Data.System; sd != nil {
+		if sd.Board != nil {
+			st.Host = sd.Board.Hostname
+		}
+		st.BridgeMAC = sd.BridgeMAC
+	}
+	// #852: un push wireless-only no trae identidad; hereda la última
+	// conocida para que MatchRouter siga emparejando al agente.
+	if prev := r.states[p.Router]; prev != nil {
+		if st.Host == "" {
+			st.Host = prev.Host
+		}
+		if st.BridgeMAC == "" {
+			st.BridgeMAC = prev.BridgeMAC
+		}
+	}
+	r.states[p.Router] = st
 }
 
 // Info devuelve last_seen + versión + kind/interval para GET /api/agents
@@ -191,12 +215,23 @@ func (r *AgentRegistry) ActiveCount() int {
 // (arranque del servidor). No revalida TTL: la expiración la decide el
 // reloj comparando contra el LastSeen restaurado. Sobrescribe cualquier
 // estado previo del slug. Los estados persistidos antes de #288 no traen
-// Kind/Interval: se recuperan del payload si están ahí.
+// Kind/Interval y los de antes de #852 no traen Host/BridgeMAC: se
+// recuperan del payload si están ahí.
 func (r *AgentRegistry) Restore(slug string, st *AgentState) {
 	r.mu.Lock()
 	defer r.mu.Unlock()
-	if st != nil && st.Interval == 0 && st.Payload != nil {
-		st.Kind, st.Interval = st.Payload.Kind, st.Payload.Interval
+	if st != nil && st.Payload != nil {
+		if st.Interval == 0 {
+			st.Kind, st.Interval = st.Payload.Kind, st.Payload.Interval
+		}
+		if sd := st.Payload.Data.System; sd != nil {
+			if st.Host == "" && sd.Board != nil {
+				st.Host = sd.Board.Hostname
+			}
+			if st.BridgeMAC == "" {
+				st.BridgeMAC = sd.BridgeMAC
+			}
+		}
 	}
 	r.states[slug] = st
 }
@@ -215,10 +250,12 @@ func (r *AgentRegistry) Snapshot(slug string) *AgentState {
 }
 
 // MatchRouter busca el agente asociado a un router: primero por slug exacto,
-// luego por hostname de board y finalmente por bridge MAC (#282). Devuelve
-// el slug real del agente, su payload y si está fresco. Permite que un agente
-// emparejado con un slug elegido por el usuario alimente un router cuyo id
-// autogenerado no coincide con ese slug.
+// luego por hostname de board y finalmente por bridge MAC (#282). El match
+// por hostname/MAC usa la identidad retenida en el estado (#852), válida
+// aunque el último push sea wireless-only. Devuelve el slug real del
+// agente, su payload y si está fresco. Permite que un agente emparejado con
+// un slug elegido por el usuario alimente un router cuyo id autogenerado no
+// coincide con ese slug.
 func (r *AgentRegistry) MatchRouter(cfg RouterConfig, macs map[string]string) (string, *probe.Payload, bool) {
 	r.mu.Lock()
 	defer r.mu.Unlock()
@@ -245,11 +282,14 @@ func (r *AgentRegistry) MatchRouter(cfg RouterConfig, macs map[string]string) (s
 			matchSlug = slug
 			break
 		}
-		if st.Payload == nil || st.Payload.Data.System == nil || st.Payload.Data.System.Board == nil {
+		// #852: el match usa la identidad RETENIDA (Host/BridgeMAC), no la
+		// del payload actual: el último push puede ser wireless-only (evento
+		// nl80211, sin sección system) y aun así debe emparejar. Sin esto,
+		// cada roam borraba la identidad hasta el próximo push completo.
+		if st.Payload == nil {
 			continue
 		}
-		h := norm(st.Payload.Data.System.Board.Hostname)
-		if h != "" {
+		if h := norm(st.Host); h != "" {
 			for _, candidate := range hostNames {
 				if h == candidate {
 					match = st
@@ -261,9 +301,8 @@ func (r *AgentRegistry) MatchRouter(cfg RouterConfig, macs map[string]string) (s
 		if match != nil {
 			break
 		}
-		mac := st.Payload.Data.System.BridgeMAC
-		if mac != "" && macs != nil {
-			if routerMac, ok := macs[cfg.ID]; ok && strings.EqualFold(mac, routerMac) {
+		if st.BridgeMAC != "" && macs != nil {
+			if routerMac, ok := macs[cfg.ID]; ok && strings.EqualFold(st.BridgeMAC, routerMac) {
 				match = st
 				matchSlug = slug
 				break
@@ -411,13 +450,19 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 			if !l.agentDown[cfg.ID] {
 				l.agentDown[cfg.ID] = true
 				name := agentName(cfg)
+				// #850: para routers agent-only el agente ES la única vía
+				// de datos (el poll sirve el payload cacheado y el router
+				// nunca marca offline): su caída es un evento de router
+				// urgente, comparable al offline, para que pase los filtros
+				// de notificación "solo urgentes del topic router". Con SSH
+				// disponible se degrada con gracia y sigue siendo system.
 				if cfg.AgentOnly {
 					l.engine.Emit(AlertEvent{
 						ID:       fmt.Sprintf("alert-agent-down-%s-%d", cfg.ID, time.Now().UnixMilli()),
-						Category: alerts.CatSystem, Urgent: false,
-						Severity:    "warn",
+						Category: alerts.CatRouter, Urgent: true,
+						Severity:    "critical",
 						Title:       fmt.Sprintf("Agente caído en %s", name),
-						Description: fmt.Sprintf("Sin datos del agente de %s desde hace más de %s — usando datos cacheados", name, confirm),
+						Description: fmt.Sprintf("Sin datos del agente de %s desde hace más de %s — la tarjeta sigue mostrando datos cacheados", name, confirm),
 						Hint:        alerts.HintFor(alerts.HintAgentDown),
 						Type:        alerts.HintAgentDown,
 						Vars:        map[string]string{"router": name, "confirm": confirm.String()},
@@ -430,7 +475,7 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 						Severity:    "warn",
 						Title:       fmt.Sprintf("Agente caído en %s — volviendo a SSH", name),
 						Description: fmt.Sprintf("Sin datos del agente de %s desde hace más de %s — sondeo SSH reanudado", name, confirm),
-						Hint:        alerts.HintFor(alerts.HintAgentDown),
+						Hint:        alerts.HintFor(alerts.HintAgentDownSSH),
 						Type:        alerts.HintAgentDownSSH,
 						Vars:        map[string]string{"router": name, "confirm": confirm.String()},
 						Time:        "ahora mismo", RouterID: cfg.ID,

+ 96 - 0
server-go/internal/adapters/agent_match_test.go

@@ -136,3 +136,99 @@ func countAlerts(list []AlertEvent, titlePart string) int {
 	}
 	return n
 }
+
+// TestAgentRegistryMatchRouterRetainedIdentity (#852): un push wireless-only
+// (sin sección system, p. ej. un evento nl80211 de roam) NO debe romper el
+// match por hostname/MAC: es la causa de los "router sin cliente" transitorios
+// en routers agent-only emparejados sin slug exacto.
+func TestAgentRegistryMatchRouterRetainedIdentity(t *testing.T) {
+	reg := NewAgentRegistry(90 * time.Second)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	pl := testPayload()
+	pl.Router = "flint2"
+	pl.Data.System.Board.Hostname = "flint2"
+	pl.Data.System.BridgeMAC = "94:83:C4:00:00:09"
+	reg.Ingest(pl)
+
+	// Evento nl80211: push rápido wireless-only, sin sección system.
+	ev := testPayload()
+	ev.Router = "flint2"
+	ev.Data.System = nil
+	reg.Ingest(ev)
+
+	cfg := RouterConfig{ID: "gl-inet-gl-mt6000", Name: "flint2", Host: "192.168.10.1"}
+	slug, p, fresh := reg.MatchRouter(cfg, nil)
+	if slug != "flint2" || p == nil || !fresh {
+		t.Fatalf("match por hostname retenido tras push wireless-only: slug=%q fresh=%v p=%v", slug, fresh, p)
+	}
+
+	cfgMac := RouterConfig{ID: "tp-link-eap225-09", Name: "Otro", Host: "192.168.1.9"}
+	macs := map[string]string{cfgMac.ID: "94:83:C4:00:00:09"}
+	slug, p, fresh = reg.MatchRouter(cfgMac, macs)
+	if slug != "flint2" || p == nil || !fresh {
+		t.Fatalf("match por MAC retenida tras push wireless-only: slug=%q fresh=%v p=%v", slug, fresh, p)
+	}
+}
+
+// TestAgentRegistryRestoreBackfillsIdentity (#852): los estados persistidos
+// antes del fix no traen Host/BridgeMAC; Restore los recupera del payload.
+func TestAgentRegistryRestoreBackfillsIdentity(t *testing.T) {
+	reg := NewAgentRegistry(90 * time.Second)
+	pl := testPayload()
+	pl.Router = "flint2"
+	pl.Data.System.Board.Hostname = "flint2"
+	reg.Restore("flint2", &AgentState{Payload: pl, LastSeen: time.Now()})
+
+	cfg := RouterConfig{ID: "gl-inet-gl-mt6000", Name: "flint2", Host: "192.168.10.1"}
+	slug, p, fresh := reg.MatchRouter(cfg, nil)
+	if slug != "flint2" || p == nil || !fresh {
+		t.Fatalf("match tras Restore sin Host explícito: slug=%q fresh=%v p=%v", slug, fresh, p)
+	}
+}
+
+// TestLiveAgentDownAgentOnlyIsUrgentRouter (#850): en routers agent-only la
+// caída del agente es el único aviso de una fuente de datos muerta (el poll
+// sirve el payload cacheado y el router nunca llega a marcar offline): la
+// alerta debe ser category router + urgent para pasar los filtros de
+// notificación "solo urgentes del topic router".
+func TestLiveAgentDownAgentOnlyIsUrgentRouter(t *testing.T) {
+	reg := NewAgentRegistry(50 * time.Millisecond)
+	l := newLiveAgentTest(t, reg)
+	cfg := RouterConfig{ID: "patio", Name: "Patio", Host: "127.0.0.1", AgentOnly: true}
+	reg.Ingest(testPayload())
+
+	if _, err := l.pollRouter(t.Context(), cfg); err != nil {
+		t.Fatalf("agente fresco: %v", err)
+	}
+	time.Sleep(60 * time.Millisecond)
+	// Agente expirado pero con payload cacheado: el poll NO falla (sirve lo
+	// cacheado) — la tarjeta sigue "viva" con datos congelados.
+	p, err := l.pollRouter(t.Context(), cfg)
+	if err != nil {
+		t.Fatalf("agent-only con payload cacheado no debe fallar el poll: %v", err)
+	}
+	if p == nil {
+		t.Fatal("esperaba datos cacheados del agente")
+	}
+	down := findAlert(l.engine.List(), "Agente caído en Patio")
+	if down == nil {
+		t.Fatalf("alerta de caída esperada: %+v", l.engine.List())
+	}
+	if down.Category != alerts.CatRouter || !down.Urgent || down.Severity != "critical" {
+		t.Fatalf("agent-down agent-only debe ser router/urgent/critical: %+v", down)
+	}
+	if strings.Contains(down.Title, "SSH") {
+		t.Fatalf("agent-only no debe mencionar SSH: %+v", down)
+	}
+	// Recuperación: alerta ok visible en el feed (system:all), sin urgencia.
+	reg.Ingest(testPayload())
+	if _, err := l.pollRouter(t.Context(), cfg); err != nil {
+		t.Fatalf("agente recuperado: %v", err)
+	}
+	ok := findAlert(l.engine.List(), "Agente recuperado en Patio")
+	if ok == nil || ok.Category != alerts.CatSystem || ok.Urgent || ok.Severity != "ok" {
+		t.Fatalf("alerta recuperación agent-only: %+v", ok)
+	}
+}

+ 8 - 2
server-go/internal/httpapi/agent.go

@@ -454,9 +454,15 @@ func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
 	if s.cfg != nil && s.cfg.SSHKeyPath != "" {
 		sshKeyArg = " --ssh-key=" + s.cfg.SSHKeyPath
 	}
+	// #851: HTTPS exige pinning SPKI. On-box el server conoce su propio FP;
+	// detrás de un proxy TLS, install-agent.sh lo deriva del certificado.
+	fpArg := ""
+	if scheme == "https" && s.serverFP != "" {
+		fpArg = " --server-fp=" + s.serverFP
+	}
 	return fmt.Sprintf(
-		"curl -fsSL -H 'Authorization: Bearer %s' %s/api/agents/%s/binary -o /tmp/netpulse-agent && curl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install-agent.sh | sh -s -- --binary=/tmp/netpulse-agent --host=%s --server=%s --slug=%s --token=%s%s",
-		token, server, slug, host, server, slug, token, sshKeyArg)
+		"curl -fsSL -H 'Authorization: Bearer %s' %s/api/agents/%s/binary -o /tmp/netpulse-agent && curl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install-agent.sh | sh -s -- --binary=/tmp/netpulse-agent --host=%s --server=%s --slug=%s --token=%s%s%s",
+		token, server, slug, host, server, slug, token, sshKeyArg, fpArg)
 }
 
 // agentListItem: lo que ve la UI — NUNCA el token ni su hash.

+ 17 - 9
server-go/internal/httpapi/agentstate.go

@@ -22,10 +22,14 @@ import (
 const agentStateKeyPrefix = "agent.state."
 
 // persistedAgentState es el formato en kv: el payload + cuándo llegó.
+// Host/BridgeMAC (#852) conservan la identidad de match entre reinicios
+// aunque el último push persisted sea wireless-only.
 type persistedAgentState struct {
-	Payload  *probe.Payload `json:"payload"`
-	LastSeen int64          `json:"lastSeen"` // unix segundos
-	Version  string         `json:"version"`
+	Payload   *probe.Payload `json:"payload"`
+	LastSeen  int64          `json:"lastSeen"` // unix segundos
+	Version   string         `json:"version"`
+	Host      string         `json:"host,omitempty"`
+	BridgeMAC string         `json:"bridgeMAC,omitempty"`
 }
 
 func agentStateKey(slug string) string { return agentStateKeyPrefix + slug }
@@ -37,9 +41,11 @@ func (s *server) persistAgentState(slug string, st *adapters.AgentState) {
 		return
 	}
 	raw, err := json.Marshal(persistedAgentState{
-		Payload:  st.Payload,
-		LastSeen: st.LastSeen.Unix(),
-		Version:  st.Version,
+		Payload:   st.Payload,
+		LastSeen:  st.LastSeen.Unix(),
+		Version:   st.Version,
+		Host:      st.Host,
+		BridgeMAC: st.BridgeMAC,
 	})
 	if err != nil {
 		log.Printf("[netpulse] aviso: no se pudo serializar el estado del agente %s: %v", slug, err)
@@ -79,9 +85,11 @@ func NewStateRestorer(d *db.DB) func(*adapters.AgentRegistry) {
 				continue
 			}
 			reg.Restore(slug, &adapters.AgentState{
-				Payload:  ps.Payload,
-				LastSeen: time.Unix(ps.LastSeen, 0),
-				Version:  ps.Version,
+				Payload:   ps.Payload,
+				LastSeen:  time.Unix(ps.LastSeen, 0),
+				Version:   ps.Version,
+				Host:      ps.Host,
+				BridgeMAC: ps.BridgeMAC,
 			})
 		}
 	}