Quellcode durchsuchen

feat(agent): report the interface of each ARP entry (#1485) (#1488)

Nacho vor 1 Monat
Ursprung
Commit
3165be04e0

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.20
+3.0.21

+ 6 - 6
agent/probe/local.go

@@ -290,7 +290,7 @@ func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
 	pl.Data.Wireless = p.probeWireless(ctx, true)
 	pl.Data.DHCP = p.probeDHCP(ctx)
 	pl.Data.FDB = p.probeFDB(ctx)
-	pl.Data.Arp, pl.Data.ArpStale = p.probeArp(ctx)
+	pl.Data.Arp, pl.Data.ArpStale, pl.Data.ArpDevs = p.probeArp(ctx)
 	pl.Data.Dawn = p.probeDawn(ctx)
 	pl.Data.Usteer = p.probeUsteer(ctx)
 	pl.Data.LuCI = p.probeLuCI(ctx)
@@ -323,7 +323,7 @@ func (p *Prober) BuildWireless(ctx context.Context, router, version string) *Pay
 	}
 	pl.Data.Wireless = p.probeWireless(ctx, false)
 	pl.Data.DHCP = p.probeDHCP(ctx)
-	pl.Data.Arp, pl.Data.ArpStale = p.probeArp(ctx)
+	pl.Data.Arp, pl.Data.ArpStale, pl.Data.ArpDevs = p.probeArp(ctx)
 	return pl
 }
 
@@ -976,7 +976,7 @@ func (p *Prober) probeDiscovery(ctx context.Context, wireless *WirelessData) *Di
 // falls back to /proc/net/arp where `ip` is missing -- there the states are
 // unknowable and the returned stale set is empty, the behaviour agents had
 // before. stale lists the MACs the kernel remembers without confirming.
