Przeglądaj źródła

test(adapters): fixture lldpcli realista, promoción managed, fantasma sin LLDP y backhaul demo; writeJSON sin '\n' + parseo forma mapa de lldpd viejo

agent 4 miesięcy temu
rodzic
commit
e312f3a53a

+ 80 - 0
server-go/internal/adapters/adapters_test.go

@@ -393,3 +393,83 @@ func TestSparkDeterminista(t *testing.T) {
 		}
 	}
 }
+
+// --- Backhaul (C1-server): sonda ubus network.wireless status + canon demo ---
+
+// Fixture ubus network.wireless status: radio0 con AP + STA asociada
+// (uplink inalámbrico, p.ej. el EAP225 del patio).
+const wirelessStatusSta = `{
+  "radio0": {
+    "up": true,
+    "interfaces": [
+      {"section": "default_radio0", "ifname": "phy0-ap0",
+       "config": {"mode": "ap", "ssid": "Casa-Patio", "network": ["lan"]}},
+      {"section": "wifinet1", "ifname": "phy0-sta0",
+       "config": {"mode": "sta", "ssid": "Casa", "network": ["wwan"]}}
+    ]
+  }
+}`
+
+const wirelessStatusSoloAp = `{
+  "radio0": {
+    "up": true,
+    "interfaces": [
+      {"section": "default_radio0", "ifname": "phy0-ap0",
+       "config": {"mode": "ap", "ssid": "Casa", "network": ["lan"]}}
+    ]
+  }
+}`
+
+func TestParseWirelessUplink(t *testing.T) {
+	// STA asociada (radio up + ifname) → uplink inalámbrico
+	wifi, err := parseWirelessUplink([]byte(wirelessStatusSta))
+	if err != nil || !wifi {
+		t.Fatalf("sta asociada: %v %v", wifi, err)
+	}
+	// Solo APs → cable
+	wifi, err = parseWirelessUplink([]byte(wirelessStatusSoloAp))
+	if err != nil || wifi {
+		t.Fatalf("solo ap: %v %v", wifi, err)
+	}
+	// STA configurada pero NO activa (radio caída o sin asociar) → cable
+	for _, in := range []string{
+		`{"radio0":{"up":false,"interfaces":[{"ifname":"phy0-sta0","config":{"mode":"sta"}}]}}`,
+		`{"radio0":{"up":true,"interfaces":[{"ifname":"","config":{"mode":"sta"}}]}}`,
+		`{}`,
+	} {
+		wifi, err = parseWirelessUplink([]byte(in))
+		if err != nil || wifi {
+			t.Fatalf("%s → %v %v", in, wifi, err)
+		}
+	}
+	// Respuesta no JSON → error (el live omite el campo, no rompe)
+	if _, err = parseWirelessUplink([]byte("Command failed")); err == nil {
+		t.Fatal("no JSON debería dar error")
+	}
+}
+
+// Canon demo del backhaul: Patio "wifi" (único AP inalámbrico), resto "cable".
+func TestDemoBackhaulCanon(t *testing.T) {
+	d := NewDemo()
+	want := map[string]string{"flint2": "cable", "living": "cable", "estudio": "cable", "patio": "wifi"}
+	seen := 0
+	for _, r := range d.GetRouters(context.Background()) {
+		if r.Backhaul != want[r.ID] {
+			t.Fatalf("backhaul %s: %q (esperaba %q)", r.ID, r.Backhaul, want[r.ID])
+		}
+		seen++
+	}
+	if seen != 4 {
+		t.Fatalf("routers: %d", seen)
+	}
+	// El overview lleva el mismo dato (routersCopy preserva el campo)
+	ov, err := d.GetOverview(context.Background())
+	if err != nil {
+		t.Fatal(err)
+	}
+	for _, r := range ov.Routers {
+		if r.Backhaul != want[r.ID] {
+			t.Fatalf("overview backhaul %s: %q", r.ID, r.Backhaul)
+		}
+	}
+}

