Procházet zdrojové kódy

fix(topology): FDB-corroborate LLDP candidates on a shared root port (#1372) (#1398)

A non-802.1AB switch flooding the reserved LLDP multicast delivers
second-hop phantom neighbors on the SAME root port, and the root-port
guard picked the first candidate on that port - which could be the
phantom (scan order).

When several fleet candidates share the root port, NetPulse now
corroborates each candidate's bridge MAC in the poller's FDB on that
port: the true peer exchanges real traffic with us, a pure phantom does
not. One corroborated candidate wins outright; several (flat LAN) fall
to the managed switch among them; none falls back to the historical
tie-break. Single-candidate and empty-FDB paths are unchanged.

Also documents the 802.1AB assumption and the phantom case in the
topology manuals (es/en).

Tests: pure phantom first-in-list loses to the corroborated candidate;
two switches with one phantom pick the corroborated one; corroborated
tie prefers the managed switch regardless of scan order.

Closes #1372
Nacho před 1 měsícem
rodič
revize
94a38a6084

+ 1 - 0
docs/manual.en.md

@@ -254,6 +254,7 @@ The map is built from the bridge FDB (for wired clients), LLDP when available (t
 
 - The topology is **inferred**, not configured: it is deduced from the router tables, which is why you sometimes see an "inferred" switch you never onboarded.
 - LLDP only identifies neighboring routers and switches, not end clients.
+- LLDP assumes **802.1AB-compliant** switches (they never forward LLDP frames between ports). A switch that floods them as regular multicast injects second-hop "phantom neighbors" on the same port; NetPulse disambiguates by FDB-corroborating which candidate actually exchanges traffic on that port (and, on a tie, prefers the managed switch). If your switch floods LLDP (some firmwares do), the odd links disappear once you block the reserved multicast on the switch or update its firmware.
 - The **Refresh** button forces an immediate backend poll (POST /api/refresh) and the map updates with the snapshot arriving over SSE, without reloading the page.
 
 ### Procedure: use the topology map

+ 1 - 0
docs/manual.es.md

@@ -254,6 +254,7 @@ El mapa se construye con el bridge FDB (para clientes por cable), LLDP cuando es
 
 - La topología es **inferida**, no configurada: se deduce de las tablas del router, por eso a veces aparece un switch "inferido" que no has dado de alta.
 - LLDP solo identifica routers y switches vecinos, no a los clientes finales.
+- LLDP asume switches **compatibles con 802.1AB** (no reenvían las tramas LLDP entre bocas). Un switch que las inunde como multicast normal mete "vecinos fantasma" de segundo salto en el mismo puerto; NetPulse los desempata corroborando por FDB qué candidato intercambia tráfico real por esa boca (y, en empate, prefiere el switch gestionado). Si tu switch inunda LLDP (algunos firmwares lo hacen), los enlaces raros desaparecen al bloquear la multicast reservada en el switch o al actualizar su firmware.
 - El botón **Refrescar** fuerza un sondeo inmediato en el backend (POST /api/refresh) y el mapa se actualiza con la instantánea que llega por SSE, sin recargar la página.
 
 ### Procedimiento: usar el mapa de topología

+ 44 - 3
server-go/internal/adapters/topo_semantics.go

@@ -198,6 +198,7 @@ func fleetLldpEvidence(polled map[string]*routerPolled, gatewayID string) map[st
 		port      string // lado padre (anunciado por él)
 		localPort string // puerto local del poller hacia él
 		isSwitch  bool
+		brMac     string // #1372: bridge MAC del candidato (corroboración FDB)
 	}
 	out := map[string]topoParent{}
 	for _, rid := range ids {
@@ -228,7 +229,7 @@ func fleetLldpEvidence(polled map[string]*routerPolled, gatewayID string) map[st
 			}
 			cands = append(cands, lldpCand{
 				parentID: ri.ID, port: nb.PortDesc, localPort: nb.Port,
-				isSwitch: ri.Type == "managed-switch",
+				isSwitch: ri.Type == "managed-switch", brMac: strings.ToUpper(ri.BrMac),
 			})
 		}
 		if len(cands) == 0 {
@@ -238,10 +239,50 @@ func fleetLldpEvidence(polled map[string]*routerPolled, gatewayID string) map[st
 		if gwMac != "" {
 			rootPort, ok := p.fdb[gwMac]
 			if ok {
+				// #1372 (phantom guard): un switch que inunda la multicast
+				// reservada 01:80:c2:00:00:0e (no 802.1AB-compliant) mete
+				// vecinos de SEGUNDO salto por el MISMO puerto raíz, así que
+				// "el primer candidato del root port" puede ser un phantom.
+				// Corroboración FDB por MAC: el peer verdadero intercambia
+				// tráfico real con nosotros y su bridge MAC está aprendida
+				// en la FDB de ese puerto; un phantom puro (sin tráfico
+				// directo) no. Solo se exige al desempatar varios candidatos
+				// en el mismo puerto: con uno solo, la LLDP basta (la FDB
+				// puede ir vacía o aún sin aprendizaje).
+				var onRoot []int
 				for i := range cands {
 					if cands[i].localPort == rootPort {
-						chosen = i
-						break
+						onRoot = append(onRoot, i)
+					}
+				}
+				if len(onRoot) == 1 {
+					chosen = onRoot[0]
+				} else if len(onRoot) > 1 {
+					var corr []int
+					for _, i := range onRoot {
+						if cands[i].brMac == "" {
+							continue
+						}
+						if port, ok2 := p.fdb[cands[i].brMac]; ok2 && port == cands[i].localPort {
+							corr = append(corr, i)
+						}
+					}
+					if len(corr) == 1 {
+						chosen = corr[0]
+					} else {
+						// Varios corroborados (LAN plana: todos hablan con
+						// todos) o ninguno (FDB sin datos): switch gestionado
+						// preferido entre los del root port (hacia el core).
+						pool := corr
+						if len(pool) == 0 {
+							pool = onRoot
+						}
+						for _, i := range pool {
+							if cands[i].isSwitch {
+								chosen = i
+								break
+							}
+						}
 					}
 				}
 			}

+ 89 - 0
server-go/internal/adapters/topology_phantom_test.go

@@ -0,0 +1,89 @@
+package adapters
+
+// topology_phantom_test.go — #1372: guarda contra vecinos LLDP fantasma
+// (switch intermedio que inunda la multicast reservada 01:80:c2:00:00:0e,
+// no 802.1AB-compliant). Varios candidatos de flota llegan por el MISMO
+// puerto raíz; la corroboración FDB por bridge-MAC decide.
+
+import "testing"
+
+const (
+	macGw    = "94:83:C4:00:00:01"
+	macRT2   = "22:22:22:22:22:02"
+	macRT3   = "33:33:33:33:33:03"
+	macSwCor = "44:44:44:44:44:04"
+	macSwFar = "55:55:55:55:55:05"
+)
+
+// phantomPolled: rt4 oye en lan1 a los vecinos dados (en ese orden, como
+// los devuelve lldpcli) y su FDB aprende al gateway por lan1 (root port).
+func phantomPolled(neighbors []LldpNeighbor, fdb map[string]string) map[string]*routerPolled {
+	return map[string]*routerPolled{
+		"gw":  {cfg: RouterConfig{ID: "gw", IsGateway: true}, brMac: macGw},
+		"rt2": {cfg: RouterConfig{ID: "rt2", Type: "openwrt"}, brMac: macRT2},
+		"rt3": {cfg: RouterConfig{ID: "rt3", Type: "openwrt"}, brMac: macRT3},
+		"swCore": {cfg: RouterConfig{ID: "swCore", Type: "managed-switch"}, brMac: macSwCor},
+		"swFar":  {cfg: RouterConfig{ID: "swFar", Type: "managed-switch"}, brMac: macSwFar},
+		"rt4": {cfg: RouterConfig{ID: "rt4", Type: "openwrt"}, brMac: "44:00:00:00:00:44",
+			fdb:  fdb,
+			lldp: neighbors,
+		},
+	}
+}
+
+// Phantom puro (sin tráfico directo: su MAC no está en la FDB) llega PRIMERO
+// en la lista pero no debe ganar al candidato corroborado.
+func TestPhantomFilteredByFdbCorroboration(t *testing.T) {
+	neighbors := []LldpNeighbor{
+		{Port: "lan1", Chassis: "rt3", ChassisMac: macRT3, PortDesc: "lan1"}, // phantom primero
+		{Port: "lan1", Chassis: "rt2", ChassisMac: macRT2, PortDesc: "lan2"}, // peer real
+	}
+	fdb := map[string]string{
+		macGw:  "lan1", // root port
+		macRT2: "lan1", // rt2 corroborado (tráfico real vía lan1)
+		// macRT3 ausente: phantom de 2º salto sin tráfico directo
+	}
+	out := fleetLldpEvidence(phantomPolled(neighbors, fdb), "gw")
+	if out["rt4"].parent != "rt2" {
+		t.Fatalf("phantom sin corroboración no debe ganar: parent=%q", out["rt4"].parent)
+	}
+	if out["rt4"].port != "lan2" {
+		t.Fatalf("puerto del padre: %q", out["rt4"].port)
+	}
+}
+
+// Dos switches gestionados oídos en el mismo puerto (cadena vista a través
+// de flooding): gana el corroborado, no el primero de la lista.
+func TestPhantomTwoSwitchesCorroboratedWins(t *testing.T) {
+	neighbors := []LldpNeighbor{
+		{Port: "lan1", Chassis: "swFar", ChassisMac: macSwFar, PortDesc: "ge9"},  // phantom primero
+		{Port: "lan1", Chassis: "swCore", ChassisMac: macSwCor, PortDesc: "ge5"}, // peer real
+	}
+	fdb := map[string]string{
+		macGw:    "lan1", // root port: el guard corre
+		macSwCor: "lan1", // swCore corroborado
+	}
+	out := fleetLldpEvidence(phantomPolled(neighbors, fdb), "gw")
+	if out["rt4"].parent != "swCore" {
+		t.Fatalf("dos switches: gana el corroborado; parent=%q", out["rt4"].parent)
+	}
+}
+
+// LAN plana: switch y AP corroborados a la vez en el root port → el switch
+// gestionado manda entre los corroborados (hacia el core), sea cual sea el
+// orden del scan.
+func TestPhantomCorroboratedTiePrefersSwitch(t *testing.T) {
+	neighbors := []LldpNeighbor{
+		{Port: "lan1", Chassis: "rt3", ChassisMac: macRT3, PortDesc: "lan1"},     // AP primero
+		{Port: "lan1", Chassis: "swCore", ChassisMac: macSwCor, PortDesc: "ge5"}, // switch
+	}
+	fdb := map[string]string{
+		macGw:    "lan1",
+		macRT3:   "lan1", // ambos corroborados
+		macSwCor: "lan1",
+	}
+	out := fleetLldpEvidence(phantomPolled(neighbors, fdb), "gw")
+	if out["rt4"].parent != "swCore" {
+		t.Fatalf("empate corroborado: switch preferido; parent=%q", out["rt4"].parent)
+	}
+}