Jelajahi Sumber

feat(server): resolve WireGuard peer names from UCI descriptions in topology (#663)

WireGuard peers in the topology were labeled by their raw tunnel IP when
they weren't already mapped to a NetPulse device.

Fetch the `description` of each wireguard_peer from `uci show network` in
the same SSH session as `wg show` (no extra roundtrip, exit code of `wg`
preserved) and use it as the peer name. Priority: NetPulse device name ->
OpenWrt UCI description -> tunnel IP -> fallback.

Closes #659

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 bulan lalu
induk
melakukan
fb2874b1c9

+ 104 - 7
server-go/internal/adapters/wireguard.go

@@ -5,6 +5,7 @@
 package adapters
 package adapters
 
 
 import (
 import (
+	"fmt"
 	"strconv"
 	"strconv"
 	"strings"
 	"strings"
 	"time"
 	"time"
@@ -12,6 +13,28 @@ import (
 
 
 const handshakeActiveSec = 180 // handshake < 3 min ⇒ peer activo
 const handshakeActiveSec = 180 // handshake < 3 min ⇒ peer activo
 
 
+// wgUciMarker separa el dump `wg show` de la config `uci show network` en una
+// única sesión SSH. Permite resolver el nombre del peer (option description de
+// los wireguard_peer) sin un segundo roundtrip (issue #659).
+const wgUciMarker = "===NETPULSE_UCI==="
+
+// wgStatsCommand devuelve el comando que emite el dump de `wg show <iface>`
+// y, a continuación, la config WireGuard UCI. El exit code es el de `wg show`
+// (si el túnel está caído, la llamada falla y GetWireGuardStats devuelve
+// error, igual que antes).
+func wgStatsCommand(iface string) string {
+	return fmt.Sprintf("wg show %s dump; rc=$?; echo '%s'; uci show network 2>/dev/null; exit $rc", iface, wgUciMarker)
+}
+
+// splitWGUci separa la salida combinada en la parte del dump y la parte UCI.
+func splitWGUci(out string) (string, string) {
+	if idx := strings.Index(out, wgUciMarker); idx >= 0 {
+		uci := strings.TrimLeft(out[idx+len(wgUciMarker):], "\n")
+		return out[:idx], uci
+	}
+	return out, ""
+}
+
 // WGDumpPeer es un peer parseado del dump (campos numéricos crudos).
 // WGDumpPeer es un peer parseado del dump (campos numéricos crudos).
 type WGDumpPeer struct {
 type WGDumpPeer struct {
 	Pubkey       string
 	Pubkey       string
@@ -64,17 +87,85 @@ type WGPeerName struct {
 	Type string
 	Type string
 }
 }
 
 
+// parseWGUciDescs extrae de la salida de `uci show network` las descripciones
+// de los peers WireGuard (option description), indexadas por public_key y por
+// cada allowed_ip normalizada (sin /32). Devuelve un mapa key → descripción.
+// Solo incluye secciones wireguard_peer con descripción no vacía.
+func parseWGUciDescs(uci string) map[string]string {
+	type peerDesc struct {
+		pub        string
+		allowedIPs string
+		desc       string
+	}
+	bySec := map[string]*peerDesc{}
+	for _, line := range strings.Split(uci, "\n") {
+		line = strings.TrimSpace(line)
+		if !strings.HasPrefix(line, "network.") {
+			continue
+		}
+		rest := strings.TrimPrefix(line, "network.")
+		eq := strings.Index(rest, "=")
+		if eq < 0 {
+			continue
+		}
+		val := strings.Trim(strings.TrimPrefix(rest[eq:], "="), "'")
+		path := rest[:eq]
+		dot := strings.Index(path, ".")
+		if dot < 0 {
+			continue
+		}
+		sec, opt := path[:dot], path[dot+1:]
+		p := bySec[sec]
+		if p == nil {
+			p = &peerDesc{}
+			bySec[sec] = p
+		}
+		switch opt {
+		case "public_key":
+			p.pub = val
+		case "allowed_ips":
+			if p.allowedIPs != "" {
+				p.allowedIPs += ","
+			}
+			p.allowedIPs += val
+		case "description":
+			p.desc = val
+		}
+	}
+	out := map[string]string{}
+	for _, p := range bySec {
+		if p.desc == "" {
+			continue
+		}
+		if p.pub != "" {
+			out[p.pub] = p.desc
+		}
+		for _, cidr := range strings.Split(p.allowedIPs, ",") {
+			ip := strings.Replace(strings.TrimSpace(cidr), "/32", "", 1)
+			if ip != "" {
+				out[ip] = p.desc
+			}
+		}
+	}
+	return out
+}
+
 // GetWireGuardStats obtiene WireGuardStats del gateway vía SSH.
 // GetWireGuardStats obtiene WireGuardStats del gateway vía SSH.
-// peerNames: mapa tunnelIp/pubkey → etiqueta opcional.
+// peerNames: mapa tunnelIp/pubkey → etiqueta opcional (nombre de device).
+// El nombre de cada peer se resuelve en este orden: nombre de device de
+// NetPulse (peerNames) → description del peer en UCI (OpenWrt) → IP del túnel
+// → "Peer <pubkey8>" (issue #659).
 func GetWireGuardStats(pool *SSHPool, host, iface, subnet string, peerNames map[string]WGPeerName) (*WireGuardStats, error) {
 func GetWireGuardStats(pool *SSHPool, host, iface, subnet string, peerNames map[string]WGPeerName) (*WireGuardStats, error) {
-	dump, err := pool.Run(host, "wg show "+iface+" dump", 0)
+	out, err := pool.Run(host, wgStatsCommand(iface), 0)
 	if err != nil {
 	if err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
+	dump, uci := splitWGUci(out)
+	descs := parseWGUciDescs(uci)
 	peers := ParseWGDump(dump)
 	peers := ParseWGDump(dump)
 	nowSec := time.Now().Unix()
 	nowSec := time.Now().Unix()
 
 
-	out := &WireGuardStats{
+	stats := &WireGuardStats{
 		Interface: iface,
 		Interface: iface,
 		Subnet:    subnet,
 		Subnet:    subnet,
 		Status:    "active", // quirk: siempre que el comando responda
 		Status:    "active", // quirk: siempre que el comando responda
@@ -95,9 +186,15 @@ func GetWireGuardStats(pool *SSHPool, host, iface, subnet string, peerNames map[
 		}
 		}
 		name := named.Name
 		name := named.Name
 		if name == "" {
 		if name == "" {
-			name = tunnelIP
+			name = descs[p.Pubkey]
+			if name == "" {
+				name = descs[tunnelIP]
+			}
 			if name == "" {
 			if name == "" {
-				name = "Peer " + p.Pubkey[:min(len(p.Pubkey), 8)]
+				name = tunnelIP
+				if name == "" {
+					name = "Peer " + p.Pubkey[:min(len(p.Pubkey), 8)]
+				}
 			}
 			}
 		}
 		}
 		typ := named.Type
 		typ := named.Type
@@ -109,11 +206,11 @@ func GetWireGuardStats(pool *SSHPool, host, iface, subnet string, peerNames map[
 		if p.HandshakeSec > 0 {
 		if p.HandshakeSec > 0 {
 			lastHandshake = relTime(p.HandshakeSec, nowSec)
 			lastHandshake = relTime(p.HandshakeSec, nowSec)
 		}
 		}
-		out.Peers = append(out.Peers, WGPeer{
+		stats.Peers = append(stats.Peers, WGPeer{
 			ID: id, Name: name, Type: typ, TunnelIP: tunnelIP,
 			ID: id, Name: name, Type: typ, TunnelIP: tunnelIP,
 			Active: active, LastHandshake: lastHandshake,
 			Active: active, LastHandshake: lastHandshake,
 			Rx: fmtBytes(float64(p.RxBytes)), Tx: fmtBytes(float64(p.TxBytes)),
 			Rx: fmtBytes(float64(p.RxBytes)), Tx: fmtBytes(float64(p.TxBytes)),
 		})
 		})
 	}
 	}
-	return out, nil
+	return stats, nil
 }
 }

+ 79 - 0
server-go/internal/adapters/wireguard_test.go

@@ -0,0 +1,79 @@
+// wireguard_test.go — tests de parseo del adapter WireGuard (issue #659):
+// resolución del nombre del peer por la option `description` de UCI.
+package adapters
+
+import "testing"
+
+func TestParseWGUciDescs(t *testing.T) {
+	uci := `network.wg0=interface
+network.wg0.proto='wireguard'
+network.wg0.private_key='x'
+network.peer1=wireguard_wg0
+network.peer1.public_key='AAA='
+network.peer1.allowed_ips='10.0.0.2/32'
+network.peer1.description='iPhone'
+network.peer2=wireguard_wg0
+network.peer2.public_key='BBB='
+network.peer2.allowed_ips='10.1.0.0/24'
+network.peer2.description='Site A'
+network.peer3=wireguard_wg0
+network.peer3.public_key='CCC='
+network.peer3.allowed_ips='10.0.0.4/32'`
+
+	descs := parseWGUciDescs(uci)
+
+	cases := map[string]string{
+		"AAA=":        "iPhone",
+		"10.0.0.2":    "iPhone", // allowed_ip /32 normalizada
+		"BBB=":        "Site A",
+		"10.1.0.0/24": "Site A", // allowed_ip /24 → clave tal cual (solo se recorta /32)
+		"CCC=":        "",
+		"10.0.0.4":    "", // peer sin description → descartado
+		"peerX=":      "",
+		"10.0.0.99":   "",
+	}
+	for key, want := range cases {
+		if got := descs[key]; got != want {
+			t.Errorf("descs[%q] = %q, want %q", key, got, want)
+		}
+	}
+}
+
+func TestSplitWGUci(t *testing.T) {
+	out := "peer-a\tAAA=\t10.0.0.2/32\n===NETPULSE_UCI===\nnetwork.wg0=interface\n"
+	dump, uci := splitWGUci(out)
+	if dump != "peer-a\tAAA=\t10.0.0.2/32\n" {
+		t.Errorf("dump = %q, want dump", dump)
+	}
+	if uci != "network.wg0=interface\n" {
+		t.Errorf("uci = %q, want uci", uci)
+	}
+
+	// Sin marker: todo es dump, uci vacío.
+	dump, uci = splitWGUci("solo-dump\n")
+	if dump != "solo-dump\n" || uci != "" {
+		t.Errorf("sin marker: dump=%q uci=%q, want dump con uci vacío", dump, uci)
+	}
+}
+
+func TestWGStatsCommand(t *testing.T) {
+	cmd := wgStatsCommand("wg0")
+	if !contains(cmd, "wg show wg0 dump") {
+		t.Errorf("comando no incluye el dump de la interfaz: %q", cmd)
+	}
+	if !contains(cmd, "===NETPULSE_UCI===") {
+		t.Errorf("comando no incluye el marker UCI: %q", cmd)
+	}
+	if !contains(cmd, "exit $rc") {
+		t.Errorf("comando no preserva el exit de wg: %q", cmd)
+	}
+}
+
+func contains(s, sub string) bool {
+	for i := 0; i+len(sub) <= len(s); i++ {
+		if s[i:i+len(sub)] == sub {
+			return true
+		}
+	}
+	return false
+}