+ 13 - 6
server-go/internal/adapters/lldp.go

@@ -122,29 +122,36 @@ func parseLldpNeighbors(data []byte) ([]LldpNeighbor, error) {
 			names = append(names, name)
 		}
 		sort.Strings(names)
+		neighbors := make([]LldpNeighbor, 0, len(names))
 		for _, name := range names {
-			entries = append(entries, byName[name])
+			// En la forma mapa el nombre de la interfaz es la CLAVE
+			neighbors = append(neighbors, parseLldpEntry(byName[name], name))
 		}
+		return neighbors, nil
 	}
 	neighbors := make([]LldpNeighbor, 0, len(entries))
 	for _, raw := range entries {
-		neighbors = append(neighbors, parseLldpEntry(raw))
+		neighbors = append(neighbors, parseLldpEntry(raw, ""))
 	}
 	return neighbors, nil
 }
 
 // parseLldpEntry parsea una entrada de interface (nunca entra en pánico:
 // los Unmarshal secundarios ignoran el error a propósito — best-effort).
-func parseLldpEntry(raw json.RawMessage) LldpNeighbor {
+// fallbackName es la clave de la forma mapa (lldpd viejo, sin campo "name").
+func parseLldpEntry(raw json.RawMessage, fallbackName string) LldpNeighbor {
 	var e struct {
 		Name    string                     `json:"name"`
 		Chassis map[string]json.RawMessage `json:"chassis"`
 		Port    json.RawMessage            `json:"port"`
 	}
-	if json.Unmarshal(raw, &e) != nil {
-		return LldpNeighbor{}
-	}
+	// Best-effort: un campo de tipo inesperado (chassis como cadena, port
+	// como número…) no invalida el resto de la entrada.
+	_ = json.Unmarshal(raw, &e)
 	n := LldpNeighbor{Port: e.Name}
+	if n.Port == "" {
+		n.Port = fallbackName
+	}
 
 	// Chassis: mapa nombre→datos (normalmente uno; el primero ordenado)
 	keys := make([]string, 0, len(e.Chassis))

+ 206 - 0
server-go/internal/adapters/lldp_test.go

@@ -0,0 +1,206 @@
+// lldp_test.go — fixture realista de `lldpcli -f json show neighbors`
+// (contrato C2): switch gestionado GS308E con mgmt-ip y caps Bridge, un AP
+// anunciándose (mgmt-ip como string suelto), un equipo sin mgmt-ip ni
+// descr de puerto, y formas degeneradas que NUNCA deben romper el parseo.
+package adapters
+
+import (
+	"errors"
+	"fmt"
+	"testing"
+)
+
+// Fixture realista (lldpd 1.0.x en OpenWrt).
+const lldpcliFixture = `{
+  "lldp": {
+    "interface": [
+      {
+        "name": "lan3",
+        "via": "LLDP",
+        "rid": "2",
+        "age": "0 day, 00:01:12",
+        "chassis": {
+          "GS308E": {
+            "id": {"type": "mac", "value": "28:c6:8e:1d:90:44"},
+            "descr": "Netgear GS308E 8-Port Gigabit Smart Managed Plus Switch",
+            "mgmt-ip": ["192.168.8.13", "fe80::2ac6:8eff:fe1d:9044"],
+            "capability": [
+              {"type": "Bridge", "enabled": true},
+              {"type": "Router", "enabled": false}
+            ]
+          }
+        },
+        "port": {
+          "id": {"type": "ifname", "value": "ge5"},
+          "descr": "ge5",
+          "ttl": "120"
+        }
+      },
+      {
+        "name": "lan1",
+        "via": "LLDP",
+        "rid": "1",
+        "age": "0 day, 00:00:45",
+        "chassis": {
+          "EAP225": {
+            "id": {"type": "mac", "value": "B0:4A:39:2E:77:10"},
+            "descr": "TP-Link EAP225 (Outdoor)",
+            "mgmt-ip": "192.168.8.4",
+            "capability": [
+              {"type": "Bridge", "enabled": true},
+              {"type": "Wlan", "enabled": true}
+            ]
+          }
+        },
+        "port": {
+          "id": {"type": "mac", "value": "B0:4A:39:2E:77:11"},
+          "descr": "eth0",
+          "ttl": "120"
+        }
+      },
+      {
+        "name": "lan2",
+        "via": "LLDP",
+        "rid": "3",
+        "age": "0 day, 00:02:03",
+        "chassis": {
+          "mini-pc": {
+            "id": {"type": "mac", "value": "3C:52:82:10:20:30"},
+            "descr": "Debian GNU/Linux",
+            "capability": [
+              {"type": "Station", "enabled": true}
+            ]
+          }
+        },
+        "port": {
+          "id": {"type": "ifname", "value": "eno1"},
+          "ttl": "120"
+        }
+      }
+    ]
+  }
+}`
+
+func TestParseLldpNeighborsFixture(t *testing.T) {
+	neighbors, err := parseLldpNeighbors([]byte(lldpcliFixture))
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(neighbors) != 3 {
+		t.Fatalf("neighbors: %d", len(neighbors))
+	}
+	// Switch GS308E en lan3: mgmt-ip array (se coge la primera), caps enabled
+	sw := neighbors[0]
+	if sw.Port != "lan3" || sw.Chassis != "GS308E" || sw.ChassisMac != "28:C6:8E:1D:90:44" {
+		t.Fatalf("gs308e: %+v", sw)
+	}
+	if sw.Mgmt != "192.168.8.13" {
+		t.Fatalf("mgmt: %q", sw.Mgmt)
+	}
+	if len(sw.Caps) != 1 || sw.Caps[0] != "Bridge" {
+		t.Fatalf("caps (Router disabled no cuenta): %v", sw.Caps)
+	}
+	if sw.PortDesc != "ge5" {
+		t.Fatalf("portDesc: %q", sw.PortDesc)
+	}
+	if info := sw.info(); info.Chassis != "GS308E" || info.Mgmt != "192.168.8.13" || info.Caps != "Bridge" || info.PortDesc != "ge5" {
+		t.Fatalf("info: %+v", info)
+	}
+	// AP anunciándose: mgmt-ip como STRING suelto, dos caps enabled
+	ap := neighbors[1]
+	if ap.Port != "lan1" || ap.Chassis != "EAP225" || ap.ChassisMac != "B0:4A:39:2E:77:10" {
+		t.Fatalf("ap: %+v", ap)
+	}
+	if ap.Mgmt != "192.168.8.4" {
+		t.Fatalf("mgmt string suelto: %q", ap.Mgmt)
+	}
+	if len(ap.Caps) != 2 || ap.Caps[0] != "Bridge" || ap.Caps[1] != "Wlan" {
+		t.Fatalf("caps ap: %v", ap.Caps)
+	}
+	if ap.info().Caps != "Bridge, Wlan" {
+		t.Fatalf("caps unidas: %q", ap.info().Caps)
+	}
+	// Equipo sin mgmt-ip ni descr de puerto: PortDesc cae al id
+	pc := neighbors[2]
+	if pc.Port != "lan2" || pc.Mgmt != "" {
+		t.Fatalf("mini-pc: %+v", pc)
+	}
+	if pc.PortDesc != "eno1" {
+		t.Fatalf("portDesc fallback id: %q", pc.PortDesc)
+	}
+}
+
+func TestParseLldpNeighborsDefensivo(t *testing.T) {
+	// Raíz no JSON → error (el caller reintenta; NO es lldpd ausente)
+	if _, err := parseLldpNeighbors([]byte("lldpd is not running")); err == nil {
+		t.Fatal("no JSON debería dar error")
+	}
+	// Formas vacías → sin vecinos, sin error
+	for _, in := range []string{`{}`, `{"lldp":{}}`, `{"lldp":{"interface":null}}`, `{"lldp":{"interface":[]}}`, `null`} {
+		neighbors, err := parseLldpNeighbors([]byte(in))
+		if err != nil || len(neighbors) != 0 {
+			t.Fatalf("%s → %v %v", in, neighbors, err)
+		}
+	}
+	// Forma mapa (lldpd viejo): {"interface": {"lan3": {...}}}
+	mapForm := `{"lldp":{"interface":{"lan3":{"chassis":{"sw1":{"id":{"type":"mac","value":"AA:BB:CC:DD:EE:FF"}}}}}}}`
+	neighbors, err := parseLldpNeighbors([]byte(mapForm))
+	if err != nil || len(neighbors) != 1 {
+		t.Fatalf("forma mapa: %v %v", neighbors, err)
+	}
+	if neighbors[0].Port != "lan3" || neighbors[0].ChassisMac != "AA:BB:CC:DD:EE:FF" || neighbors[0].Chassis != "sw1" {
+		t.Fatalf("forma mapa parseada: %+v", neighbors[0])
+	}
+	// Tipos inesperados por todas partes: nunca panic, campos vacíos
+	weird := `{"lldp":{"interface":[
+		{"name":"lan1","chassis":"una cadena","port":123},
+		{"name":"lan2","chassis":{"x":{"id":"no-objeto","mgmt-ip":42,"capability":"no-array"}},"port":{"id":{}}},
+		42,
+		null
+	]}}`
+	neighbors, err = parseLldpNeighbors([]byte(weird))
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(neighbors) != 4 {
+		t.Fatalf("entradas raras: %d", len(neighbors))
+	}
+	if neighbors[0].Port != "lan1" || neighbors[0].Chassis != "" || neighbors[0].PortDesc != "" {
+		t.Fatalf("chassis cadena: %+v", neighbors[0])
+	}
+	if neighbors[1].Port != "lan2" || neighbors[1].ChassisMac != "" || neighbors[1].Mgmt != "" {
+		t.Fatalf("subcampos raros: %+v", neighbors[1])
+	}
+	if neighbors[2].Port != "" || neighbors[2].Chassis != "" || neighbors[2].Caps != nil {
+		t.Fatalf("entrada no-objeto: %+v", neighbors[2])
+	}
+	if neighbors[3].Port != "" || neighbors[3].ChassisMac != "" {
+		t.Fatalf("entrada null: %+v", neighbors[3])
+	}
+	// interface con forma ni array ni mapa → sin datos, no error
+	neighbors, err = parseLldpNeighbors([]byte(`{"lldp":{"interface":42}}`))
+	if err != nil || len(neighbors) != 0 {
+		t.Fatalf("interface escalar: %v %v", neighbors, err)
+	}
+}
+
+func TestIsLldpUnavailable(t *testing.T) {
+	// lldpcli no existe: exit 127 del shell (mensaje de ssh.ExitError envuelto)
+	err127 := fmt.Errorf("ssh 192.168.8.2: %w", errors.New("Process exited with status 127"))
+	if !isLldpUnavailable(err127) {
+		t.Fatalf("exit 127: %v", err127)
+	}
+	if !isLldpUnavailable(errors.New("ssh h: ash: lldpcli: not found")) {
+		t.Fatal("not found")
+	}
+	// Otros fallos NO son indisponibilidad cacheable
+	for _, e := range []error{
+		errors.New("ssh h: timeout (5s)"),
+		errors.New("ssh h: Process exited with status 1"),
+		nil,
+	} {
+		if isLldpUnavailable(e) {
+			t.Fatalf("no debería ser unavailable: %v", e)
+		}
+	}
+}

+ 133 - 0
server-go/internal/adapters/topology_test.go

@@ -197,3 +197,136 @@ func TestInferTopologyApCableadoDirecto(t *testing.T) {
 		t.Fatalf("port: %q", devices[0].Port)
 	}
 }
+
+// --- LLDP (contrato C2): promoción a "managed" y Device.Lldp ---
+
+// gs308eNeighbor: switch gestionado anunciándose en lan3 (fixture GS308E).
+func gs308eNeighbor() []LldpNeighbor {
+	return []LldpNeighbor{{
+		Port: "lan3", Chassis: "GS308E", ChassisMac: "28:C6:8E:1D:90:44",
+		Mgmt: "192.168.8.13", Caps: []string{"Bridge"}, PortDesc: "ge5",
+	}}
+}
+
+// Puerto multi-MAC del gateway CON vecino LLDP cuya chassis-MAC está entre
+// las aprendidas → nodo "managed" con Name/Ip/Lldp; los equipos cuelgan de
+// él igual que del inferido.
+func TestInferTopologySwitchManagedLldp(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"flint2": {cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01",
+			fdb: map[string]string{
+				"28:C6:8E:1D:90:44": "lan3", // el propio GS308E
+				"04:D4:C4:8B:30:A7": "lan3", // PC tras el switch
+				"DC:A6:32:4F:77:02": "lan3", // Raspberry tras el switch
+			},
+			lldp: gs308eNeighbor()},
+	}
+	devices := []Device{
+		dev("28:C6:8E:1D:90:44", "flint2", "cable"),
+		dev("04:D4:C4:8B:30:A7", "flint2", "cable"),
+		dev("DC:A6:32:4F:77:02", "flint2", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 {
+		t.Fatalf("distnodes: %+v", dists)
+	}
+	dn := dists[0]
+	if dn.Kind != "managed" || dn.ID != "dist-flint2-lan3" || dn.MacCount != 3 {
+		t.Fatalf("distnode managed: %+v", dn)
+	}
+	if dn.Name != "GS308E" || dn.Ip != "192.168.8.13" {
+		t.Fatalf("name/ip: %+v", dn)
+	}
+	if dn.Lldp == nil || dn.Lldp.Chassis != "GS308E" || dn.Lldp.Mgmt != "192.168.8.13" || dn.Lldp.Caps != "Bridge" || dn.Lldp.PortDesc != "ge5" {
+		t.Fatalf("lldp del nodo: %+v", dn.Lldp)
+	}
+	for _, d := range devices {
+		if d.AttachTo != "dist-flint2-lan3" || d.Port != "lan3" {
+			t.Fatalf("%s debería colgar del nodo managed: port=%q attachTo=%q", d.MAC, d.Port, d.AttachTo)
+		}
+	}
+	// El propio switch queda identificado como Device
+	if devices[0].Lldp == nil || devices[0].Lldp.Chassis != "GS308E" {
+		t.Fatalf("Device.Lldp del switch: %+v", devices[0].Lldp)
+	}
+}
+
+// El mismo puerto multi-MAC SIN datos LLDP (lldpd ausente: lldp nil) sigue
+// fantasma: nodo "inferred" exactamente como antes.
+func TestInferTopologyMultiMacSinLldpSigueFantasma(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"flint2": {cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01",
+			fdb: map[string]string{
+				"78:2B:CB:AA:01:01": "lan3",
+				"8C:EA:48:AA:02:02": "lan3",
+			}},
+	}
+	devices := []Device{
+		dev("78:2B:CB:AA:01:01", "flint2", "cable"),
+		dev("8C:EA:48:AA:02:02", "flint2", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 || dists[0].Kind != "inferred" || dists[0].Lldp != nil || dists[0].Ip != "" {
+		t.Fatalf("sin LLDP sigue inferido: %+v", dists)
+	}
+	// Vecino LLDP cuya chassis-MAC NO está aprendida en ese puerto → tampoco
+	// promociona (no es el equipo que multiplexa).
+	polled["flint2"].lldp = []LldpNeighbor{{
+		Port: "lan3", Chassis: "OtroEquipo", ChassisMac: "00:00:00:00:00:99",
+	}}
+	_, dists = inferTopology(polled, devices)
+	if len(dists) != 1 || dists[0].Kind != "inferred" {
+		t.Fatalf("chassis no aprendida sigue inferido: %+v", dists)
+	}
+	// Vecino en OTRO puerto → no promociona este
+	polled["flint2"].lldp = []LldpNeighbor{{
+		Port: "lan1", Chassis: "GS308E", ChassisMac: "78:2B:CB:AA:01:01",
+	}}
+	_, dists = inferTopology(polled, devices)
+	if len(dists) != 1 || dists[0].Kind != "inferred" {
+		t.Fatalf("vecino en otro puerto sigue inferido: %+v", dists)
+	}
+}
+
+// Managed también aplica tras un AP (evidencia positiva, como el hipervisor):
+// switch gestionado identificado colgando del AP, no del gateway.
+func TestInferTopologyManagedTrasAP(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"flint2": {cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01", fdb: map[string]string{}},
+		"living": {cfg: RouterConfig{ID: "living"}, brMac: "94:83:C4:00:00:02",
+			fdb: map[string]string{
+				"28:C6:8E:1D:90:44": "lan3",
+				"04:D4:C4:8B:30:A7": "lan3",
+			},
+			lldp: gs308eNeighbor()},
+	}
+	devices := []Device{
+		dev("28:C6:8E:1D:90:44", "living", "cable"),
+		dev("04:D4:C4:8B:30:A7", "living", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 || dists[0].Kind != "managed" || dists[0].RouterID != "living" || dists[0].Name != "GS308E" {
+		t.Fatalf("managed tras AP: %+v", dists)
+	}
+	if devices[1].AttachTo != "dist-living-lan3" {
+		t.Fatalf("cliente tras el switch: %q", devices[1].AttachTo)
+	}
+}
+
+// Vecino LLDP cuya chassis-MAC es un Device conocido en puerto de UNA sola
+// MAC (cableado directo): no hay nodo, pero el Device queda identificado.
+func TestInferTopologyLldpIdentificaDeviceDirecto(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"flint2": {cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01",
+			fdb:  map[string]string{"28:C6:8E:1D:90:44": "lan3"},
+			lldp: gs308eNeighbor()},
+	}
+	devices := []Device{dev("28:C6:8E:1D:90:44", "flint2", "cable")}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 0 {
+		t.Fatalf("cableado directo no genera nodo: %+v", dists)
+	}
+	if devices[0].Lldp == nil || devices[0].Lldp.Chassis != "GS308E" || devices[0].Lldp.Mgmt != "192.168.8.13" {
+		t.Fatalf("Device.Lldp: %+v", devices[0].Lldp)
+	}
+}

+ 21 - 0
server-go/internal/httpapi/httpapi_test.go

@@ -711,3 +711,24 @@ func TestSPAFallback(t *testing.T) {
 	// con STATIC_DIR. Aquí solo verificamos que /api/* no cae al SPA.
 	_ = srv
 }
+
+// writeJSON debe serializar como Hono: JSON compacto SIN el '\n' final que
+// añade json.Encoder (consistencia con D5 WriteError).
+func TestWriteJSONSinSaltoFinal(t *testing.T) {
+	srv := makeTestServer(t)
+	res := get(t, srv.URL, "/api/health", "")
+	defer res.Body.Close()
+	body, err := io.ReadAll(res.Body)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(body) == 0 {
+		t.Fatal("body vacío")
+	}
+	if body[len(body)-1] == '\n' {
+		t.Fatalf("el body NO debe terminar en '\\n': %q", body[len(body)-20:])
+	}
+	if !json.Valid(body) {
+		t.Fatalf("body no es JSON válido: %q", body)
+	}
+}