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

fix: normalise MACs at the boundaries with one shared parser (#2121)

Add the agent/macaddr package, shared by the agent and the server.
macaddr.Normalize accepts ':' or '-' separators or 12 bare hex digits
in either case and returns AA:BB:CC:DD:EE:FF, or "" for anything that
isn't a 6-octet MAC. Use it where inconsistent handling loses data:

- ParseGlClients: GL.iNet's gl-clients cache can emit hyphenated MACs
  (#1145). They were only upper-cased, so the server's colon-keyed
  lookup missed them and those clients lost their IP and hostname.
- /api/roam-events and /api/device-events: the ?mac filter was passed
  to SQL as given, so lower-case or hyphenated MACs matched nothing.
  Each value is now normalised (roam-events keeps its comma-separated
  list), and a value that isn't a MAC returns 400 invalid_mac.
- Known MACs and Wi-Fi re-anchor accept hyphenated MACs.
- Switch beacons: MACs are now validated as hex instead of by length.
- The agent's interface-MAC check uses the shared parser.
Mike Grupenhoff 2 недель назад
Родитель
Сommit
d43cbcae4f

+ 62 - 0
agent/macaddr/macaddr.go

@@ -0,0 +1,62 @@
+// Package macaddr normaliza direcciones MAC a la forma canónica de NetPulse
+// (AA:BB:CC:DD:EE:FF). El agente y el servidor la usan desde aquí para que
+// las dos partes no diverjan.
+package macaddr
+
+import "strings"
+
+// Normalize devuelve la MAC en forma canónica (AA:BB:CC:DD:EE:FF) o "" si
+// raw no es una MAC ethernet de 6 octetos. Acepta separadores ':' o '-' (el
+// mismo en las cinco posiciones) y 12 dígitos hex sin separador; ignora
+// espacios alrededor y mayúsculas/minúsculas.
+func Normalize(raw string) string {
+	s := strings.TrimSpace(raw)
+	var b [17]byte
+	switch len(s) {
+	case 17:
+		sep := s[2]
+		if sep != ':' && sep != '-' {
+			return ""
+		}
+		for i := 0; i < 17; i++ {
+			c := s[i]
+			if i%3 == 2 {
+				if c != sep {
+					return ""
+				}
+				b[i] = ':'
+				continue
+			}
+			u, ok := upperHex(c)
+			if !ok {
+				return ""
+			}
+			b[i] = u
+		}
+	case 12:
+		for i := 0; i < 12; i++ {
+			u, ok := upperHex(s[i])
+			if !ok {
+				return ""
+			}
+			b[i/2*3+i%2] = u
+			if i%2 == 1 && i < 11 {
+				b[i/2*3+2] = ':'
+			}
+		}
+	default:
+		return ""
+	}
+	return string(b[:])
+}
+
+// upperHex devuelve el dígito hex en mayúscula y si c era un dígito hex.
+func upperHex(c byte) (byte, bool) {
+	switch {
+	case c >= '0' && c <= '9', c >= 'A' && c <= 'F':
+		return c, true
+	case c >= 'a' && c <= 'f':
+		return c - 'a' + 'A', true
+	}
+	return 0, false
+}

+ 33 - 0
agent/macaddr/macaddr_test.go

@@ -0,0 +1,33 @@
+package macaddr
+
+import "testing"
+
+func TestNormalize(t *testing.T) {
+	const want = "AA:BB:CC:DD:EE:FF"
+	tests := []struct {
+		name string
+		in   string
+		want string
+	}{
+		{"dos puntos en minúsculas", "aa:bb:cc:dd:ee:ff", want},
+		{"dos puntos en mayúsculas", "AA:BB:CC:DD:EE:FF", want},
+		{"con guiones", "aa-bb-cc-dd-ee-ff", want},
+		{"12 hex sin separador", "aabbccddeeff", want},
+		{"espacios alrededor", "  aa:bb:cc:dd:ee:ff\t\n", want},
+		{"separadores mezclados", "aa:bb-cc:dd-ee:ff", ""},
+		{"separador incorrecto", "aa.bb.cc.dd.ee.ff", ""},
+		{"no hex", "gg:bb:cc:dd:ee:ff", ""},
+		{"no hex sin separador", "aabbccddeefg", ""},
+		{"demasiado corta", "aa:bb:cc:dd:ee", ""},
+		{"demasiado larga", "aa:bb:cc:dd:ee:ff:00", ""},
+		{"vacía", "", ""},
+		{"nula aceptada", "00:00:00:00:00:00", "00:00:00:00:00:00"},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			if got := Normalize(tc.in); got != tc.want {
+				t.Errorf("Normalize(%q) = %q, esperaba %q", tc.in, got, tc.want)
+			}
+		})
+	}
+}

