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

feat(alerts): emit wireguard-disconnect when a peer drops its handshake (#1348)

Closes #1348. Disconnect transition on handshake loss with session duration; transitions only on successful polls; warmup preserved.
Nacho 1 месяц назад
Родитель
Сommit
ae398127bb

+ 4 - 0
app/public/locales/en/translation.json

@@ -243,6 +243,10 @@
         "title": "WireGuard handshake",
         "description": "{{peer}} connected"
       },
+      "wireguard-disconnect": {
+        "title": "WireGuard disconnect",
+        "description": "{{peer}} disconnected after {{duration}}"
+      },
       "firmware-upgrade-done": {
         "title": "Firmware upgraded",
         "description": "{{router}}: {{from}} → {{to}} (owut, {{origin}})"

+ 4 - 0
app/public/locales/es/translation.json

@@ -243,6 +243,10 @@
         "title": "Handshake WireGuard",
         "description": "{{peer}} conectado"
       },
+      "wireguard-disconnect": {
+        "title": "Desconexión WireGuard",
+        "description": "{{peer}} desconectado tras {{duration}}"
+      },
       "firmware-upgrade-done": {
         "title": "Firmware actualizado",
         "description": "{{router}}: {{from}} → {{to}} (owut, {{origin}})"

+ 65 - 9
server-go/internal/adapters/live.go

@@ -306,6 +306,7 @@ type Live struct {
 	recoverStreak map[string]int
 	engine        *alerts.Engine
 	wgActive      map[string]bool
+	wgActiveSince map[string]time.Time // when each active peer became active (disconnect duration)
 	weakAlerted   map[string]int64
 	onlineMacs    map[string]bool
 	// unknownGrace: ticks consecutivos online+sin nombre (Name == MAC) por
@@ -455,6 +456,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		recoverStreak:        map[string]int{},
 		engine:               alerts.New(d, nil),
 		wgActive:             map[string]bool{},
+		wgActiveSince:        map[string]time.Time{},
 		weakAlerted:          map[string]int64{},
 		onlineMacs:           map[string]bool{},
 		unknownGrace:         map[string]int{},
@@ -2431,7 +2433,7 @@ func (l *Live) pollAdGuard(ctx context.Context) *AdGuardStats {
 	return stats
 }
 
-// pollWireGuard: stats WG del gateway + alerta de handshake nuevo.
+// pollWireGuard: gateway WireGuard stats plus connect/disconnect alerts.
 func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 	l.mu.Lock()
 	gw := l.gatewayCfg
@@ -2450,7 +2452,17 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 		log.Printf("[netpulse] WireGuard no disponible: %v", err)
 		return &WireGuardStats{Interface: l.cfg.WGInterface, Subnet: "", Status: "inactive", Peers: []WGPeer{}}
 	}
-	// Alerta en handshake nuevo (peer pasa a activo)
+	// Transitions run only on a successful poll: a failed poll would mark every
+	// previously active peer as spuriously disconnected.
+	l.applyWireGuardTransitions(stats, gw.ID)
+	return stats
+}
+
+// applyWireGuardTransitions emits connect (handshake) and disconnect alerts for
+// peers whose active state changed since the last successful poll, and keeps
+// wgActive/wgActiveSince in sync. A peer that was never active cannot emit a
+// disconnect; the first post-boot cycle never emits a connect (warmup).
+func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
 	activeNow := map[string]bool{}
 	for _, p := range stats.Peers {
 		if p.Active {
@@ -2458,8 +2470,39 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 		}
 	}
 	l.mu.Lock()