-func (p *Prober) probeArp(ctx context.Context) (arp map[string]string, stale []string) {
+func (p *Prober) probeArp(ctx context.Context) (arp map[string]string, stale []string, devs map[string]string) {
 	if out := p.runBest(ctx, CmdIpNeigh, 3*time.Second); out != "" {
 		m, st := ParseIPNeigh(out)
 		if len(m) > 0 {
@@ -984,16 +984,16 @@ func (p *Prober) probeArp(ctx context.Context) (arp map[string]string, stale []s
 				stale = append(stale, mac)
 			}
 			sort.Strings(stale) // stable payloads, so a diff means a change
-			return m, stale
+			return m, stale, ParseIPNeighDevs(out)
 		}
 	}
 	out := p.runBest(ctx, CmdProcArp, 3*time.Second)
 	if out == "" {
-		return nil, nil
+		return nil, nil, nil
 	}
 	m := ParseArp(out)
 	if m == nil {
 		m = map[string]string{}
 	}
-	return m, nil
+	return m, nil, ParseArpDevs(out)
 }

+ 5 - 0
agent/probe/payload.go

@@ -38,6 +38,11 @@ type PayloadData struct {
 	// con el dnsmasq en otro router): cualquier router de la flota que
 	// enrute la LAN conoce el mapa completo.
 	Arp map[string]string `json:"arp,omitempty"`
+	// ArpDevs: MAC -> interfaz donde el kernel tiene la entrada ARP (#1485).
+	// Permite al servidor distinguir el ARP aprendido en el puerto WAN (el
+	// primer salto del enlace, ONT/modem en bridge) del de la LAN. Un agente
+	// antiguo lo omite y el servidor no atribuye nada al lado WAN.
+	ArpDevs map[string]string `json:"arpDevs,omitempty"`
 	// ArpStale: the MACs of Arp whose neighbour entries are all unconfirmed
 	// (STALE/FAILED/INCOMPLETE). Their address is still the best one known
 	// for the host, but their presence in the table proves nothing: the

+ 49 - 0
agent/probe/probe.go

@@ -2122,6 +2122,55 @@ func ParseIPNeigh(out string) (arp map[string]string, stale map[string]bool) {
 	return arp, stale
 }
 
+// ParseIPNeighDevs devuelve MAC -> interfaz de `ip neigh show` (#1485). Solo
+// entradas confirmadas, con la misma regla que ParseIPNeigh: una entrada STALE
+// no prueba presencia y su interfaz tampoco sirve para atribuir el lado WAN.
+func ParseIPNeighDevs(out string) map[string]string {
+	devs := map[string]string{}
+	for _, line := range strings.Split(out, "\n") {
+		f := strings.Fields(line)
+		if len(f) < 6 || net.ParseIP(f[0]) == nil {
+			continue
+		}
+		var mac, dev string
+		for i := 1; i+1 < len(f); i++ {
+			switch f[i] {
+			case "lladdr":
+				mac = strings.ToUpper(f[i+1])
+			case "dev":
+				dev = f[i+1]
+			}
+		}
+		if mac == "" || mac == "00:00:00:00:00:00" || dev == "" {
+			continue
+		}
+		if !neighConfirmed[f[len(f)-1]] {
+			continue
+		}
+		devs[mac] = dev
+	}
+	return devs
+}
+
+// ParseArpDevs devuelve MAC -> interfaz de /proc/net/arp (#1485), con el mismo
+// filtro de entradas incompletas que ParseArp. Es el fallback cuando el equipo
+// no tiene `ip`.
+func ParseArpDevs(out string) map[string]string {
+	devs := map[string]string{}
+	for _, line := range strings.Split(out, "\n") {
+		f := strings.Fields(line)
+		if len(f) < 6 || f[0] == "IP" {
+			continue
+		}
+		mac := strings.ToUpper(f[3])
+		if mac == "" || mac == "00:00:00:00:00:00" || f[2] == "0x0" || net.ParseIP(f[0]) == nil {
+			continue
+		}
+		devs[mac] = f[5]
+	}
+	return devs
+}
+
 // sumProcRSS returns the total VmRSS (bytes) of every user-space process
 // (/proc/<pid>/status): the memory actually held by processes, excluding the
 // kernel page cache that inflates (total-available) on ubifs/overlay routers.

+ 47 - 5
agent/probe/probe_test.go

@@ -583,12 +583,12 @@ func TestProberWirelessWithoutClients(t *testing.T) {
 		CmdNetDev:          "  eth0: 1000000 0 0 0 0 0 0 0 500000 0\n",
 		CmdBridgeMAC:       "94:83:c4:00:00:09\n",
 		// Sin clientes: ningún comando de assoclist/ubus hostapd.
-		CmdRadios:   "2.4|6|HT20|20|0\n",
-		CmdDhcpFile: "1700000000 ec:71:db:44:12:8a 192.168.8.71 movil *\n",
-		CmdBridgeFDB: "==PORTS==\n0x1 lan1\n==MACS==\n1 ec:71:db:44:12:8a\n",
-		CmdPortStates: "lan1 up 1000\nwan down -1\n",
+		CmdRadios:       "2.4|6|HT20|20|0\n",
+		CmdDhcpFile:     "1700000000 ec:71:db:44:12:8a 192.168.8.71 movil *\n",
+		CmdBridgeFDB:    "==PORTS==\n0x1 lan1\n==MACS==\n1 ec:71:db:44:12:8a\n",
+		CmdPortStates:   "lan1 up 1000\nwan down -1\n",
 		CmdUbusWireless: `{"radio0":{"up":true,"interfaces":[{"ifname":"wlan0","config":{"mode":"ap"}}]}}`,
-		CmdIwDev: "phy#0\n\tInterface wlan0\n\t\taddr 62:e5:56:b6:94:bd\n\t\tssid temiscira\n\t\ttype AP\n",
+		CmdIwDev:        "phy#0\n\tInterface wlan0\n\t\taddr 62:e5:56:b6:94:bd\n\t\tssid temiscira\n\t\ttype AP\n",
 	}}
 	p := NewProber(run, Options{GwPingTarget: "192.168.8.1", ScanInterval: ScanDisabled})
 
@@ -1624,3 +1624,45 @@ func TestParseMdnsHosts(t *testing.T) {
 		t.Fatalf("broken json must not panic: %+v", got)
 	}
 }