+ 6 - 20
agent/probe/ifacemacs.go

@@ -14,6 +14,8 @@ package probe
 import (
 	"sort"
 	"strings"
+
+	"github.com/gnacho/netpulse/agent/macaddr"
 )
 
 // ParseIfaceMACs convierte la salida de CmdIfaceMACs ("iface mac" por línea)
@@ -39,27 +41,11 @@ func ParseIfaceMACs(out string) []string {
 	return macs
 }
 
-// normalizeIfaceMAC acepta solo MAC ethernet de 6 octetos en hex. La MAC nula
-// es la de loopback y no identifica a nadie.
+// normalizeIfaceMAC acepta solo MAC ethernet de 6 octetos en hex (forma
+// canónica de macaddr.Normalize). La MAC nula es la de loopback y no
+// identifica a nadie.
 func normalizeIfaceMAC(raw string) string {
-	mac := strings.ToUpper(strings.TrimSpace(raw))
-	if len(mac) != 17 {
-		return ""
-	}
-	for i := 0; i < 17; i++ {
-		c := mac[i]
-		if i%3 == 2 {
-			if c != ':' && c != '-' {
-				return ""
-			}
-			continue
-		}
-		isHex := (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')
-		if !isHex {
-			return ""
-		}
-	}
-	mac = strings.ReplaceAll(mac, "-", ":")
+	mac := macaddr.Normalize(raw)
 	if mac == "00:00:00:00:00:00" {
 		return ""
 	}

+ 7 - 3
agent/probe/probe.go

@@ -18,6 +18,8 @@ import (
 	"strconv"
 	"strings"
 	"time"
+
+	"github.com/gnacho/netpulse/agent/macaddr"
 )
 
 // ---------------------------------------------------------------------------
@@ -985,9 +987,11 @@ func ParseGlClients(raw []byte) ([]DhcpLease, error) {
 	}
 	out := make([]DhcpLease, 0, len(data.Clients))
 	for key, c := range data.Clients {
-		mac := c.MAC
+		// El firmware puede emitir MAC con guiones ("AA-BB-...", #1145): se
+		// guarda siempre la forma canónica para que el servidor la encuentre.
+		mac := macaddr.Normalize(c.MAC)
 		if mac == "" {
-			mac = key
+			mac = macaddr.Normalize(key)
 		}
 		if mac == "" || c.IP == "" || !c.Online {
 			continue
@@ -996,7 +1000,7 @@ func ParseGlClients(raw []byte) ([]DhcpLease, error) {
 		if hostname == "" {
 			hostname = c.Name
 		}
-		out = append(out, DhcpLease{MAC: strings.ToUpper(mac), IP: c.IP, Hostname: hostname})
+		out = append(out, DhcpLease{MAC: mac, IP: c.IP, Hostname: hostname})
 	}
 	sort.Slice(out, func(i, j int) bool { return out[i].MAC < out[j].MAC })
 	return out, nil

+ 23 - 0
agent/probe/probe_test.go

@@ -269,6 +269,29 @@ func TestParseGlClients(t *testing.T) {
 	}
 }
 
+func TestParseGlClientsHyphenatedMACs(t *testing.T) {
+	// La caché de gl-clients puede emitir MAC con guiones (#1145): deben salir
+	// en forma canónica, también cuando solo la clave del mapa trae la MAC.
+	raw := `{"clients":{
+		"AA-BB-CC-DD-EE-01":{"mac":"aa-bb-cc-dd-ee-01","ip":"192.168.8.21","name":"uno","online":true},
+		"aa-bb-cc-dd-ee-02":{"mac":"","ip":"192.168.8.22","name":"dos","online":true},
+		"basura":{"mac":"tampoco","ip":"192.168.8.23","name":"tres","online":true}
+	}}`
+	leases, err := ParseGlClients([]byte(raw))
+	if err != nil {
+		t.Fatalf("parse: %v", err)
+	}
+	if len(leases) != 2 {
+		t.Fatalf("esperaba 2 entradas (la inválida se descarta), obtuve %d: %+v", len(leases), leases)
+	}
+	if leases[0].MAC != "AA:BB:CC:DD:EE:01" || leases[0].IP != "192.168.8.21" {
+		t.Errorf("primera: esperaba AA:BB:CC:DD:EE:01, obtuve %+v", leases[0])
+	}
+	if leases[1].MAC != "AA:BB:CC:DD:EE:02" || leases[1].IP != "192.168.8.22" {
+		t.Errorf("segunda: esperaba AA:BB:CC:DD:EE:02, obtuve %+v", leases[1])
+	}
+}
+
 func TestParseArp(t *testing.T) {
 	out := "IP address       HW type     Flags       HW address            Mask     Device\n" +
 		"192.168.1.10     0x1         0x2         aa:bb:cc:dd:ee:ff     *        br-lan\n" +

+ 7 - 26
server-go/internal/httpapi/beacon.go

@@ -23,9 +23,9 @@ import (
 	"log"
 	"net"
 	"sort"
-	"strings"
 	"time"
 
+	"github.com/gnacho/netpulse/agent/macaddr"
 	"github.com/gnacho/netpulse/agent/probe"
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
 	"github.com/gnacho/netpulse/server-go/internal/portseries"
@@ -192,11 +192,13 @@ func (s *server) ingestBeacon(src string, raw []byte) {
 		if prev, okPrev := s.agents.StalePayload(p.Slug); okPrev && prev != nil && prev.Data.FDB != nil {
 			ports = prev.Data.FDB.Ports
 		}
-		// MACs sin separadores ("AABBCCDDEEFF") → formato canónico con dos
-		// puntos; las irrecuperables se descartan (firmware razonable).
+		// El firmware envía las MAC en MAYÚSCULAS sin separadores
+		// ("AABBCCDDEEFF"); el resto de la app (leases, wifi, FDB,
+		// enriquecimiento) usa "AA:BB:CC:DD:EE:FF". Las irrecuperables se
+		// descartan (firmware razonable).
 		macs := make(map[string]string, len(p.FDB))
 		for mac, port := range p.FDB {
-			if norm := normalizeBeaconMAC(mac); norm != "" {
+			if norm := macaddr.Normalize(mac); norm != "" {
 				macs[norm] = port
 			}
 		}
@@ -284,7 +286,7 @@ func (s *server) ingestBeacon(src string, raw []byte) {
 		pl.Data.System = &probe.SystemData{
 			Board:     b,
 			SysInfo:   &probe.SysInfo{Uptime: float64(p.Up)},
-			BridgeMAC: strings.ToUpper(normalizeBeaconMAC(p.Mac)),
+			BridgeMAC: macaddr.Normalize(p.Mac),
 		}
 	} else {
 		// #639: el beacon no lleva firmware/uptime; el server los obtiene de
@@ -597,27 +599,6 @@ func (s *server) startBeaconListener(addr string) (net.Addr, error) {
 	return pc.LocalAddr(), nil
 }
 
-// normalizeBeaconMAC: el firmware envía las MAC en MAYÚSCULAS sin
-// separadores ("AABBCCDDEEFF"); el resto de la app (leases, wifi, FDB,
-// enriquecimiento) usa "AA:BB:CC:DD:EE:FF". Devuelve "" si no es una MAC.
-func normalizeBeaconMAC(mac string) string {
-	clean := strings.ToUpper(strings.TrimSpace(mac))
-	if len(clean) == 12 && !strings.Contains(clean, ":") {
-		var b strings.Builder
-		for i := 0; i < 12; i += 2 {
-			if i > 0 {
-				b.WriteByte(':')
-			}
-			b.WriteString(clean[i : i+2])
-		}
-		return b.String()
-	}
-	if len(clean) == 17 && strings.Count(clean, ":") == 5 {
-		return clean
-	}
-	return ""
-}
-
 // recordBeaconCandidate guarda/refresca un anuncio de descubrimiento (#291).
 func (s *server) recordBeaconCandidate(src string, p beaconPacket) {
 	s.beaconCandMu.Lock()

+ 23 - 1
server-go/internal/httpapi/data.go

@@ -10,6 +10,7 @@ import (
 	"strings"
 	"time"
 
+	"github.com/gnacho/netpulse/agent/macaddr"
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
 	"github.com/gnacho/netpulse/server-go/internal/clientbw"
@@ -726,7 +727,21 @@ func (s *server) handleRoamEvents(w http.ResponseWriter, r *http.Request) {
 	}
 	routerID := r.URL.Query().Get("router")
 	eventType := r.URL.Query().Get("type")
-	mac := r.URL.Query().Get("mac")
+	// El filtro mac admite lista separada por comas (#1127): cada elemento se
+	// pasa a la forma canónica que usa la tabla (AA:BB:CC:DD:EE:FF).
+	var macs []string
+	for _, part := range strings.Split(r.URL.Query().Get("mac"), ",") {
+		if strings.TrimSpace(part) == "" {
+			continue
+		}
+		m := macaddr.Normalize(part)
+		if m == "" {
+			writeError(w, http.StatusBadRequest, "invalid_mac")
+			return
+		}
+		macs = append(macs, m)
+	}
+	mac := strings.Join(macs, ",")
 	events, err := roamevents.ListEvents(s.db.DB, limit, since, routerID, eventType, mac)
 	if err != nil {
 		writeError(w, http.StatusInternalServerError, "internal_error")
@@ -764,6 +779,13 @@ func (s *server) handleDeviceEvents(w http.ResponseWriter, r *http.Request) {
 	}
 	routerID := r.URL.Query().Get("router")
 	mac := r.URL.Query().Get("mac")
+	if mac != "" {
+		// La tabla guarda MAC canónicas: ?mac=aa-bb-... debe encontrarlas.
+		if mac = macaddr.Normalize(mac); mac == "" {
+			writeError(w, http.StatusBadRequest, "invalid_mac")
+			return
+		}
+	}
 	state := r.URL.Query().Get("state")
 	events, err := deviceevents.ListEvents(s.db.DB, limit, since, routerID, mac, state)
 	if err != nil {

+ 27 - 0
server-go/internal/httpapi/device_events_test.go

@@ -92,3 +92,30 @@ func TestDeviceEventsFiltros(t *testing.T) {
 		t.Fatalf("since=2000: %d, want 2", len(events))
 	}
 }
+
+// TestDeviceEventsNormalizesMAC: ?mac acepta guiones/minúsculas y rechaza
+// valores que no son una MAC.
+func TestDeviceEventsNormalizesMAC(t *testing.T) {
+	srv := makeTestServer(t)
+	if _, err := srv.db.Exec(
+		"INSERT INTO device_events (ts_ms, mac, router_id, state) VALUES (?,?,?,?)",
+		1000, "AA:BB:CC:DD:EE:01", "rt1", "offline",
+	); err != nil {
+		t.Fatalf("seed: %v", err)
+	}
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	res := get(t, srv.URL, "/api/device-events?mac=aa-bb-cc-dd-ee-01", cookie)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("mac con guiones: got %d want 200", res.StatusCode)
+	}
+	events, _ := readJSON(t, res)["events"].([]any)
+	if len(events) != 1 {
+		t.Fatalf("esperaba 1 evento, obtuve %v", events)
+	}
+
+	res = get(t, srv.URL, "/api/device-events?mac=nope", cookie)
+	if res.StatusCode != http.StatusBadRequest {
+		t.Fatalf("mac inválida: got %d want 400", res.StatusCode)
+	}
+}

+ 40 - 0
server-go/internal/httpapi/roam_events_test.go

@@ -0,0 +1,40 @@
+// roam_events_test.go — filtro ?mac de GET /api/roam-events.
+package httpapi_test
+
+import (
+	"net/http"
+	"testing"
+)
+
+// TestRoamEventsNormalizesMAC: ?mac acepta guiones/minúsculas (también en
+// lista separada por comas) y rechaza valores que no son una MAC.
+func TestRoamEventsNormalizesMAC(t *testing.T) {
+	srv := makeTestServer(t)
+	if _, err := srv.db.Exec(
+		"INSERT INTO roam_events (ts_ms, router_id, type, mac, iface, detail, content_hash) VALUES (?,?,?,?,?,?,?)",
+		1000, "rt1", "assoc", "AA:BB:CC:DD:EE:01", "phy0-ap0", "", "h1",
+	); err != nil {
+		t.Fatalf("seed: %v", err)
+	}
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	for _, q := range []string{
+		"aa-bb-cc-dd-ee-01",
+		"aa:bb:cc:dd:ee:01",
+		"aa-bb-cc-dd-ee-01,11:22:33:44:55:66",
+	} {
+		res := get(t, srv.URL, "/api/roam-events?mac="+q, cookie)
+		if res.StatusCode != http.StatusOK {
+			t.Fatalf("mac=%s: got %d want 200", q, res.StatusCode)
+		}
+		events, _ := readJSON(t, res)["events"].([]any)
+		if len(events) != 1 {
+			t.Fatalf("mac=%s: esperaba 1 evento, obtuve %v", q, events)
+		}
+	}
+
+	res := get(t, srv.URL, "/api/roam-events?mac=nope", cookie)
+	if res.StatusCode != http.StatusBadRequest {
+		t.Fatalf("mac inválida: got %d want 400", res.StatusCode)
+	}
+}

+ 5 - 20
server-go/internal/httpapi/settings.go

@@ -9,8 +9,8 @@ import (
 	"database/sql"
 	"net/http"
 	"strconv"
-	"strings"
 
+	"github.com/gnacho/netpulse/agent/macaddr"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
@@ -333,26 +333,11 @@ type knownMacItem struct {
 	Note string `json:"note,omitempty"`
 }
 
-// validMAC normaliza y valida una dirección MAC (AA:BB:CC:DD:EE:FF).
+// validMAC normaliza y valida una dirección MAC a su forma canónica
+// (AA:BB:CC:DD:EE:FF). Acepta ':' o '-' como separador y 12 hex sin separador.
 func validMAC(raw string) (string, bool) {
-	m := strings.ToUpper(strings.TrimSpace(raw))
-	if len(m) != 17 {
-		return "", false
-	}
-	for i := 0; i < 17; i++ {
-		if i%3 == 2 {
-			if m[i] != ':' {
-				return "", false
-			}
-		} else if !isHex(m[i]) {
-			return "", false
-		}
-	}
-	return m, true
-}
-
-func isHex(c byte) bool {
-	return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')
+	m := macaddr.Normalize(raw)
+	return m, m != ""
 }
 
 // registerKnownMacsRoutes: GET/PUT/DELETE /api/settings/known-macs (admin,