+	defer l.mu.Unlock()
+	// Disconnects: previously active peers no longer present in activeNow.
+	for id := range l.wgActive {
+		if activeNow[id] {
+			continue
+		}
+		name := id
+		for _, p := range stats.Peers {
+			if p.ID == id {
+				name = p.Name
+			}
+		}
+		dur := wgDuration(time.Since(l.wgActiveSince[id]))
+		l.engine.Emit(AlertEvent{
+			ID:          fmt.Sprintf("alert-wg-down-%s-%d", id, time.Now().UnixMilli()),
+			Category:    alerts.CatVPN,
+			Urgent:      false,
+			Severity:    "info",
+			Title:       "WireGuard disconnect",
+			Description: fmt.Sprintf("%s disconnected after %s", name, dur),
+			Type:        alerts.TypeWireguardDisconnect,
+			Vars:        map[string]string{"peer": name, "duration": dur},
+			Time:        "just now",
+			RouterID:    gwID,
+		})
+		delete(l.wgActiveSince, id)
+	}
+	// Connects: newly active peers, skipping the first post-boot cycle.
 	for id := range activeNow {
-		if !l.wgActive[id] && len(l.wgActive) > 0 {
+		if l.wgActive[id] {
+			continue
+		}
+		if len(l.wgActive) > 0 {
 			name := id
 			for _, p := range stats.Peers {
 				if p.ID == id {
@@ -2467,19 +2510,32 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 				}
 			}
 			l.engine.Emit(AlertEvent{
-				ID:       fmt.Sprintf("alert-wg-%s-%d", id, time.Now().UnixMilli()),
-				Category: alerts.CatVPN, Urgent: false,
-				Severity: "info", Title: "WireGuard handshake",
+				ID:          fmt.Sprintf("alert-wg-%s-%d", id, time.Now().UnixMilli()),
+				Category:    alerts.CatVPN,
+				Urgent:      false,
+				Severity:    "info",
+				Title:       "WireGuard handshake",
 				Description: name + " connected",
 				Type:        alerts.TypeWireguardHandshake,
 				Vars:        map[string]string{"peer": name},
-				Time:        "just now", RouterID: gw.ID,
+				Time:        "just now",
+				RouterID:    gwID,
 			})
 		}
+		l.wgActiveSince[id] = time.Now()
 	}
 	l.wgActive = activeNow
-	l.mu.Unlock()
-	return stats
+}
+
+// wgDuration humanizes a WireGuard session duration as "Xh Ym" (hours and
+// minutes). Negative values collapse to "0h 0m".
+func wgDuration(d time.Duration) string {
+	if d < 0 {
+		d = 0
+	}
+	h := int(d.Hours())
+	m := int(d.Minutes()) % 60
+	return fmt.Sprintf("%dh %dm", h, m)
 }
 
 // buildDevices: unión de leases + MACs vistas (wireless > FDB satélites >

+ 178 - 0
server-go/internal/adapters/wireguard_disconnect_test.go