+
+// #1485: la interfaz de cada entrada ARP. Con ella el servidor distingue el
+// ARP aprendido en el puerto WAN (primer salto del enlace, ONT en bridge tras
+// PPPoE) del de la LAN.
+func TestParseIPNeighDevs(t *testing.T) {
+	out := `192.168.1.1 dev eth2 lladdr C0:49:43:A3:D1:34 REACHABLE
+192.168.1.60 dev br-lan lladdr AA:BB:CC:00:00:01 STALE
+192.168.1.61 dev br-lan lladdr AA:BB:CC:00:00:02 DELAY
+192.168.1.70 dev br-lan  FAILED`
+	devs := ParseIPNeighDevs(out)
+	if got := devs["C0:49:43:A3:D1:34"]; got != "eth2" {
+		t.Fatalf("ONT dev %q, want eth2", got)
+	}
+	// DELAY/REACHABLE cuentan como confirmadas; STALE no prueba presencia.
+	if got := devs["AA:BB:CC:00:00:02"]; got != "br-lan" {
+		t.Fatalf("DELAY dev %q, want br-lan", got)
+	}
+	if _, ok := devs["AA:BB:CC:00:00:01"]; ok {
+		t.Fatalf("una entrada STALE no debe aportar interfaz")
+	}
+	if len(devs) != 2 {
+		t.Fatalf("devs %v, want 2 entradas", devs)
+	}
+}
+
+// Fallback /proc/net/arp: misma idea con las columnas del fichero.
+func TestParseArpDevs(t *testing.T) {
+	out := `IP address       HW type     Flags       HW address            Mask     Device
+192.168.1.1      0x1         0x2         c0:49:43:a3:d1:34     *        eth2
+192.168.1.60     0x1         0x2         aa:bb:cc:00:00:01     *        br-lan
+192.168.1.61     0x1         0x0         00:00:00:00:00:00     *        br-lan`
+	devs := ParseArpDevs(out)
+	if devs["C0:49:43:A3:D1:34"] != "eth2" {
+		t.Fatalf("ONT dev %q, want eth2", devs["C0:49:43:A3:D1:34"])
+	}
+	if devs["AA:BB:CC:00:00:01"] != "br-lan" {
+		t.Fatalf("cliente dev %q, want br-lan", devs["AA:BB:CC:00:00:01"])
+	}
+	if len(devs) != 2 {
+		t.Fatalf("devs %v, want 2 (la incompleta se descarta)", devs)
+	}
+}

+ 1 - 0
server-go/internal/adapters/agent.go

@@ -732,6 +732,7 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	}
 	if p.Data.Arp != nil {
 		out.arp = p.Data.Arp
+		out.arpDevs = p.Data.ArpDevs
 		// An agent old enough not to send arpStale leaves this empty, and
 		// the whole table counts as presence, exactly as it used to.
 		out.arpStale = make(map[string]bool, len(p.Data.ArpStale))

+ 56 - 7
server-go/internal/adapters/arp_test.go

@@ -22,7 +22,7 @@ func TestBuildDevicesArpFallback(t *testing.T) {
 			},
 		},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if len(devs) != 1 {
 		t.Fatalf("esperado 1 dispositivo, got %d: %+v", len(devs), devs)
 	}
@@ -45,7 +45,7 @@ func TestBuildDevicesArpDiscovery(t *testing.T) {
 			},
 		},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if len(devs) != 1 {
 		t.Fatalf("esperado 1 dispositivo, got %d: %+v", len(devs), devs)
 	}
@@ -80,7 +80,7 @@ func TestBuildDevicesArpRouterExcluded(t *testing.T) {
 			},
 		},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if len(devs) != 0 {
 		t.Fatalf("esperado 0 dispositivos (bridge MAC excluida), got %d: %+v", len(devs), devs)
 	}
@@ -115,7 +115,7 @@ func TestBuildDevicesIgnoresStaleArpOnlyHosts(t *testing.T) {
 			arpStale: map[string]bool{"02:00:00:00:00:11": true},
 		},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if len(devs) != 1 || devs[0].MAC != "02:00:00:00:00:10" {
 		t.Fatalf("only the confirmed host is a device: %+v", devs)
 	}
@@ -133,7 +133,7 @@ func TestBuildDevicesStaleArpStillResolvesIPs(t *testing.T) {
 			arpStale: map[string]bool{"02:00:00:00:00:11": true},
 		},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if len(devs) != 1 || devs[0].IP != "192.0.2.61" {
 		t.Fatalf("an associated client keeps its address: %+v", devs)
 	}