@@ -0,0 +1,178 @@
+// wireguard_disconnect_test.go - WireGuard disconnect alerts (#1348).
+package adapters
+
+import (
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+// wgAlertLive builds a Live whose engine accepts VPN alerts.
+func wgAlertLive(t *testing.T) *Live {
+	t.Helper()
+	l := NewLive(nil, nil, nil, nil)
+	if err := l.engine.SetConfig(map[string]string{alerts.CatVPN: alerts.LevelAll}); err != nil {
+		t.Fatalf("SetConfig vpn: %v", err)
+	}
+	return l
+}
+
+func wgDisconnects(l *Live) []alerts.AlertEvent {
+	out := []alerts.AlertEvent{}
+	for _, ev := range l.engine.List() {
+		if ev.Type == alerts.TypeWireguardDisconnect {
+			out = append(out, ev)
+		}
+	}
+	return out
+}
+
+func TestWireGuardDisconnectOnActiveToInactive(t *testing.T) {
+	l := wgAlertLive(t)
+	l.wgActive = map[string]bool{"peerA": true}
+	l.wgActiveSince = map[string]time.Time{"peerA": time.Now().Add(-90 * time.Minute)}
+
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "peerA", Name: "Alice", Active: false},
+	}}, "gw")
+
+	got := wgDisconnects(l)
+	if len(got) != 1 {
+		t.Fatalf("disconnects: %d, want 1", len(got))
+	}
+	ev := got[0]
+	if ev.Category != alerts.CatVPN {
+		t.Errorf("category: %q, want %q", ev.Category, alerts.CatVPN)
+	}
+	if ev.Urgent {
+		t.Errorf("urgent: true, want false")
+	}
+	if ev.Severity != "info" {
+		t.Errorf("severity: %q, want info", ev.Severity)
+	}
+	if ev.Title != "WireGuard disconnect" {
+		t.Errorf("title: %q, want %q", ev.Title, "WireGuard disconnect")
+	}
+	if ev.Vars["peer"] != "Alice" {
+		t.Errorf("vars.peer: %q, want Alice", ev.Vars["peer"])
+	}
+	if ev.RouterID != "gw" {
+		t.Errorf("routerId: %q, want gw", ev.RouterID)
+	}
+	if !strings.HasPrefix(ev.ID, "alert-wg-down-") {
+		t.Errorf("id: %q, want prefix alert-wg-down-", ev.ID)
+	}
+}
+
+func TestWireGuardNoDisconnectWhileActive(t *testing.T) {
+	l := wgAlertLive(t)
+	l.wgActive = map[string]bool{"peerA": true}
+	l.wgActiveSince = map[string]time.Time{"peerA": time.Now().Add(-90 * time.Minute)}
+
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "peerA", Name: "Alice", Active: true},
+	}}, "gw")
+
+	if got := wgDisconnects(l); len(got) != 0 {
+		t.Fatalf("disconnects: %d, want 0", len(got))
+	}
+	if !l.wgActive["peerA"] {
+		t.Errorf("peerA no longer active")
+	}
+}
+
+func TestWireGuardNoDisconnectForNeverActive(t *testing.T) {
+	l := wgAlertLive(t) // wgActive empty (fresh boot)
+
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "peerA", Name: "Alice", Active: false},
+	}}, "gw")
+
+	if got := wgDisconnects(l); len(got) != 0 {
+		t.Fatalf("disconnects: %d, want 0", len(got))
+	}
+}
+
+func TestWireGuardDisconnectDuration(t *testing.T) {
+	l := wgAlertLive(t)
+	l.wgActive = map[string]bool{"peerA": true}
+	l.wgActiveSince = map[string]time.Time{"peerA": time.Now().Add(-90 * time.Minute)}
+
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "peerA", Name: "Alice", Active: false},
+	}}, "gw")
+
+	got := wgDisconnects(l)
+	if len(got) != 1 {
+		t.Fatalf("disconnects: %d, want 1", len(got))
+	}
+	if !strings.Contains(got[0].Description, "after 1h 30m") {
+		t.Errorf("description: %q, want to contain %q", got[0].Description, "after 1h 30m")
+	}
+	if got[0].Vars["duration"] != "1h 30m" {
+		t.Errorf("vars.duration: %q, want 1h 30m", got[0].Vars["duration"])
+	}
+}
+
+func TestWireGuardActiveSinceConsistency(t *testing.T) {
+	l := wgAlertLive(t)
+	base := time.Now().Add(-90 * time.Minute)
+	l.wgActive = map[string]bool{"peerA": true}
+	l.wgActiveSince = map[string]time.Time{"peerA": base}
+
+	// Disconnect: peer removed from both maps.
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "peerA", Name: "Alice", Active: false},
+	}}, "gw")
+
+	if _, ok := l.wgActive["peerA"]; ok {
+		t.Errorf("peerA still in wgActive after disconnect")
+	}
+	if _, ok := l.wgActiveSince["peerA"]; ok {
+		t.Errorf("peerA still in wgActiveSince after disconnect")
+	}
+
+	// Reconnect: peer tracked again with a fresh since timestamp.
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "peerA", Name: "Alice", Active: true},
+	}}, "gw")
+
+	if !l.wgActive["peerA"] {
+		t.Errorf("peerA not active after reconnect")
+	}
+	since, ok := l.wgActiveSince["peerA"]
+	if !ok {
+		t.Fatalf("peerA missing since after reconnect")
+	}
+	if !since.After(base) {
+		t.Errorf("since: %v, want after %v", since, base)
+	}
+}
+
+// Regression: the connect path still emits a handshake for a newly active peer
+// and tracks its since timestamp.
+func TestWireGuardHandshakeStillEmitted(t *testing.T) {
+	l := wgAlertLive(t)
+	l.wgActive = map[string]bool{"peerB": true}
+	l.wgActiveSince = map[string]time.Time{"peerB": time.Now().Add(-5 * time.Minute)}
+
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "peerA", Name: "Alice", Active: true},
+		{ID: "peerB", Name: "Bob", Active: true},
+	}}, "gw")
+
+	handshakes := 0
+	for _, ev := range l.engine.List() {
+		if ev.Type == alerts.TypeWireguardHandshake && ev.Vars["peer"] == "Alice" {
+			handshakes++
+		}
+	}
+	if handshakes != 1 {
+		t.Fatalf("handshakes for Alice: %d, want 1", handshakes)
+	}
+	if _, ok := l.wgActiveSince["peerA"]; !ok {
+		t.Errorf("peerA missing since")
+	}
+}

+ 23 - 22
server-go/internal/alerts/alerts.go

@@ -109,28 +109,29 @@ const (
 // Additional stable alert-type slugs (issue #712): recovery/info/beacon/rearmer
 // types emitted without Type/Vars in #671. They carry no hint.
 const (
-	TypeAgentRecovered     = "agent-recovered"
-	TypeSSHAccessLost      = "ssh-access-lost"
-	TypeSSHAccessRecovered = "ssh-access-recovered"
-	TypeAgentUpdated       = "agent-updated"
-	TypeRouterRecovered    = "router-recovered"
-	TypeWireguardHandshake = "wireguard-handshake"
-	TypePortStable         = "port-stable"
-	TypeGhostPortRecovered = "ghost-port-recovered"
-	TypeLinkRecovered      = "link-recovered"
-	TypeSwitchLoop         = "switch-loop"
-	TypePortDisabled       = "port-disabled"
-	TypePortRecovered      = "port-recovered"
-	TypeLinkDown           = "link-down"
-	TypeLinkUp             = "link-up"
-	TypeSfpRxLow           = "sfp-rx-low"
-	TypeSfpTempHigh        = "sfp-temp-high"
-	TypeSwitchRebooted     = "switch-rebooted"
-	TypeAgentRearmed       = "agent-rearmed"
-	TypeAgentReinstalled   = "agent-reinstalled"
-	TypeAutoRearmFailed    = "auto-rearm-failed"
-	TypeUplinkRestored     = "uplink-restored"
-	TypeSnmpRecovered      = "snmp-recovered"
+	TypeAgentRecovered      = "agent-recovered"
+	TypeSSHAccessLost       = "ssh-access-lost"
+	TypeSSHAccessRecovered  = "ssh-access-recovered"
+	TypeAgentUpdated        = "agent-updated"
+	TypeRouterRecovered     = "router-recovered"
+	TypeWireguardHandshake  = "wireguard-handshake"
+	TypeWireguardDisconnect = "wireguard-disconnect"
+	TypePortStable          = "port-stable"
+	TypeGhostPortRecovered  = "ghost-port-recovered"
+	TypeLinkRecovered       = "link-recovered"
+	TypeSwitchLoop          = "switch-loop"
+	TypePortDisabled        = "port-disabled"
+	TypePortRecovered       = "port-recovered"
+	TypeLinkDown            = "link-down"
+	TypeLinkUp              = "link-up"
+	TypeSfpRxLow            = "sfp-rx-low"
+	TypeSfpTempHigh         = "sfp-temp-high"
+	TypeSwitchRebooted      = "switch-rebooted"
+	TypeAgentRearmed        = "agent-rearmed"
+	TypeAgentReinstalled    = "agent-reinstalled"
+	TypeAutoRearmFailed     = "auto-rearm-failed"
+	TypeUplinkRestored      = "uplink-restored"
+	TypeSnmpRecovered       = "snmp-recovered"
 	// #1354: router offline (was reused from HintDeviceOffline, now its own slug)
 	// and client device offline (opt-in, volatile).
 	TypeRouterOffline = "router-offline"

+ 3 - 2
server-go/internal/alerts/alerts_i18n_test.go

@@ -15,6 +15,7 @@ import (
 var newTypeSlugs = []string{
 	TypeAgentRecovered, TypeSSHAccessLost, TypeSSHAccessRecovered,
 	TypeAgentUpdated, TypeRouterRecovered, TypeWireguardHandshake,
+	TypeWireguardDisconnect,
 	TypePortStable, TypeGhostPortRecovered, TypeLinkRecovered,
 	TypeSwitchLoop, TypePortDisabled, TypePortRecovered,
 	TypeLinkDown, TypeLinkUp, TypeSfpRxLow, TypeSfpTempHigh,
@@ -49,8 +50,8 @@ func TestNewTypeSlugsAreKebabCaseAndUnique(t *testing.T) {
 		}
 		seen[slug] = true
 	}
-	if len(newTypeSlugs) != 23 {
-		t.Errorf("se esperan 23 slugs nuevos, hay %d", len(newTypeSlugs))
+	if len(newTypeSlugs) != 24 {
+		t.Errorf("se esperan 24 slugs nuevos, hay %d", len(newTypeSlugs))
 	}
 }