@@ -153,7 +153,7 @@ func TestBuildDevicesStaleOnOneRouterOnly(t *testing.T) {
 			arp: map[string]string{"02:00:00:00:00:10": "192.0.2.60"},
 		},
 	}
-	if devs := l.buildDevices(polled); len(devs) != 1 {
+	if devs := l.buildDevices(polled, ""); len(devs) != 1 {
 		t.Fatalf("confirmed by one router is enough: %+v", devs)
 	}
 }
@@ -207,7 +207,7 @@ func TestBuildDevicesReattributesDeletedRouters(t *testing.T) {
 		},
 	}
 	byMAC := map[string]Device{}
-	for _, dev := range l.buildDevices(polled) {
+	for _, dev := range l.buildDevices(polled, "") {
 		byMAC[dev.MAC] = dev
 	}
 	if len(byMAC) != 2 {
@@ -289,3 +289,52 @@ func TestGetRoutersCountsClientsNotLeases(t *testing.T) {
 		t.Fatalf("routers endpoint says %d, attribution says %d", routers[0].Clients, online)
 	}
 }
+
+// #1485: el ARP aprendido en el puerto WAN del gateway cuenta como presencia
+// para el primer salto del enlace (ONT/modem en bridge tras PPPoE), que no
+// está en ninguna FDB. Solo en la boca WAN: el ARP de una boca LAN no se marca.
+func TestBuildDevicesWanSideArp(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	l.gatewayCfg = &RouterConfig{ID: "gw", Name: "Gateway", IsGateway: true}
+	polled := map[string]*routerPolled{
+		"gw": {
+			cfg: RouterConfig{ID: "gw", Name: "Gateway", IsGateway: true},
+			arp: map[string]string{
+				"C0:49:43:A3:D1:34": "192.168.1.1",  // ONT en el puerto WAN
+				"AA:BB:CC:00:00:01": "192.168.1.60", // cliente visto por LAN
+			},
+			arpDevs: map[string]string{
+				"C0:49:43:A3:D1:34": "eth2",
+				"AA:BB:CC:00:00:01": "br-lan",
+			},
+		},
+	}
+	devs := l.buildDevices(polled, "eth2")
+	byMAC := map[string]Device{}
+	for _, d := range devs {
+		byMAC[d.MAC] = d
+	}
+	ont, ok := byMAC["C0:49:43:A3:D1:34"]
+	if !ok {
+		t.Fatalf("el ONT no aparece en devices: %+v", devs)
+	}
+	if !ont.WanSide {
+		t.Fatalf("ONT: %+v, want WanSide (ARP en el puerto WAN)", ont)
+	}
+	if !ont.Online {
+		t.Fatalf("ONT: %+v, want online (el ARP del puerto WAN es presencia)", ont)
+	}
+	lan, ok := byMAC["AA:BB:CC:00:00:01"]
+	if !ok {
+		t.Fatalf("el cliente LAN no aparece: %+v", devs)
+	}
+	if lan.WanSide {
+		t.Fatalf("un ARP de boca LAN no puede ser WanSide: %+v", lan)
+	}
+	// Sin boca WAN (p.ej. rutas que no la pasan) no se marca nada.
+	for _, d := range l.buildDevices(polled, "") {
+		if d.WanSide {
+			t.Fatalf("sin wanPort no debe haber WanSide: %+v", d)
+		}
+	}
+}

+ 1 - 1
server-go/internal/adapters/bssid_1206_test.go

@@ -32,7 +32,7 @@ func TestBuildDevicesExcludesOwnBssids(t *testing.T) {
 			},
 		},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	for _, d := range devs {
 		if d.MAC == "AA:BB:CC:00:00:01" {
 			t.Fatalf("el BSSID propio salió como cliente: %+v", devs)

+ 2 - 2
server-go/internal/adapters/device_reservation_test.go

@@ -26,7 +26,7 @@ func TestBuildDevicesNamesFromReservation(t *testing.T) {
 			},
 		},
 	}
-	devices := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, payload)})
+	devices := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, payload)}, "")
 	var found bool
 	for _, d := range devices {
 		if d.MAC != "02:00:00:00:00:01" {
@@ -60,7 +60,7 @@ func TestBuildDevicesLeaseHostnameWinsOverReservation(t *testing.T) {
 			},
 		},
 	}
-	devices := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, payload)})
+	devices := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, payload)}, "")
 	for _, d := range devices {
 		if d.MAC == "02:00:00:00:00:02" && (d.Name != "laptop" || d.IP != "192.0.2.30") {
 			t.Fatalf("the lease must win: %+v", d)

+ 2 - 2
server-go/internal/adapters/fdbsticky694_test.go

@@ -41,7 +41,7 @@ func TestUpdateFdbMemoGatewayUplinkWithoutApBrMac(t *testing.T) {
 	if m, ok := memo["44:44:44:44:44:44"]; !ok || m.routerID != "ap" || m.port != "lan3" {
 		t.Fatalf("la memo debe quedar en el AP (lan3), got %+v", memo["44:44:44:44:44:44"])
 	}
-	devs := l.buildDevices(polled2)
+	devs := l.buildDevices(polled2, "")
 	if d := mustDevice(t, devs, "44:44:44:44:44:44"); d.RouterID != "ap" {
 		t.Fatalf("buildDevices debería atribuir al AP, got %q", d.RouterID)
 	}
@@ -58,7 +58,7 @@ func TestBuildDevicesKeepsApWhenApPollFails(t *testing.T) {
 			fdb: map[string]string{"GG:GG:GG:GG:GG:GG": "lan1"},
 			arp: map[string]string{"44:44:44:44:44:44": "192.168.13.123"}},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if d := mustDevice(t, devs, "44:44:44:44:44:44"); d.RouterID != "ap" {
 		t.Fatalf("RouterID=%q (want ap por la memo, aunque el AP falló el sondeo)", d.RouterID)
 	}

+ 2 - 2
server-go/internal/adapters/fdbsticky_test.go

@@ -150,7 +150,7 @@ func TestBuildDevicesStickySatelliteAttribution(t *testing.T) {
 		"ap": {cfg: RouterConfig{ID: "ap", Name: "Luizjana2"}, brMac: "AA:AA:AA:AA:AA:AA",
 			fdb: map[string]string{"AA:AA:AA:AA:AA:AA": "lan1"}},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if d := mustDevice(t, devs, "44:44:44:44:44:44"); d.RouterID != "ap" {
 		t.Fatalf("RouterID=%q (want ap por la memo sticky)", d.RouterID)
 	}
@@ -171,7 +171,7 @@ func TestBuildDevicesGatewayLocalWinsOverSticky(t *testing.T) {
 		"ap": {cfg: RouterConfig{ID: "ap"}, brMac: "AA:AA:AA:AA:AA:AA",
 			fdb: map[string]string{"AA:AA:AA:AA:AA:AA": "lan1"}},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if d := mustDevice(t, devs, "44:44:44:44:44:44"); d.RouterID != "gateway" {
 		t.Fatalf("RouterID=%q (want gateway: boca local fresca manda)", d.RouterID)
 	}

+ 39 - 7
server-go/internal/adapters/live.go

@@ -122,6 +122,9 @@ type routerPolled struct {
 	// arp: MAC→IP de /proc/net/arp (#377). Último recurso de resolución de
 	// IP cuando ni el lease ni gl-clients la tienen (DHCP en otro equipo).
 	arp map[string]string
+	// arpDevs: MAC→interfaz de la tabla ARP (#1485). Permite distinguir el
+	// ARP aprendido en el puerto WAN (primer salto del enlace) del de la LAN.
+	arpDevs map[string]string
 	// arpStale: the subset of `arp` the kernel remembers without having
 	// confirmed (STALE/FAILED/INCOMPLETE). Good enough to resolve an IP,
 	// never enough to claim the host is connected -- an entry outlives the
@@ -1185,7 +1188,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	}
 	leases := client.GetDhcpLeases()
 	reservations := client.GetDhcpReservations()
-	arp, arpStale := client.GetArp()
+	arp, arpStale, arpDevs := client.GetArp()
 	// gl-clients (GL.iNet): complementa la resolución de IP donde dnsmasq no
 	// tiene lease (issue #5 bug 1). En routers sin el objeto ubus sale vacío
 	// — coste: una llamada ubus local por poll.
@@ -1287,7 +1290,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	return &routerPolled{
 		cfg: cfg, client: client, sysInfo: sysInfo, board: board,
 		cpu: cpuV, ram: ramPct, temp: tempV,
-		uptimeSec: sysInfo.Uptime, net: net, leases: leases, reservations: reservations, arp: arp, arpStale: arpStale, glClients: glClients,
+		uptimeSec: sysInfo.Uptime, net: net, leases: leases, reservations: reservations, arp: arp, arpStale: arpStale, arpDevs: arpDevs, glClients: glClients,
 		wireless: wirelessGood, ports: portsGood, radios: radiosGood,
 		fdb: fdbGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
 		backhaul: backhaul, lldp: lldp, lldpUnavailable: lldpUnavailable,
@@ -2842,7 +2845,7 @@ func wgDuration(d time.Duration) string {
 
 // buildDevices: unión de leases + MACs vistas (wireless > FDB satélites >
 // FDB gateway si no hay memoria) + device_attrib (index.js:396-460).
-func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
+func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []Device {
 	leasesByMac := map[string]DhcpLease{}
 	leaseRouter := map[string]string{}
 	arpByMac := map[string]string{}
@@ -3037,6 +3040,27 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	// for the entry to age out. A source that cannot report states (old
 	// agent, /proc/net/arp fallback) marks nothing stale and keeps the old
 	// behaviour.
+	// #1485: el ARP aprendido en el puerto WAN del gateway identifica al
+	// primer salto del enlace (ONT/módem en bridge tras PPPoE). Va antes del
+	// paso ARP general para que ese MAC no se atribuya como cliente LAN: se
+	// marca WanSide y lo dibuja el mapa como peer WAN bajo Internet. Solo si
+	// no tiene ya evidencia LAN (la LAN manda) y solo en la boca WAN del
+	// gateway, nunca en sus bocas LAN.
+	wanSide := map[string]bool{}
+	if gwID != "" && wanPort != "" {
+		if gwP := polled[gwID]; gwP != nil {
+			for mac, dev := range gwP.arpDevs {
+				if dev != wanPort {
+					continue
+				}
+				if _, ok := seen[mac]; ok {
+					continue
+				}
+				seen[mac] = seenInfo{gwID, "cable", nil}
+				wanSide[mac] = true
+			}
+		}
+	}
 	arpConfirmed := map[string]bool{}
 	for _, p := range polled {
 		for mac := range p.arp {
@@ -3207,7 +3231,7 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			MAC: mac, Manufacturer: manufacturer,
 			TrafficMbps: 0, Sparkline: []float64{},
 			RouterID: defaultRouterID, Band: "—",
-			Online: isSeen,
+			Online: isSeen, WanSide: wanSide[mac],
 		}
 		res, hasRes := resByMac[mac]
 		if hasLease {
@@ -3616,7 +3640,15 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	// como overlay de inferTopology (puerto/attachTo).
 	nowMs := time.Now().UnixMilli()
 	memo := l.updateFdbMemo(polled, nowMs)
-	devices := l.buildDevices(polled)
+	// #1485: buildDevices necesita la boca WAN (ARP del primer salto del
+	// enlace); sale del estado WAN del propio sondeo del gateway.
+	wanPort := ""
+	if gw != nil {
+		if gp := polled[gw.ID]; gp != nil {
+			wanPort = gp.wanInfo.Port
+		}
+	}
+	devices := l.buildDevices(polled, wanPort)
 	stickyPolled := overlayStickyFdb(polled, memo, nowMs)
 	devices, distNodes := inferTopology(stickyPolled, devices)
 	// Capa 2 manual (issue #142): overrides de topología tras el autodiscover.
@@ -4124,7 +4156,7 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 		return out
 	}
 	clients := []Device{}
-	detDevices, _ := inferTopology(polledAll, l.buildDevices(polledAll))
+	detDevices, _ := inferTopology(polledAll, l.buildDevices(polledAll, ""))
 	// #954: first/last seen también en los clientes del detalle del router.
 	l.applyDeviceSeen(detDevices)
 	for _, d := range detDevices {
@@ -4292,7 +4324,7 @@ func (l *Live) attributedDevices() []Device {
 	detailMemo := l.updateFdbMemo(polled, detailNowMs)
 	devices, _ := inferTopology(
 		overlayStickyFdb(polled, detailMemo, detailNowMs),
-		l.buildDevices(polled),
+		l.buildDevices(polled, ""),
 	)
 	// #1292: lápidas fuera de la lista del detalle (la fuente viva puede
 	// seguir emitiendo la MAC borrada).

+ 6 - 4
server-go/internal/adapters/openwrt.go

@@ -693,15 +693,17 @@ func radiosToAdapter(in []probe.Radio) []Radio {
 // MACs the kernel remembers without confirming (stale): their address is
 // still usable, but they are not evidence that the host is connected. Falls
 // back to /proc/net/arp, where no state is available and nothing is stale.
-func (c *OpenWrtClient) GetArp() (arp map[string]string, stale map[string]bool) {
+// GetArp devuelve además MAC -> interfaz (#1485): con esa columna el poller
+// distingue el ARP del puerto WAN (primer salto del enlace) del de la LAN.
+func (c *OpenWrtClient) GetArp() (arp map[string]string, stale map[string]bool, devs map[string]string) {
 	if out, err := c.pool.Run(c.Host, probe.CmdIpNeigh, 0); err == nil {
 		if m, st := probe.ParseIPNeigh(out); len(m) > 0 {
-			return m, st
+			return m, st, probe.ParseIPNeighDevs(out)
 		}
 	}
 	out, err := c.pool.Run(c.Host, probe.CmdProcArp, 0)
 	if err != nil {
-		return nil, nil
+		return nil, nil, nil
 	}
-	return probe.ParseArp(out), nil
+	return probe.ParseArp(out), nil, probe.ParseArpDevs(out)
 }

+ 1 - 1
server-go/internal/adapters/override_builddevices_test.go

@@ -26,7 +26,7 @@ func TestBuildDevicesNameTypeIconOverride(t *testing.T) {
 			wireless: map[string]WirelessClient{mac: {SignalDbm: -55, Band: "5 GHz"}},
 		},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if len(devs) != 1 {
 		t.Fatalf("esperado 1 dispositivo, got %d", len(devs))
 	}

+ 23 - 7
server-go/internal/adapters/topo_semantics.go

@@ -560,15 +560,31 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 				break
 			}
 		}
-		if wanPeerID != "" {
-			filtered := online[:0]
-			for _, d := range online {
-				if d.ID != wanPeerID {
-					filtered = append(filtered, d)
-				}
+	}
+	if wanPeerID == "" {
+		// #1485: con PPPoE la puerta de enlace WAN es el BRAS, así que el
+		// ONT/módem del primer salto nunca casa por IP. Su evidencia es el ARP
+		// aprendido en el puerto WAN del gateway (Device.WanSide); si hay
+		// varios, gana la MAC más baja para que el resultado sea estable.
+		bestMac := ""
+		for _, d := range online {
+			if !d.WanSide {
+				continue
+			}
+			m := strings.ToLower(d.MAC)
+			if wanPeerID == "" || m < bestMac {
+				wanPeerID, bestMac = d.ID, m
+			}
+		}
+	}
+	if wanPeerID != "" {
+		filtered := online[:0]
+		for _, d := range online {
+			if d.ID != wanPeerID {
+				filtered = append(filtered, d)
 			}
-			online = filtered
 		}
+		online = filtered
 	}
 	deviceByID := map[string]Device{}
 	for _, d := range online {

+ 36 - 0
server-go/internal/adapters/topo_semantics_test.go

@@ -782,3 +782,39 @@ func TestTopoSemanticsAbsorbeDistnodeSombra(t *testing.T) {
 		t.Fatalf("AbsorbedDists: %+v", sem.AbsorbedDists)
 	}
 }
+
+// #1485: con PPPoE la puerta de enlace WAN es el BRAS, así que el ONT/módem
+// del primer salto no casa por IP. Su evidencia es el ARP del puerto WAN
+// (Device.WanSide): debe dibujarse como peer WAN bajo Internet y no como
+// cliente cableado del gateway.
+func TestTopoSemanticsWanPeerByWanSide(t *testing.T) {
+	routers := []Router{{ID: "gw", Name: "Gateway", RoleBadge: "Principal"}}
+	devices := []Device{
+		{ID: "ont", MAC: "c0-49-43-a3-d1-34", IP: "192.168.1.1", Online: true, WanSide: true, Band: "cable", RouterID: "gw"},
+		{ID: "pc", MAC: "aa-bb-cc-00-00-01", Online: true, Band: "cable", RouterID: "gw"},
+	}
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "123.113.96.1", nil, nil, nil)
+	if sem.WanPeer != "ont" {
+		t.Fatalf("WanPeer %q, want ont", sem.WanPeer)
+	}
+	// Se dibuja como nodo WAN (enlace wan-peer desde Internet), no como
+	// cliente cableado del gateway.
+	for _, l := range sem.Links {
+		if l.To == "ont" && l.Kind != "wan-peer" {
+			t.Fatalf("el peer WAN no debe tener enlace LAN: %+v", l)
+		}
+	}
+}
+
+// El match por IP de siempre (#1042) sigue mandando cuando existe.
+func TestTopoSemanticsWanPeerByIPWins(t *testing.T) {
+	routers := []Router{{ID: "gw", Name: "Gateway", RoleBadge: "Principal"}}
+	devices := []Device{
+		{ID: "brasa", MAC: "00-00-00-00-00-aa", IP: "123.113.96.1", Online: true, Band: "cable", RouterID: "gw"},
+		{ID: "ont", MAC: "c0-49-43-a3-d1-34", IP: "192.168.1.1", Online: true, WanSide: true, Band: "cable", RouterID: "gw"},
+	}
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "123.113.96.1", nil, nil, nil)
+	if sem.WanPeer != "brasa" {
+		t.Fatalf("WanPeer %q, want brasa (el match por IP manda)", sem.WanPeer)
+	}
+}

+ 4 - 4
server-go/internal/adapters/topology656_test.go

@@ -51,7 +51,7 @@ func TestBuildDevicesDumbAPWiredClient(t *testing.T) {
 			},
 		},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if len(devs) != 2 {
 		t.Fatalf("esperado 2 dispositivos, got %d: %+v", len(devs), devs)
 	}
@@ -78,7 +78,7 @@ func TestBuildDevicesOwnBridgeExcluded(t *testing.T) {
 		"dumbap": {cfg: RouterConfig{ID: "dumbap"}, brMac: "AA:AA:AA:AA:AA:AA",
 			fdb: map[string]string{"GG:GG:GG:GG:GG:GG": "lan2", "AA:AA:AA:AA:AA:AA": "lan2"}},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if len(devs) != 0 {
 		t.Fatalf("esperado 0 dispositivos (todas las MACs son de bridge), got %d: %+v", len(devs), devs)
 	}
@@ -111,7 +111,7 @@ func TestBuildDevicesAgentOnlySpecific(t *testing.T) {
 			},
 		},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if len(devs) != 1 {
 		t.Fatalf("esperado 1 dispositivo, got %d: %+v", len(devs), devs)
 	}
@@ -137,7 +137,7 @@ func TestBuildDevicesStableOrder(t *testing.T) {
 			},
 		},
 	}
-	devs := l.buildDevices(polled)
+	devs := l.buildDevices(polled, "")
 	if len(devs) != 3 {
 		t.Fatalf("esperado 3 dispositivos, got %d: %+v", len(devs), devs)
 	}

+ 4 - 0
server-go/internal/adapters/types.go

@@ -273,6 +273,10 @@ type Device struct {
 	PortLabel string `json:"portLabel,omitempty"`
 	// Lldp: identificación del vecino cuando se anuncia por LLDP.
 	Lldp *LldpInfo `json:"lldp,omitempty"`
+	// WanSide (#1485): la única evidencia de este equipo es una entrada ARP en
+	// el puerto WAN del gateway (ONT/módem en bridge tras PPPoE, fuera de toda
+	// FDB). Lo dibuja como peer WAN bajo Internet, no como cliente LAN.
+	WanSide bool `json:"wanSide,omitempty"`
 	// AttachTo: hub del que cuelga en el mapa (router por defecto; id de
 	// DistributionNode inferido o de otro Device — hipervisor/switch).
 	AttachTo string `json:"attachTo,omitempty"`