Explorar o código

fix(mac): store MACs upper case in the remaining lower-case tables (#2170)

Closes #2170

Co-authored-by: Mike Grupenhoff <2231096+mgrupenhoff@users.noreply.github.com>
Mike Grupenhoff hai 1 semana
pai
achega
70ae0c5351
Modificáronse 34 ficheiros con 1091 adicións e 160 borrados
  1. 1 1
      app/src/lib/rackStale.ts
  2. 13 13
      app/src/pages/Rack.tsx
  3. 7 19
      server-go/internal/adapters/clientbw.go
  4. 34 0
      server-go/internal/adapters/clientbw_test.go
  5. 1 1
      server-go/internal/adapters/device_seen.go
  6. 11 8
      server-go/internal/adapters/live.go
  7. 2 2
      server-go/internal/adapters/override_builddevices_test.go
  8. 44 22
      server-go/internal/adapters/topology_override.go
  9. 34 0
      server-go/internal/adapters/topology_override_test.go
  10. 242 0
      server-go/internal/db/db.go
  11. 315 0
      server-go/internal/db/mac_migration_test.go
  12. 5 1
      server-go/internal/httpapi/agentstate.go
  13. 39 0
      server-go/internal/httpapi/agentstate_restore_macs_test.go
  14. 2 2
      server-go/internal/httpapi/data.go
  15. 37 24
      server-go/internal/httpapi/device_actions.go
  16. 47 0
      server-go/internal/httpapi/device_actions_multimac_test.go
  17. 33 0
      server-go/internal/httpapi/device_actions_test.go
  18. 5 26
      server-go/internal/httpapi/device_overrides.go
  19. 2 2
      server-go/internal/httpapi/device_overrides_test.go
  20. 3 2
      server-go/internal/httpapi/dns.go
  21. 1 1
      server-go/internal/httpapi/httpapi_test.go
  22. 4 7
      server-go/internal/httpapi/onboarding.go
  23. 3 3
      server-go/internal/httpapi/presence.go
  24. 7 5
      server-go/internal/httpapi/racks.go
  25. 19 0
      server-go/internal/httpapi/racks_error_test.go
  26. 10 8
      server-go/internal/httpapi/topology_override.go
  27. 89 0
      server-go/internal/httpapi/topology_override_test.go
  28. 3 2
      server-go/internal/rack/import.go
  29. 5 5
      server-go/internal/rack/import_test.go
  30. 11 0
      server-go/internal/rack/store.go
  31. 55 2
      server-go/internal/rack/store_test.go
  32. 1 1
      server-go/internal/rack/types.go
  33. 5 2
      server-go/internal/topooverride/topooverride.go
  34. 1 1
      server-go/internal/topooverride/topooverride_test.go

+ 1 - 1
app/src/lib/rackStale.ts

@@ -25,7 +25,7 @@ export function computeStalePorts(
 ): StalePortsEntry[] {
   const out: StalePortsEntry[] = []
   for (const m of mounts) {
-    const mac = m.device_mac?.toLowerCase()
+    const mac = m.device_mac?.toUpperCase()
     if (!mac) continue
     const prof = profiles.get(mac)
     const live = liveByMac.get(mac)

+ 13 - 13
app/src/pages/Rack.tsx

@@ -67,14 +67,14 @@ function RackCanvas() {
   // #1151: nombre real de las unidades de flota por MAC (los routers/switches
   // de la flota no están en np.devices - eso son clientes).
   const routerNameByMac = useMemo(
-    () => new Map(np.routers.flatMap((r) => (r.mac ? [[r.mac.toLowerCase(), r.name] as const] : []))),
+    () => new Map(np.routers.flatMap((r) => (r.mac ? [[r.mac.toUpperCase(), r.name] as const] : []))),
     [np.routers],
   )
   // #1804: los perfiles guardados antes de este cambio solo llevan el id de la
   // boca (snmp-49153 en un switch SNMP). La etiqueta legible se resuelve
   // contra el detalle vivo de cada unidad montada, una vez por MAC.
   const routerIdByMac = useMemo(
-    () => new Map(np.routers.flatMap((r) => (r.mac ? [[r.mac.toLowerCase(), r.id] as const] : []))),
+    () => new Map(np.routers.flatMap((r) => (r.mac ? [[r.mac.toUpperCase(), r.id] as const] : []))),
     [np.routers],
   )
   const [portLabels, setPortLabels] = useState<Map<string, Record<string, string>>>(new Map())
@@ -92,7 +92,7 @@ function RackCanvas() {
 
   const labelMacs = useMemo(() => {
     const out = new Set<string>()
-    for (const m of working.mounts) if (m.device_mac) out.add(m.device_mac.toLowerCase())
+    for (const m of working.mounts) if (m.device_mac) out.add(m.device_mac.toUpperCase())
     return out
   }, [working.mounts])
 
@@ -344,7 +344,7 @@ function RackCanvas() {
   }, [reload])
 
   // --- Modelo derivado ---
-  const deviceByMac = useMemo(() => new Map(np.devices.map((d) => [d.mac.toLowerCase(), d])), [np.devices])
+  const deviceByMac = useMemo(() => new Map(np.devices.map((d) => [d.mac.toUpperCase(), d])), [np.devices])
   const rackById = useMemo(() => new Map(working.racks.map((r) => [r.id, r])), [working.racks])
   const mountById = useMemo(() => new Map(working.mounts.map((m) => [m.id, m])), [working.mounts])
 
@@ -356,7 +356,7 @@ function RackCanvas() {
         if (plate) return plate
         // Perfil placeholder/vacío: sugerimos por el tipo detectado del
         // dispositivo (un switch nunca debe quedarse sin bocas LAN).
-        const devType = deviceByMac.get(m.device_mac.toLowerCase())?.type ?? ''
+        const devType = deviceByMac.get(m.device_mac.toUpperCase())?.type ?? ''
         return suggestFaceplate(devType) ?? getFaceplate('blank-1u')!
       }
       return getFaceplate(m.faceplate_id || 'blank-1u') || getFaceplate('blank-1u')!
@@ -374,7 +374,7 @@ function RackCanvas() {
           // #2010: si el sondeo ya dice qué bocas son físicas, el frontal pinta
           // solo esas. Lo guardado sigue intacto hasta que el usuario limpie
           // (banner de puertos obsoletos), así que esto es solo presentación.
-          const live = livePhysicalPorts.get(m.device_mac.toLowerCase())
+          const live = livePhysicalPorts.get(m.device_mac.toUpperCase())
           const liveSet = live && live.length > 0 ? new Set(live) : null
           const kept = liveSet ? declared.filter((p) => liveSet.has(p.id)) : declared
           if (liveSet && kept.length !== declared.length) {
@@ -405,7 +405,7 @@ function RackCanvas() {
     (m: MountDTO): 'online' | 'offline' | 'unknown' => {
       if (m.status_pin && m.status_pin !== 'auto') return m.status_pin as 'online' | 'offline' | 'unknown'
       if (!m.device_mac) return 'unknown'
-      const d = deviceByMac.get(m.device_mac.toLowerCase())
+      const d = deviceByMac.get(m.device_mac.toUpperCase())
       if (!d) return 'unknown'
       return d.online ? 'online' : 'offline'
     },
@@ -536,13 +536,13 @@ function RackCanvas() {
           plate,
           ports: portsFor(m).map((p) => ({
             ...p,
-            label: p.label ?? (m.device_mac ? portLabels.get(m.device_mac.toLowerCase())?.[p.id] : undefined),
+            label: p.label ?? (m.device_mac ? portLabels.get(m.device_mac.toUpperCase())?.[p.id] : undefined),
           })),
           mountId: m.id,
           label:
             m.label ||
-            deviceByMac.get(m.device_mac?.toLowerCase() ?? '')?.name ||
-            routerNameByMac.get(m.device_mac?.toLowerCase() ?? '') ||
+            deviceByMac.get(m.device_mac?.toUpperCase() ?? '')?.name ||
+            routerNameByMac.get(m.device_mac?.toUpperCase() ?? '') ||
             '',
           color: m.device_mac ? working.profiles.get(m.device_mac)?.color || undefined : undefined,
           status: statusFor(m),
@@ -1134,7 +1134,7 @@ function RackCanvas() {
 
   // --- Picker data ---
   const mountedMacs = useMemo(
-    () => new Set(working.mounts.map((m) => m.device_mac?.toLowerCase() ?? '')),
+    () => new Set(working.mounts.map((m) => m.device_mac?.toUpperCase() ?? '')),
     [working.mounts],
   )
   // Solo cableados: el rack es físico; WiFi (2.4/5/6/60 GHz) queda fuera.
@@ -1149,7 +1149,7 @@ function RackCanvas() {
       // portátiles y electrodomésticos de sala.
       np.devices.filter(
         (d) =>
-          !mountedMacs.has(d.mac.toLowerCase()) &&
+          !mountedMacs.has(d.mac.toUpperCase()) &&
           (d.band === 'cable' || d.band === '—') &&
           d.infra !== 'ct' &&
           d.infra !== 'vm' &&
@@ -1158,7 +1158,7 @@ function RackCanvas() {
     [np.devices, mountedMacs],
   )
   const unmountedRouters = useMemo(
-    () => np.routers.filter((r) => r.mac && !mountedMacs.has(r.mac.toLowerCase())),
+    () => np.routers.filter((r) => r.mac && !mountedMacs.has(r.mac.toUpperCase())),
     [np.routers, mountedMacs],
   )
   const accessoryPlates = useMemo(() => FACEPLATES.filter((p) => p.group === 'accessory'), [])

+ 7 - 19
server-go/internal/adapters/clientbw.go

@@ -20,9 +20,9 @@
 package adapters
 
 import (
-	"strings"
 	"time"
 
+	"github.com/gnacho/netpulse/agent/macaddr"
 	"github.com/gnacho/netpulse/agent/probe"
 	"github.com/gnacho/netpulse/server-go/internal/clientbw"
 )
@@ -49,25 +49,10 @@ type clientBwSample struct {
 	tx  uint64
 }
 
-// canonBWMac normaliza la MAC al formato canónico del server para las rutas
-// /api/devices/{mac}/* (minúsculas con ':'). Las fuentes (hostapd/nlbwmon)
-// entregan mayúsculas; la store client_bw_raw debe casar con normalizeMAC.
+// canonBWMac devuelve la MAC en la forma canónica (AA:BB:CC:DD:EE:FF), o ""
+// si mac no es una MAC válida de 6 octetos.
 func canonBWMac(mac string) string {
-	var b strings.Builder
-	for _, r := range strings.ToLower(mac) {
-		if (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') {
-			b.WriteRune(r)
-		}
-	}
-	s := b.String()
-	var out strings.Builder
-	for i := 0; i+1 < len(s); i += 2 {
-		if i > 0 {
-			out.WriteByte(':')
-		}
-		out.WriteString(s[i : i+2])
-	}
-	return out.String()
+	return macaddr.Normalize(mac)
 }
 
 // recordClientBwSamples persiste el delta de cada cliente desde el último
@@ -136,6 +121,9 @@ func (l *Live) recordClientBwSamples(routerID string, now time.Time, samples []c
 // ya contabiliza todo el tráfico de la MAC; sumar hostapd doblaría).
 func (l *Live) clientBwRateFor(mac string) (rxBps, txBps float64) {
 	mac = canonBWMac(mac)
+	if mac == "" {
+		return 0, 0
+	}
 	l.mu.Lock()
 	defer l.mu.Unlock()
 	if c := l.findClientBwRate(mac, "nlbwmon"); c != nil {

+ 34 - 0
server-go/internal/adapters/clientbw_test.go

@@ -188,3 +188,37 @@ func TestClientBwRateForPriorizaFuente(t *testing.T) {
 		t.Fatalf("rate tx: %.0f (want 0)", tx)
 	}
 }
+
+// TestCanonBWMacRejectsNonMAC comprueba que canonBWMac devuelve la forma
+// canónica en mayúsculas para MACs válidas y "" para cadenas que no son MAC
+// (p. ej. una IP como "192.168.1.1"), de modo que no se persistan en
+// client_bw_raw.
+func TestCanonBWMacRejectsNonMAC(t *testing.T) {
+	cases := []struct {
+		name string
+		in   string
+		want string
+	}{
+		{name: "IPv4 no es MAC", in: "192.168.1.1", want: ""},
+		{name: "texto arbitrario", in: "no-es-mac", want: ""},
+		{name: "MAC en minúsculas", in: "aa:bb:cc:dd:ee:01", want: "AA:BB:CC:DD:EE:01"},
+		{name: "MAC con guiones", in: "aa-bb-cc-dd-ee-01", want: "AA:BB:CC:DD:EE:01"},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			if got := canonBWMac(tc.in); got != tc.want {
+				t.Errorf("canonBWMac(%q) = %q, esperaba %q", tc.in, got, tc.want)
+			}
+		})
+	}
+
+	d := openLiveTestDB(t)
+	l := &Live{db: d}
+	t0 := time.Now()
+	t1 := t0.Add(10 * time.Second)
+	l.recordClientBwSamples("gw", t0, []clientBwSample{{mac: "192.168.1.1", rx: 100, tx: 100}}, "nlbwmon")
+	l.recordClientBwSamples("gw", t1, []clientBwSample{{mac: "192.168.1.1", rx: 500, tx: 500}}, "nlbwmon")
+	if n := countRawClientBW(t, d); n != 0 {
+		t.Fatalf("una IP no debe escribirse en client_bw_raw, hay %d filas", n)
+	}
+}

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

@@ -552,7 +552,7 @@ func (l *Live) ghostDevices(devices []Device) []Device {
 		// #437/#797: el override manual manda también en el fantasma offline
 		// (icono, nombre y tipo). Sin esto un cliente retenido perdía su icono
 		// al caer offline y no reflejaba los cambios hechos estando offline.
-		if ov, ok := overrides[strings.ToLower(mac)]; ok {
+		if ov, ok := overrides[mac]; ok {
 			if ov.Icon != "" {
 				d.IconOverride = ov.Icon
 			}

+ 11 - 8
server-go/internal/adapters/live.go

@@ -1819,10 +1819,13 @@ type overrideInfo struct {
 	NotifyOffline bool
 }
 
-// loadDeviceOverrides lee los overrides manuales, con clave en minúsculas
-// para que el lookup sea robusto al caso de la MAC (#797). Lo usan tanto
-// buildDevices (clientes vivos) como ghostDevices (retenidos offline):
-// un override debe verse igual esté el cliente online u offline.
+// loadDeviceOverrides lee los overrides manuales, con clave por la MAC tal
+// como está guardada: ya canónica (AA:BB:CC:DD:EE:FF), porque el handler la
+// normaliza al escribir y la migración pasó las filas antiguas. Las MAC de
+// los dispositivos también lo son desde su fuente (#960), así que el lookup
+// es exacto. Lo usan tanto buildDevices (clientes vivos) como ghostDevices
+// (retenidos offline): un override debe verse igual esté el cliente online u
+// offline (#797).
 func (l *Live) loadDeviceOverrides() map[string]overrideInfo {
 	out := map[string]overrideInfo{}
 	if l.db == nil {
@@ -1838,7 +1841,7 @@ func (l *Live) loadDeviceOverrides() map[string]overrideInfo {
 		var icon sql.NullString
 		var notifyOffline bool
 		if err := rows.Scan(&mac, &icon, &name, &deviceType, &bannedBands, &notifyOffline); err == nil {
-			out[strings.ToLower(mac)] = overrideInfo{Icon: icon.String, Name: name, DeviceType: deviceType, BannedBands: bannedBands, NotifyOffline: notifyOffline}
+			out[mac] = overrideInfo{Icon: icon.String, Name: name, DeviceType: deviceType, BannedBands: bannedBands, NotifyOffline: notifyOffline}
 		}
 	}
 	return out
@@ -4113,7 +4116,7 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 		// issue #437/#797: overrides manuales (icono, nombre) se aplican sobre
 		// el dispositivo auto-descubierto; el nombre manual manda incluso
 		// sobre el alias de la allowlist.
-		if ov, ok := deviceOverrides[strings.ToLower(mac)]; ok {
+		if ov, ok := deviceOverrides[mac]; ok {
 			if ov.Icon != "" {
 				d.IconOverride = ov.Icon
 			}
@@ -4185,12 +4188,12 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 		}
 		// issue #797: el tipo manual manda sobre la clasificación (reglas,
 		// huella DHCP y refinación mDNS).
-		if ov, ok := deviceOverrides[strings.ToLower(mac)]; ok && ov.DeviceType != "" {
+		if ov, ok := deviceOverrides[mac]; ok && ov.DeviceType != "" {
 			d.Type = ov.DeviceType
 			d.TypeOverride = ov.DeviceType
 		}
 		// #1354: flag opt-in de alerta por desconexión (override persistido).
-		if ov, ok := deviceOverrides[strings.ToLower(mac)]; ok {
+		if ov, ok := deviceOverrides[mac]; ok {
 			d.NotifyOffline = ov.NotifyOffline
 		}
 		if isSeen {

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

@@ -16,7 +16,7 @@ func TestBuildDevicesNameTypeIconOverride(t *testing.T) {
 	now := time.Now().UnixMilli()
 	_, err := d.Exec(
 		`INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, created_at, updated_at)
-		 VALUES ('aa:bb:cc:dd:ee:ff', 'tv', 'TV Salón', 'tv', '', ?, ?)`, now, now)
+		 VALUES ('AA:BB:CC:DD:EE:FF', 'tv', 'TV Salón', 'tv', '', ?, ?)`, now, now)
 	if err != nil {
 		t.Fatalf("seed override: %v", err)
 	}
@@ -54,7 +54,7 @@ func TestGhostDevicesApplyManualOverrides(t *testing.T) {
 	now := time.Now().UnixMilli()
 	if _, err := d.Exec(
 		`INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, created_at, updated_at)
-		 VALUES ('aa:bb:cc:dd:ee:ff', 'projector', '投影', 'tv', '', ?, ?)`, now, now); err != nil {
+		 VALUES ('AA:BB:CC:DD:EE:FF', 'projector', '投影', 'tv', '', ?, ?)`, now, now); err != nil {
 		t.Fatalf("seed override: %v", err)
 	}
 	ghosts := l.ghostDevices(nil)

+ 44 - 22
server-go/internal/adapters/topology_override.go

@@ -22,8 +22,9 @@ package adapters
 import (
 	"database/sql"
 	"fmt"
-	"regexp"
 	"strings"
+
+	"github.com/gnacho/netpulse/agent/macaddr"
 )
 
 // queryer: subset de *sql.DB usado para cargar overrides (evita acoplar a db.DB).
@@ -59,12 +60,38 @@ func loadTopologyOverrides(q queryer) []TopologyOverride {
 	return out
 }
 
-// NormalizeMAC normaliza una MAC a minúsculas sin espacios (formato de
-// comparación de la capa de overrides y del resto del pipeline).
+// colonMAC devuelve la forma canónica (AA:BB:CC:DD:EE:FF) si s es una MAC
+// escrita con ':', o "". Los campos de override admiten también ids de router,
+// que son slugs (minúsculas, '-', sin ':'): uno como "aa-bb-cc-dd-ee-ff" o
+// "cafebabe1234" no debe leerse como MAC, así que solo cuenta la forma con ':'.
+func colonMAC(s string) string {
+	s = strings.TrimSpace(s)
+	if strings.Count(s, ":") != 5 {
+		return ""
+	}
+	return macaddr.Normalize(s)
+}
+
+// NormalizeMAC normaliza el target de un override: una MAC con ':' en forma
+// canónica; cualquier otra cosa es un id de router (#1485: unidad de flota sin
+// MAC de bridge) y se devuelve en minúsculas sin espacios, como antes.
 func NormalizeMAC(mac string) string {
+	if m := colonMAC(mac); m != "" {
+		return m
+	}
 	return strings.ToLower(strings.TrimSpace(mac))
 }
 
+// NormalizeParentRef normaliza el parent de un override antes de guardarlo:
+// una MAC con ':' en forma canónica; una referencia de router ("routerId" o
+// "routerId:puerto") solo sin espacios alrededor.
+func NormalizeParentRef(raw string) string {
+	if m := colonMAC(raw); m != "" {
+		return m
+	}
+	return strings.TrimSpace(raw)
+}
+
 // deviceIndexByMAC indexa devices por MAC normalizada.
 func deviceIndexByMAC(devices []Device) map[string]int {
 	m := make(map[string]int, len(devices))
@@ -76,9 +103,6 @@ func deviceIndexByMAC(devices []Device) map[string]int {
 	return m
 }
 
-// macRe reconoce una MAC normalizada (6 octetos hex separados por ':').
-var macRe = regexp.MustCompile(`^([0-9a-f]{2}:){5}[0-9a-f]{2}$`)
-
 // parentRefKind clasifica el `parent` de un override kind=attach (issue #690).
 type parentRefKind int
 
@@ -93,25 +117,24 @@ const (
 type routerPort struct{ router, port string }
 
 // parseParentRef clasifica el `parent` de un override attach. Formato:
-//   - MAC ("aa:bb:cc:dd:ee:ff"): cuelga del device con esa MAC (formato
+//   - MAC ("AA:BB:CC:DD:EE:FF"): cuelga del device con esa MAC (formato
 //     original, se mantiene).
 //   - "<routerId>": cuelga directamente del router.
 //   - "<routerId>:<puerto>": cuelga del puerto concreto del router.
 //
-// No hay ambigüedad: los slugs de router no contienen ':' (routerstore.slugify
-// mapea [^a-z0-9]+ → '-') y las MAC siempre llevan 5 ':'. Un valor con ':' que
-// casa con la regex MAC es una MAC; con exactamente un ':' es router:puerto;
-// sin ':' es un router; cualquier otra forma es inválida.
+// Una MAC solo cuenta en la forma con ':' (ver colonMAC). La referencia de
+// router se compara en minúsculas, id y puerto, como siempre.
 func parseParentRef(parent string) (kind parentRefKind, routerID, port, mac string) {
-	p := NormalizeMAC(parent)
+	p := strings.TrimSpace(parent)
 	if p == "" {
 		return parentRefInvalid, "", "", ""
 	}
-	if macRe.MatchString(p) {
-		return parentRefMAC, "", "", p
+	if m := colonMAC(p); m != "" {
+		return parentRefMAC, "", "", m
 	}
+	p = strings.ToLower(p)
 	if i := strings.IndexByte(p, ':'); i >= 0 {
-		routerID, port = p[:i], p[i+1:]
+		routerID, port = strings.TrimSpace(p[:i]), strings.TrimSpace(p[i+1:])
 		if routerID == "" || port == "" {
 			return parentRefInvalid, "", "", ""
 		}
@@ -305,7 +328,7 @@ func fleetOverrideEvidence(overrides []TopologyOverride, routers []Router) map[s
 			// alta como external sin MAC) no se puede fijar por MAC. El target
 			// puede ser su id de router: así la intención del admin siempre se
 			// puede expresar, sea cual sea la forma en que se registró.
-			rid, ok = routerIDByLower[NormalizeMAC(o.MAC)]
+			rid, ok = routerIDByLower[strings.ToLower(strings.TrimSpace(o.MAC))]
 			if !ok {
 				continue
 			}
@@ -315,18 +338,17 @@ func fleetOverrideEvidence(overrides []TopologyOverride, routers []Router) map[s
 			continue
 		}
 		var parent, port string
-		switch {
-		case macRe.MatchString(strings.ToLower(p)):
-			parent = routerByMac[strings.ToLower(p)]
+		if m := colonMAC(p); m != "" {
+			parent = routerByMac[m]
 			if parent == "" {
 				continue // el target no es un router de flota
 			}
-		default:
+		} else {
 			routerID := ""
 			if i := strings.IndexByte(p, ':'); i >= 0 {
-				routerID, port = NormalizeMAC(p[:i]), strings.TrimSpace(p[i+1:])
+				routerID, port = strings.ToLower(strings.TrimSpace(p[:i])), strings.TrimSpace(p[i+1:])
 			} else {
-				routerID = NormalizeMAC(p)
+				routerID = strings.ToLower(p)
 			}
 			if !routerByID[routerID] {
 				continue

+ 34 - 0
server-go/internal/adapters/topology_override_test.go

@@ -382,3 +382,37 @@ func TestFleetOverrideEvidenceTargetByRouterID(t *testing.T) {
 		t.Fatalf("un target desconocido no debe generar evidencia: %+v", ev)
 	}
 }
+
+// TestParseParentRefMACOnlyWithColons comprueba que solo una MAC con ':' es
+// una MAC: los ids de router son slugs, y uno que parece una MAC con guiones
+// o 12 dígitos hex sigue siendo una referencia de router.
+func TestParseParentRefMACOnlyWithColons(t *testing.T) {
+	cases := []struct {
+		in                  string
+		kind                parentRefKind
+		routerID, port, mac string
+	}{
+		{"c8:ff:BF:08:6f:ba", parentRefMAC, "", "", "C8:FF:BF:08:6F:BA"},
+		{"c8-ff-bf-08-6f-ba", parentRefRouter, "c8-ff-bf-08-6f-ba", "", ""},
+		{"cafebabe1234", parentRefRouter, "cafebabe1234", "", ""},
+		{" Rtr1:LAN4 ", parentRefPort, "rtr1", "lan4", ""},
+	}
+	for _, c := range cases {
+		kind, routerID, port, mac := parseParentRef(c.in)
+		if kind != c.kind || routerID != c.routerID || port != c.port || mac != c.mac {
+			t.Errorf("parseParentRef(%q) = %v %q %q %q, esperaba %v %q %q %q", c.in, kind, routerID, port, mac, c.kind, c.routerID, c.port, c.mac)
+		}
+	}
+
+	devices := []Device{
+		devOverride("host", "C8:FF:BF:08:6F:BA", "rtr1", "lan4"),
+		devOverride("vm", "02:78:F4:02:8A:94", "rtr1", "lan4"),
+	}
+	overrides := []TopologyOverride{
+		{Kind: "attach", MAC: "02:78:f4:02:8a:94", Parent: "c8:ff:bf:08:6f:ba", Enabled: true},
+	}
+	out, _ := applyTopologyOverrides(nil, devices, nil, overrides)
+	if out[1].AttachTo != "host" {
+		t.Fatalf("esperaba VM anidada bajo host con parent en minúsculas, got %+v", out[1])
+	}
+}

+ 242 - 0
server-go/internal/db/db.go

@@ -830,11 +830,253 @@ func Open(dir string, opts ...OpenOption) (*DB, error) {
 		return nil, fmt.Errorf("client_bw store: %w", err)
 	}
 	d.ClientBW = cb
+	migrateLowercaseMACTables(sqldb)
 	d.wg.Add(1)
 	go d.maintenanceLoop()
 	return d, nil
 }
 
+// migrateLowercaseMACTables pasa a la forma canónica en mayúsculas
+// (AA:BB:CC:DD:EE:FF) las tablas que históricamente guardaban MACs en
+// minúsculas. Corre tras clientbw.NewStore para que client_bw_* ya existan.
+// Corre una sola vez: todos los pasos van en una transacción que, al terminar
+// bien, deja la marca macUpperMigratedKey en kv; los arranques siguientes no
+// vuelven a recorrer client_bw_* (millones de filas). Si un paso falla, se
+// registra un warning, se deshace todo y se reintenta en el siguiente arranque;
+// el arranque nunca se aborta.
+func migrateLowercaseMACTables(sqldb *sql.DB) {
+	var done int
+	if err := sqldb.QueryRow("SELECT COUNT(*) FROM kv WHERE key = ?", macUpperMigratedKey).Scan(&done); err == nil && done > 0 {
+		return
+	}
+	type step struct {
+		name string
+		sql  string
+	}
+	steps := []step{
+		// device_overrides: PK (mac), sobrevive la fila con updated_at más reciente
+		// (empate: la que ya esté en forma canónica, luego mayor rowid).
+		{
+			name: "dedup device_overrides MACs",
+			sql: `DELETE FROM device_overrides
+				WHERE ` + macOnlyMatch("mac") + `
+				  AND EXISTS (
+				    SELECT 1 FROM device_overrides o2
+				    WHERE ` + macOnlyMatch("o2.mac") + `
+				      AND UPPER(REPLACE(o2.mac, '-', ':')) = UPPER(REPLACE(device_overrides.mac, '-', ':'))
+				      AND o2.rowid != device_overrides.rowid
+				      AND (
+				        o2.updated_at > device_overrides.updated_at
+				        OR (o2.updated_at = device_overrides.updated_at AND (o2.mac = UPPER(REPLACE(o2.mac, '-', ':'))) > (device_overrides.mac = UPPER(REPLACE(device_overrides.mac, '-', ':'))))
+				        OR (o2.updated_at = device_overrides.updated_at AND (o2.mac = UPPER(REPLACE(o2.mac, '-', ':'))) = (device_overrides.mac = UPPER(REPLACE(device_overrides.mac, '-', ':'))) AND o2.rowid > device_overrides.rowid)
+				      )
+				  )`,
+		},
+		{
+			name: "normalize device_overrides MACs",
+			sql: `UPDATE device_overrides
+				SET mac = UPPER(REPLACE(mac, '-', ':'))
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
+		},
+		// topology_overrides: PK (id = mac). mac y parent solo se reescriben si
+		// son una MAC con ':'; cualquier otra cosa es un id de router (#1485,
+		// #690) y se deja como está.
+		{
+			name: "dedup topology_overrides MACs",
+			sql: `DELETE FROM topology_overrides
+				WHERE mac GLOB '` + colonMACGlob + `'
+				  AND EXISTS (
+				    SELECT 1 FROM topology_overrides t2
+				    WHERE t2.mac GLOB '` + colonMACGlob + `'
+				      AND UPPER(REPLACE(t2.mac, '-', ':')) = UPPER(REPLACE(topology_overrides.mac, '-', ':'))
+				      AND t2.rowid != topology_overrides.rowid
+				      AND (
+				        t2.updated_at > topology_overrides.updated_at
+				        OR (t2.updated_at = topology_overrides.updated_at AND (t2.mac = UPPER(REPLACE(t2.mac, '-', ':'))) > (topology_overrides.mac = UPPER(REPLACE(topology_overrides.mac, '-', ':'))))
+				        OR (t2.updated_at = topology_overrides.updated_at AND (t2.mac = UPPER(REPLACE(t2.mac, '-', ':'))) = (topology_overrides.mac = UPPER(REPLACE(topology_overrides.mac, '-', ':'))) AND t2.rowid > topology_overrides.rowid)
+				      )
+				  )`,
+		},
+		{
+			name: "normalize topology_overrides MACs",
+			sql: `UPDATE topology_overrides
+				SET id = UPPER(REPLACE(mac, '-', ':')),
+				    mac = UPPER(REPLACE(mac, '-', ':'))
+				WHERE mac GLOB '` + colonMACGlob + `'
+				  AND (mac != UPPER(REPLACE(mac, '-', ':')) OR id != UPPER(REPLACE(mac, '-', ':')))`,
+		},
+		{
+			name: "normalize topology_overrides parent MACs",
+			// main guardaba el parent tal cual llegaba, sin recortar espacios.
+			// TRIM sin segundo argumento solo quita ' '; se recortan también
+			// '\t', '\n' y '\r', como strings.TrimSpace.
+			sql: `UPDATE topology_overrides
+				SET parent = UPPER(` + trimWS("parent") + `)
+				WHERE parent IS NOT NULL
+				  AND ` + trimWS("parent") + ` GLOB '` + colonMACGlob + `'
+				  AND parent != UPPER(` + trimWS("parent") + `)`,
+		},
+		// client_bw_raw, client_bw_5m, client_bw_daily: en colisión sobre
+		// (mac, router_id, ts/bucket_ts/date) sobrevive la fila ya canónica.
+		{
+			// Tablas grandes: el duplicado canónico se busca por la clave
+			// primaria (índice), no con una subconsulta que recorra la tabla.
+			name: "dedup client_bw_raw MACs",
+			sql: `DELETE FROM client_bw_raw
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))
+				  AND EXISTS (
+				    SELECT 1 FROM client_bw_raw b2
+				    WHERE b2.mac = UPPER(REPLACE(client_bw_raw.mac, '-', ':'))
+				      AND b2.router_id = client_bw_raw.router_id
+				      AND b2.ts = client_bw_raw.ts
+				  )`,
+		},
+		{
+			// OR IGNORE: dos variantes no canónicas de la misma clave (no
+			// ocurre con datos reales) no deben abortar el resto; la que queda
+			// sin actualizar se borra en el paso siguiente.
+			name: "normalize client_bw_raw MACs",
+			sql: `UPDATE OR IGNORE client_bw_raw
+				SET mac = UPPER(REPLACE(mac, '-', ':'))
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
+		},
+		{
+			name: "drop leftover client_bw_raw MAC variants",
+			sql: `DELETE FROM client_bw_raw
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
+		},
+		{
+			// Tablas grandes: el duplicado canónico se busca por la clave
+			// primaria (índice), no con una subconsulta que recorra la tabla.
+			name: "dedup client_bw_5m MACs",
+			sql: `DELETE FROM client_bw_5m
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))
+				  AND EXISTS (
+				    SELECT 1 FROM client_bw_5m b2
+				    WHERE b2.mac = UPPER(REPLACE(client_bw_5m.mac, '-', ':'))
+				      AND b2.router_id = client_bw_5m.router_id
+				      AND b2.bucket_ts = client_bw_5m.bucket_ts
+				  )`,
+		},
+		{
+			// OR IGNORE: dos variantes no canónicas de la misma clave (no
+			// ocurre con datos reales) no deben abortar el resto; la que queda
+			// sin actualizar se borra en el paso siguiente.
+			name: "normalize client_bw_5m MACs",
+			sql: `UPDATE OR IGNORE client_bw_5m
+				SET mac = UPPER(REPLACE(mac, '-', ':'))
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
+		},
+		{
+			name: "drop leftover client_bw_5m MAC variants",
+			sql: `DELETE FROM client_bw_5m
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
+		},
+		{
+			// Tablas grandes: el duplicado canónico se busca por la clave
+			// primaria (índice), no con una subconsulta que recorra la tabla.
+			name: "dedup client_bw_daily MACs",
+			sql: `DELETE FROM client_bw_daily
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))
+				  AND EXISTS (
+				    SELECT 1 FROM client_bw_daily b2
+				    WHERE b2.mac = UPPER(REPLACE(client_bw_daily.mac, '-', ':'))
+				      AND b2.router_id = client_bw_daily.router_id
+				      AND b2.date = client_bw_daily.date
+				  )`,
+		},
+		{
+			// OR IGNORE: dos variantes no canónicas de la misma clave (no
+			// ocurre con datos reales) no deben abortar el resto; la que queda
+			// sin actualizar se borra en el paso siguiente.
+			name: "normalize client_bw_daily MACs",
+			sql: `UPDATE OR IGNORE client_bw_daily
+				SET mac = UPPER(REPLACE(mac, '-', ':'))
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
+		},
+		{
+			name: "drop leftover client_bw_daily MAC variants",
+			sql: `DELETE FROM client_bw_daily
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
+		},
+		// device_rack_profile y rack_mounts: rack_mounts.device_mac tiene
+		// REFERENCES device_rack_profile(mac) ON DELETE SET NULL con
+		// foreign_keys=ON. Primero se inserta la fila canónica en
+		// device_rack_profile (INSERT OR IGNORE preserva la ya mayúscula si
+		// existían ambas), luego se reasigna rack_mounts.device_mac y por
+		// último se borran los perfiles no canónicos sin disparar SET NULL.
+		{
+			name: "copy device_rack_profile MACs to canonical",
+			sql: `INSERT OR IGNORE INTO device_rack_profile (mac, faceplate_id, u_height, col_span, color, ports_json)
+				SELECT UPPER(REPLACE(mac, '-', ':')), faceplate_id, u_height, col_span, color, ports_json
+				FROM device_rack_profile
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
+		},
+		{
+			name: "normalize rack_mounts device_mac",
+			sql: `UPDATE rack_mounts
+				SET device_mac = UPPER(REPLACE(device_mac, '-', ':'))
+				WHERE device_mac IS NOT NULL
+				  AND ` + macOnlyMatch("device_mac") + `
+				  AND device_mac != UPPER(REPLACE(device_mac, '-', ':'))`,
+		},
+		{
+			name: "delete non-canonical device_rack_profile MACs",
+			sql: `DELETE FROM device_rack_profile
+				WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
+		},
+	}
+	start := time.Now()
+	tx, err := sqldb.Begin()
+	if err != nil {
+		log.Printf("[netpulse] warning: could not start the MAC migration: %v", err)
+		return
+	}
+	for _, s := range steps {
+		if _, err := tx.Exec(s.sql); err != nil {
+			_ = tx.Rollback()
+			log.Printf("[netpulse] warning: could not %s, MAC migration rolled back: %v", s.name, err)
+			return
+		}
+	}
+	if _, err := tx.Exec("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING",
+		macUpperMigratedKey, time.Now().Format(time.RFC3339)); err != nil {
+		_ = tx.Rollback()
+		log.Printf("[netpulse] warning: could not mark the MAC migration done: %v", err)
+		return
+	}
+	if err := tx.Commit(); err != nil {
+		log.Printf("[netpulse] warning: could not commit the MAC migration: %v", err)
+		return
+	}
+	log.Printf("[netpulse] db: MACs in overrides, rack and client_bw tables upper-cased (%v)", time.Since(start).Round(time.Millisecond))
+}
+
+// macUpperMigratedKey marca en kv que migrateLowercaseMACTables ya corrió.
+const macUpperMigratedKey = "mac_upper_tables_migrated"
+
+// Patrones GLOB de una MAC de 17 caracteres. topology_overrides solo admite la
+// forma con ':', porque sus columnas también guardan ids de router (slugs con
+// '-', que pueden parecer una MAC con guiones); las demás tablas solo guardan
+// MACs y aceptan también '-'. Como macaddr.Normalize, el separador debe ser el
+// mismo en las cinco posiciones: "aa-bb:cc-…" no es una MAC.
+var (
+	colonMACGlob = strings.Repeat("[0-9A-Fa-f][0-9A-Fa-f]:", 5) + "[0-9A-Fa-f][0-9A-Fa-f]"
+	dashMACGlob  = strings.Repeat("[0-9A-Fa-f][0-9A-Fa-f]-", 5) + "[0-9A-Fa-f][0-9A-Fa-f]"
+)
+
+// trimWS devuelve la expresión SQL que recorta espacios, tabuladores y saltos
+// de línea a ambos lados de col.
+func trimWS(col string) string {
+	return "TRIM(" + col + ", ' ' || char(9) || char(10) || char(13))"
+}
+
+// macOnlyMatch devuelve la condición SQL "col es una MAC con ':' o con '-'",
+// para las tablas que solo guardan MACs.
+func macOnlyMatch(col string) string {
+	return "(" + col + " GLOB '" + colonMACGlob + "' OR " + col + " GLOB '" + dashMACGlob + "')"
+}
+
 // migrate replica src/db.js:143-150: introspección PRAGMA table_info y DDL
 // tragándose errores.
 func migrate(db *sql.DB, table, column, ddl string) {

+ 315 - 0
server-go/internal/db/mac_migration_test.go

@@ -0,0 +1,315 @@
+package db_test
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// TestOpenMigratesLowercaseMACTables verifica que la migración de arranque
+// normaliza a la forma canónica (AA:BB:CC:DD:EE:FF) las tablas con MACs en
+// minúsculas o con guiones, resuelve colisiones de clave primaria, deja
+// intactos los valores que no son MAC (como routerId:puerto en parent) y que
+// sus sentencias son idempotentes si vuelven a correr.
+func TestOpenMigratesLowercaseMACTables(t *testing.T) {
+	dataDir := t.TempDir()
+	first, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("primer db.Open: %v", err)
+	}
+
+	seed := []string{
+		// device_overrides: minúsculas, guiones y colisión (gana updated_at más reciente).
+		`INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, notify_offline, created_at, updated_at) VALUES
+			('aa:bb:cc:dd:ee:01', 'tv', 'TV Salón', 'tv', '', 0, 10, 10),
+			('aa-bb-cc-dd-ee-02', 'laptop', 'Portátil', 'ordenador', '', 0, 10, 10),
+			('aa:bb:cc:dd:ee:03', 'server', 'Nuevo', 'servidor', '', 1, 10, 200),
+			('AA:BB:CC:DD:EE:03', 'router', 'Viejo', 'router', '', 0, 10, 100)`,
+
+		// topology_overrides: MAC y parent MAC en minúsculas, colisión (gana
+		// updated_at), y valores que no son MAC con ':' y no deben tocarse: ids
+		// de router que parecen una MAC con guiones o 12 dígitos hex, un parent
+		// routerId:puerto y uno con ':' que no es hex.
+		`INSERT INTO topology_overrides (id, mac, kind, name, parent, enabled, created_at, updated_at) VALUES
+			('aa:bb:cc:00:00:01', 'aa:bb:cc:00:00:01', 'attach', 'vm1', 'c8:ff:bf:08:6f:ba', 1, 10, 10),
+			('aa-bb-cc-00-00-02', 'aa-bb-cc-00-00-02', 'attach', 'vm2', 'sw1:two-gigabitEthernet 1/0/21', 1, 10, 10),
+			('cafebabe1234', 'cafebabe1234', 'attach', 'vm4', 'ab-cd-ef-01-02-03', 1, 10, 10),
+			('zz-router', 'zz-router', 'attach', 'vm5', 'ab:cd:ef:gh:ij:kl', 1, 10, 10),
+			('aa:bb:cc:00:00:03', 'aa:bb:cc:00:00:03', 'switch', 'sw-viejo', NULL, 1, 10, 50),
+			('AA:BB:CC:00:00:03', 'AA:BB:CC:00:00:03', 'hypervisor', 'hv-nuevo', NULL, 1, 10, 150),
+			('g7615v2', 'g7615v2', 'attach', 'ont', 'gw:eth2', 1, 10, 10)`,
+
+		// client_bw_raw, client_bw_5m, client_bw_daily: minúsculas, guiones,
+		// colisión (sobrevive la fila ya canónica) y valor corrupto no-MAC ("19:21:68:11").
+		`INSERT INTO client_bw_raw (mac, router_id, ts, rx_bytes, tx_bytes, rx_bps, tx_bps) VALUES
+			('aa:bb:cc:dd:ee:01', 'gw', 1000, 100, 200, 800, 1600),
+			('aa-bb-cc-dd-ee-02', 'gw', 1000, 300, 400, 2400, 3200),
+			('aa:bb:cc:dd:ee:03', 'gw', 1000, 111, 222, 888, 1776),
+			('AA:BB:CC:DD:EE:03', 'gw', 1000, 500, 600, 4000, 4800),
+			('19:21:68:11', 'gw', 1000, 1, 2, 8, 16)`,
+		`INSERT INTO client_bw_5m (mac, router_id, bucket_ts, n, rx_bytes, tx_bytes) VALUES
+			('aa:bb:cc:dd:ee:01', 'gw', 300000, 1, 100, 200),
+			('aa:bb:cc:dd:ee:03', 'gw', 300000, 1, 111, 222),
+			('AA:BB:CC:DD:EE:03', 'gw', 300000, 2, 500, 600)`,
+		`INSERT INTO client_bw_daily (mac, router_id, date, n, rx_bytes, tx_bytes) VALUES
+			('aa-bb-cc-dd-ee-01', 'gw', '2026-11-20', 1, 100, 200),
+			('aa:bb:cc:dd:ee:03', 'gw', '2026-11-20', 1, 111, 222),
+			('AA:BB:CC:DD:EE:03', 'gw', '2026-11-20', 2, 500, 600)`,
+
+		// device_rack_profile y rack_mounts: perfil en minúsculas con montaje
+		// apuntándole por FK, y colisión de perfil minúsculas/mayúsculas.
+		`INSERT INTO racks (id, name, u_height) VALUES ('r1', 'Lab', 12)`,
+		`INSERT INTO device_rack_profile (mac, faceplate_id, u_height, col_span, color, ports_json) VALUES
+			('aa:bb:cc:00:01:01', 'server-2u', 2, 12, '#112233', '[{"id":"eth0","kind":"rj45","x":0.5,"y":0.5}]'),
+			('aa:bb:cc:00:01:02', 'blank-1u', 1, 12, '', '[]'),
+			('AA:BB:CC:00:01:02', 'switch', 2, 12, '#445566', '[]')`,
+		`INSERT INTO rack_mounts (id, rack_id, device_mac, faceplate_id, u_start, col_start) VALUES
+			('m1', 'r1', 'aa:bb:cc:00:01:01', 'server-2u', 1, 0),
+			('m2', 'r1', 'aa:bb:cc:00:01:02', 'switch', 3, 0),
+			('m3', 'r1', NULL, 'patch-panel-1u', 5, 0)`,
+	}
+	for _, q := range seed {
+		if _, err := first.Exec(q); err != nil {
+			t.Fatalf("sembrar datos de prueba: %v\nSQL: %s", err, q)
+		}
+	}
+	// Una base de datos de antes de la migración no lleva la marca.
+	if _, err := first.Exec(`DELETE FROM kv WHERE key = 'mac_upper_tables_migrated'`); err != nil {
+		t.Fatalf("borrar la marca: %v", err)
+	}
+	if err := first.Close(); err != nil {
+		t.Fatalf("cerrar primer db: %v", err)
+	}
+
+	// Dos aperturas seguidas: la segunda, sin la marca, vuelve a correr las
+	// sentencias sobre datos ya migrados y no debe cambiar nada.
+	for pass := 1; pass <= 2; pass++ {
+		d, err := db.Open(dataDir)
+		if err != nil {
+			t.Fatalf("db.Open pasada %d: %v", pass, err)
+		}
+
+		// 1) device_overrides
+		var name string
+		if err := d.QueryRow(`SELECT name FROM device_overrides WHERE mac = 'AA:BB:CC:DD:EE:01'`).Scan(&name); err != nil || name != "TV Salón" {
+			t.Fatalf("pasada %d: esperaba TV Salón en AA:BB:CC:DD:EE:01, got %q (err=%v)", pass, name, err)
+		}
+		if err := d.QueryRow(`SELECT name FROM device_overrides WHERE mac = 'AA:BB:CC:DD:EE:02'`).Scan(&name); err != nil || name != "Portátil" {
+			t.Fatalf("pasada %d: esperaba Portátil en AA:BB:CC:DD:EE:02, got %q (err=%v)", pass, name, err)
+		}
+		if err := d.QueryRow(`SELECT name FROM device_overrides WHERE mac = 'AA:BB:CC:DD:EE:03'`).Scan(&name); err != nil || name != "Nuevo" {
+			t.Fatalf("pasada %d: en colisión de device_overrides debía ganar el más reciente ('Nuevo'), got %q (err=%v)", pass, name, err)
+		}
+		var count int
+		if err := d.QueryRow(`SELECT COUNT(*) FROM device_overrides`).Scan(&count); err != nil || count != 3 {
+			t.Fatalf("pasada %d: esperaba 3 filas en device_overrides, got %d (err=%v)", pass, count, err)
+		}
+
+		// 2) topology_overrides
+		var mac, parent, kind string
+		if err := d.QueryRow(`SELECT mac, parent FROM topology_overrides WHERE id = 'AA:BB:CC:00:00:01'`).Scan(&mac, &parent); err != nil {
+			t.Fatalf("pasada %d: no se migró AA:BB:CC:00:00:01: %v", pass, err)
+		}
+		if mac != "AA:BB:CC:00:00:01" || parent != "C8:FF:BF:08:6F:BA" {
+			t.Fatalf("pasada %d: esperaba mac/parent en forma canónica, got %q / %q", pass, mac, parent)
+		}
+		for _, c := range []struct{ id, parent string }{
+			{"aa-bb-cc-00-00-02", "sw1:two-gigabitEthernet 1/0/21"},
+			{"cafebabe1234", "ab-cd-ef-01-02-03"},
+			{"zz-router", "ab:cd:ef:gh:ij:kl"},
+		} {
+			if err := d.QueryRow(`SELECT mac, parent FROM topology_overrides WHERE id = ?`, c.id).Scan(&mac, &parent); err != nil || mac != c.id || parent != c.parent {
+				t.Fatalf("pasada %d: el id de router %q y su parent %q no debían alterarse, got mac=%q parent=%q (err=%v)", pass, c.id, c.parent, mac, parent, err)
+			}
+		}
+		if err := d.QueryRow(`SELECT kind, name FROM topology_overrides WHERE id = 'AA:BB:CC:00:00:03'`).Scan(&kind, &name); err != nil || kind != "hypervisor" || name != "hv-nuevo" {
+			t.Fatalf("pasada %d: en colisión de topology_overrides debía ganar updated_at=150, got kind=%q name=%q (err=%v)", pass, kind, name, err)
+		}
+		if err := d.QueryRow(`SELECT mac, parent FROM topology_overrides WHERE id = 'g7615v2'`).Scan(&mac, &parent); err != nil || mac != "g7615v2" || parent != "gw:eth2" {
+			t.Fatalf("pasada %d: el target routerId no-MAC debía quedar intacto, got mac=%q parent=%q (err=%v)", pass, mac, parent, err)
+		}
+
+		// 3) client_bw_*
+		var rx int64
+		if err := d.QueryRow(`SELECT rx_bytes FROM client_bw_raw WHERE mac = 'AA:BB:CC:DD:EE:01' AND router_id = 'gw' AND ts = 1000`).Scan(&rx); err != nil || rx != 100 {
+			t.Fatalf("pasada %d: esperaba 100 rx_bytes en client_bw_raw AA:BB:CC:DD:EE:01, got %d (err=%v)", pass, rx, err)
+		}
+		if err := d.QueryRow(`SELECT rx_bytes FROM client_bw_raw WHERE mac = 'AA:BB:CC:DD:EE:02' AND router_id = 'gw' AND ts = 1000`).Scan(&rx); err != nil || rx != 300 {
+			t.Fatalf("pasada %d: esperaba 300 rx_bytes en client_bw_raw AA:BB:CC:DD:EE:02, got %d (err=%v)", pass, rx, err)
+		}
+		if err := d.QueryRow(`SELECT rx_bytes FROM client_bw_raw WHERE mac = 'AA:BB:CC:DD:EE:03' AND router_id = 'gw' AND ts = 1000`).Scan(&rx); err != nil || rx != 500 {
+			t.Fatalf("pasada %d: en colisión de client_bw_raw debía sobrevivir la fila mayúscula (500), got %d (err=%v)", pass, rx, err)
+		}
+		if err := d.QueryRow(`SELECT rx_bytes FROM client_bw_raw WHERE mac = '19:21:68:11'`).Scan(&rx); err != nil || rx != 1 {
+			t.Fatalf("pasada %d: la cadena de longitud != 17 no debía tocarse, got %d (err=%v)", pass, rx, err)
+		}
+		if err := d.QueryRow(`SELECT rx_bytes FROM client_bw_5m WHERE mac = 'AA:BB:CC:DD:EE:03' AND router_id = 'gw' AND bucket_ts = 300000`).Scan(&rx); err != nil || rx != 500 {
+			t.Fatalf("pasada %d: en colisión de client_bw_5m debía sobrevivir la fila mayúscula (500), got %d (err=%v)", pass, rx, err)
+		}
+		if err := d.QueryRow(`SELECT rx_bytes FROM client_bw_daily WHERE mac = 'AA:BB:CC:DD:EE:01' AND router_id = 'gw' AND date = '2026-11-20'`).Scan(&rx); err != nil || rx != 100 {
+			t.Fatalf("pasada %d: esperaba client_bw_daily AA:BB:CC:DD:EE:01 migrada, got %d (err=%v)", pass, rx, err)
+		}
+		if err := d.QueryRow(`SELECT rx_bytes FROM client_bw_daily WHERE mac = 'AA:BB:CC:DD:EE:03' AND router_id = 'gw' AND date = '2026-11-20'`).Scan(&rx); err != nil || rx != 500 {
+			t.Fatalf("pasada %d: en colisión de client_bw_daily debía sobrevivir la fila mayúscula (500), got %d (err=%v)", pass, rx, err)
+		}
+
+		// 4) device_rack_profile y rack_mounts (sin perder la FK por ON DELETE SET NULL)
+		var uHeight int
+		var faceplate string
+		if err := d.QueryRow(`SELECT m.device_mac, p.faceplate_id, p.u_height
+			FROM rack_mounts m JOIN device_rack_profile p ON p.mac = m.device_mac
+			WHERE m.id = 'm1'`).Scan(&mac, &faceplate, &uHeight); err != nil {
+			t.Fatalf("pasada %d: montaje m1 perdió su perfil tras migrar: %v", pass, err)
+		}
+		if mac != "AA:BB:CC:00:01:01" || faceplate != "server-2u" || uHeight != 2 {
+			t.Fatalf("pasada %d: m1 esperaba AA:BB:CC:00:01:01 server-2u 2U, got %s %s %dU", pass, mac, faceplate, uHeight)
+		}
+		if err := d.QueryRow(`SELECT m.device_mac, p.faceplate_id, p.u_height
+			FROM rack_mounts m JOIN device_rack_profile p ON p.mac = m.device_mac
+			WHERE m.id = 'm2'`).Scan(&mac, &faceplate, &uHeight); err != nil {
+			t.Fatalf("pasada %d: montaje m2 no cruzó con el perfil mayúscula superviviente: %v", pass, err)
+		}
+		if mac != "AA:BB:CC:00:01:02" || faceplate != "switch" || uHeight != 2 {
+			t.Fatalf("pasada %d: m2 esperaba AA:BB:CC:00:01:02 switch 2U, got %s %s %dU", pass, mac, faceplate, uHeight)
+		}
+		if err := d.QueryRow(`SELECT COUNT(*) FROM device_rack_profile`).Scan(&count); err != nil || count != 2 {
+			t.Fatalf("pasada %d: esperaba 2 perfiles canónicos en device_rack_profile, got %d (err=%v)", pass, count, err)
+		}
+
+		if err := d.QueryRow(`SELECT COUNT(*) FROM kv WHERE key = 'mac_upper_tables_migrated'`).Scan(&count); err != nil || count != 1 {
+			t.Fatalf("pasada %d: esperaba la marca de migración en kv, got %d (err=%v)", pass, count, err)
+		}
+		if _, err := d.Exec(`DELETE FROM kv WHERE key = 'mac_upper_tables_migrated'`); err != nil {
+			t.Fatalf("pasada %d: borrar la marca: %v", pass, err)
+		}
+
+		if err := d.Close(); err != nil {
+			t.Fatalf("cerrar db pasada %d: %v", pass, err)
+		}
+	}
+}
+
+// TestMACMigrationRunsOnce verifica que, con la marca puesta, los arranques
+// siguientes no vuelven a recorrer las tablas.
+func TestMACMigrationRunsOnce(t *testing.T) {
+	dataDir := t.TempDir()
+	first, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("primer db.Open: %v", err)
+	}
+	if _, err := first.Exec(`INSERT INTO client_bw_raw (mac, router_id, ts, rx_bytes, tx_bytes, rx_bps, tx_bps)
+		VALUES ('aa:bb:cc:dd:ee:01', 'gw', 1, 1, 1, 1, 1)`); err != nil {
+		t.Fatalf("sembrar: %v", err)
+	}
+	first.Close()
+
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("segundo db.Open: %v", err)
+	}
+	defer d.Close()
+	var mac string
+	if err := d.QueryRow(`SELECT mac FROM client_bw_raw`).Scan(&mac); err != nil || mac != "aa:bb:cc:dd:ee:01" {
+		t.Fatalf("con la marca puesta no debía migrar de nuevo, got %q (err=%v)", mac, err)
+	}
+}
+
+// TestMigrationLeavesMixedSeparatorsAlone: una cadena con separadores mezclados
+// ('-' y ':') no es una MAC para macaddr.Normalize, así que la migración no la
+// reescribe ni la usa para pisar el override real de la MAC canónica.
+func TestMigrationLeavesMixedSeparatorsAlone(t *testing.T) {
+	dataDir := t.TempDir()
+	first, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("primer db.Open: %v", err)
+	}
+
+	seed := []string{
+		`INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, notify_offline, created_at, updated_at) VALUES
+			('AA:BB:CC:DD:EE:01', 'tv', 'Real', 'tv', '', 0, 10, 100),
+			('aa-bb:cc-dd:ee-01', 'laptop', 'Separadores mezclados', 'ordenador', '', 0, 10, 200)`,
+		`INSERT INTO client_bw_raw (mac, router_id, ts, rx_bytes, tx_bytes, rx_bps, tx_bps)
+			VALUES ('aa-bb:cc-dd:ee-02', 'gw', 1000, 100, 200, 800, 1600)`,
+		`DELETE FROM kv WHERE key = 'mac_upper_tables_migrated'`,
+	}
+	for _, q := range seed {
+		if _, err := first.Exec(q); err != nil {
+			t.Fatalf("sembrar datos: %v\nSQL: %s", err, q)
+		}
+	}
+	if err := first.Close(); err != nil {
+		t.Fatalf("cerrar primer db: %v", err)
+	}
+
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("segundo db.Open: %v", err)
+	}
+	defer d.Close()
+
+	var name string
+	if err := d.QueryRow(`SELECT name FROM device_overrides WHERE mac = 'AA:BB:CC:DD:EE:01'`).Scan(&name); err != nil {
+		t.Fatalf("leer device_overrides: %v", err)
+	}
+	if name != "Real" {
+		t.Errorf("una cadena con separadores mezclados pisó el override real: esperaba %q, obtuve %q", "Real", name)
+	}
+	var bwMac string
+	if err := d.QueryRow(`SELECT mac FROM client_bw_raw WHERE router_id = 'gw' AND ts = 1000`).Scan(&bwMac); err != nil {
+		t.Fatalf("leer client_bw_raw: %v", err)
+	}
+	if bwMac != "aa-bb:cc-dd:ee-02" {
+		t.Errorf("client_bw_raw no debía reescribir una cadena con separadores mezclados: esperaba %q, obtuve %q", "aa-bb:cc-dd:ee-02", bwMac)
+	}
+}
+
+// TestMigrationTrimsTopologyParentMAC: main guardaba el parent tal cual
+// llegaba a POST /api/topology/overrides, con espacios incluidos; la migración
+// lo recorta y lo pasa a la forma canónica.
+func TestMigrationTrimsTopologyParentMAC(t *testing.T) {
+	dataDir := t.TempDir()
+	first, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("primer db.Open: %v", err)
+	}
+
+	seed := []string{
+		`INSERT INTO topology_overrides (id, mac, kind, name, parent, enabled, created_at, updated_at)
+			VALUES ('aa:bb:cc:00:00:01', 'aa:bb:cc:00:00:01', 'attach', 'vm1', ' c8:ff:bf:08:6f:ba ', 1, 10, 10)`,
+		// strings.TrimSpace también quita tabuladores y saltos de línea.
+		`INSERT INTO topology_overrides (id, mac, kind, name, parent, enabled, created_at, updated_at)
+			VALUES ('aa:bb:cc:00:00:02', 'aa:bb:cc:00:00:02', 'attach', 'vm2', char(9) || 'c8:ff:bf:08:6f:bb' || char(9), 1, 10, 10)`,
+		`INSERT INTO topology_overrides (id, mac, kind, name, parent, enabled, created_at, updated_at)
+			VALUES ('aa:bb:cc:00:00:03', 'aa:bb:cc:00:00:03', 'attach', 'vm3', char(13) || char(10) || 'c8:ff:bf:08:6f:bc' || char(10), 1, 10, 10)`,
+		`DELETE FROM kv WHERE key = 'mac_upper_tables_migrated'`,
+	}
+	for _, q := range seed {
+		if _, err := first.Exec(q); err != nil {
+			t.Fatalf("sembrar datos: %v", err)
+		}
+	}
+	if err := first.Close(); err != nil {
+		t.Fatalf("cerrar primer db: %v", err)
+	}
+
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("segundo db.Open: %v", err)
+	}
+	defer d.Close()
+
+	want := map[string]string{
+		"AA:BB:CC:00:00:01": "C8:FF:BF:08:6F:BA",
+		"AA:BB:CC:00:00:02": "C8:FF:BF:08:6F:BB",
+		"AA:BB:CC:00:00:03": "C8:FF:BF:08:6F:BC",
+	}
+	for id, wantParent := range want {
+		var parent string
+		if err := d.QueryRow(`SELECT parent FROM topology_overrides WHERE id = ?`, id).Scan(&parent); err != nil {
+			t.Fatalf("leer parent de %s: %v", id, err)
+		}
+		if parent != wantParent {
+			t.Errorf("%s: esperaba parent normalizado %s, obtuve %q", id, wantParent, parent)
+		}
+	}
+}

+ 5 - 1
server-go/internal/httpapi/agentstate.go

@@ -84,12 +84,16 @@ func NewStateRestorer(d *db.DB) func(*adapters.AgentRegistry) {
 			if err := json.Unmarshal([]byte(raw), &ps); err != nil || ps.Payload == nil {
 				continue
 			}
+			// Un estado guardado antes de que el push normalizara las MAC
+			// (#2134) puede traerlas en minúsculas o con guiones. Ingest no
+			// normaliza, así que se hace aquí, una vez, al restaurarlo.
+			normalizePayloadMACs(ps.Payload)
 			reg.Restore(slug, &adapters.AgentState{
 				Payload:   ps.Payload,
 				LastSeen:  time.Unix(ps.LastSeen, 0),
 				Version:   ps.Version,
 				Host:      ps.Host,
-				BridgeMAC: ps.BridgeMAC,
+				BridgeMAC: canonMAC(ps.BridgeMAC),
 			})
 		}
 	}

+ 39 - 0
server-go/internal/httpapi/agentstate_restore_macs_test.go

@@ -0,0 +1,39 @@
+package httpapi
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// Un estado persistido antes de #2134 con MAC en minúsculas y con guiones
+// vuelve canónico al restaurarlo: Ingest ya no normaliza, y sin esto los
+// overrides manuales no casaban hasta el siguiente push.
+func TestStateRestorerNormalizesMACs(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("open db: %v", err)
+	}
+	defer d.Close()
+	if _, err := d.Exec("INSERT INTO kv (key, value) VALUES (?, ?)", agentStateKey("sw1"),
+		`{"payload":{"router":"sw1","data":{"dhcp":{"leases":[{"mac":"aa-bb-cc-dd-ee-01","ip":"192.0.2.50"}]},"fdb":{"macs":{"aa:bb:cc:dd:ee:02":"lan1"}}}},"lastSeen":1,"version":"1.0.0","bridgeMAC":"aa-bb-cc-dd-ee-00"}`); err != nil {
+		t.Fatalf("sembrar estado: %v", err)
+	}
+
+	reg := adapters.NewAgentRegistry(0)
+	NewStateRestorer(d)(reg)
+	st := reg.Snapshot("sw1")
+	if st == nil || st.Payload == nil || st.Payload.Data.DHCP == nil || st.Payload.Data.FDB == nil {
+		t.Fatalf("esperaba el estado restaurado, obtuve %+v", st)
+	}
+	if got := st.Payload.Data.DHCP.Leases[0].MAC; got != "AA:BB:CC:DD:EE:01" {
+		t.Errorf("esperaba MAC de lease canónica, obtuve %q", got)
+	}
+	if _, ok := st.Payload.Data.FDB.MACs["AA:BB:CC:DD:EE:02"]; !ok || len(st.Payload.Data.FDB.MACs) != 1 {
+		t.Errorf("esperaba la clave FDB canónica, obtuve %v", st.Payload.Data.FDB.MACs)
+	}
+	if st.BridgeMAC != "AA:BB:CC:DD:EE:00" {
+		t.Errorf("esperaba BridgeMAC canónica, obtuve %q", st.BridgeMAC)
+	}
+}

+ 2 - 2
server-go/internal/httpapi/data.go

@@ -898,8 +898,8 @@ func (s *server) handleDeviceTraffic(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusServiceUnavailable, "unavailable")
 		return
 	}
-	mac := normalizeMAC(r.PathValue("mac"))
-	if len(mac) != len("aa:bb:cc:dd:ee:ff") {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}

+ 37 - 24
server-go/internal/httpapi/device_actions.go

@@ -14,6 +14,7 @@ import (
 	"strings"
 	"time"
 
+	"github.com/gnacho/netpulse/agent/macaddr"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
 )
 
@@ -215,13 +216,25 @@ func parseDhcpHosts(lines []string) []*dhcpHost {
 	return hosts
 }
 
+// uciMAC es la forma de una MAC canónica en el router: las secciones, nombres
+// y opciones UCI que escribe netpulse van en minúsculas, y así casan las reglas
+// ya existentes.
+func uciMAC(mac string) string {
+	return strings.ToLower(mac)
+}
+
 // findDhcpHost busca una sección host cuya MAC coincida (sin importar el
 // formato; admite varias MACs separadas por coma/espacio en una misma sección).
+// Una `list mac` sale de `uci show` como 'aa:…' 'bb:…' y uciValue solo quita
+// las comillas de fuera, así que también se corta por las comillas.
 func findDhcpHost(hosts []*dhcpHost, mac string) *dhcpHost {
-	macNorm := normalizeMAC(mac)
+	macNorm := macaddr.Normalize(mac)
+	if macNorm == "" {
+		return nil
+	}
 	for _, h := range hosts {
-		for _, m := range strings.FieldsFunc(h.MAC, func(r rune) bool { return r == ',' || r == ' ' }) {
-			if normalizeMAC(m) == macNorm {
+		for _, m := range strings.FieldsFunc(h.MAC, func(r rune) bool { return r == ',' || r == ' ' || r == '\'' || r == '"' }) {
+			if macaddr.Normalize(m) == macNorm {
 				return h
 			}
 		}
@@ -232,13 +245,13 @@ func findDhcpHost(hosts []*dhcpHost, mac string) *dhcpHost {
 // dhcpHostSection es el nombre de sección determinista para la reserva de una
 // MAC (uci set dhcp.np_host_<mac12>=host).
 func dhcpHostSection(mac string) string {
-	return "np_host_" + strings.ReplaceAll(mac, ":", "")
+	return "np_host_" + strings.ReplaceAll(uciMAC(mac), ":", "")
 }
 
 // handleDeviceReservationGet devuelve la reserva DHCP estática de un dispositivo.
 func (s *server) handleDeviceReservationGet(w http.ResponseWriter, r *http.Request) {
-	mac := normalizeMAC(r.PathValue("mac"))
-	if len(mac) != 17 {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
@@ -270,8 +283,8 @@ func (s *server) handleDeviceReservationGet(w http.ResponseWriter, r *http.Reque
 func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Request) {
 	// #2112: uci show + commit + restart del servicio en la unidad antes de responder.
 	setLongWriteDeadline(w, deviceActionWriteCeiling)
-	mac := normalizeMAC(r.PathValue("mac"))
-	if len(mac) != 17 {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
@@ -330,12 +343,12 @@ func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Reque
 		section := dhcpHostSection(mac)
 		name := body.Hostname
 		if name == "" {
-			name = mac
+			name = uciMAC(mac)
 		}
 		apply = append(apply,
 			fmt.Sprintf("uci set dhcp.%s=host", section),
 			uciSetCmd("dhcp", section, "name", name),
-			uciSetCmd("dhcp", section, "mac", mac),
+			uciSetCmd("dhcp", section, "mac", uciMAC(mac)),
 			uciSetCmd("dhcp", section, "ip", body.IP),
 		)
 		rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
@@ -370,8 +383,8 @@ func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Reque
 func (s *server) handleDeviceReservationHostnamePut(w http.ResponseWriter, r *http.Request) {
 	// #2112: uci show + commit + restart del servicio en la unidad antes de responder.
 	setLongWriteDeadline(w, deviceActionWriteCeiling)
-	mac := normalizeMAC(r.PathValue("mac"))
-	if len(mac) != 17 {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
@@ -442,7 +455,7 @@ func (s *server) handleDeviceReservationHostnamePut(w http.ResponseWriter, r *ht
 		apply = append(apply,
 			fmt.Sprintf("uci set dhcp.%s=host", section),
 			uciSetCmd("dhcp", section, "name", body.Hostname),
-			uciSetCmd("dhcp", section, "mac", mac),
+			uciSetCmd("dhcp", section, "mac", uciMAC(mac)),
 			uciSetCmd("dhcp", section, "ip", body.IP),
 		)
 		rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
@@ -487,8 +500,8 @@ func writeDevicePlan(w http.ResponseWriter, mac, host string, apply, rollback []
 func (s *server) handleDeviceReservationDelete(w http.ResponseWriter, r *http.Request) {
 	// #2112: uci show + commit + restart del servicio en la unidad antes de responder.
 	setLongWriteDeadline(w, deviceActionWriteCeiling)
-	mac := normalizeMAC(r.PathValue("mac"))
-	if len(mac) != 17 {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
@@ -594,12 +607,12 @@ func parseFirewallRules(lines []string) []*firewallRule {
 // blockRuleSection es el nombre de sección determinista para el bloqueo de una
 // MAC (uci set firewall.np_block_<mac12>=rule).
 func blockRuleSection(mac string) string {
-	return "np_block_" + strings.ReplaceAll(mac, ":", "")
+	return "np_block_" + strings.ReplaceAll(uciMAC(mac), ":", "")
 }
 
 // blockRuleName es el nombre legible de la regla (mostrado en LuCI).
 func blockRuleName(mac string) string {
-	return "np-block-" + strings.ReplaceAll(mac, ":", "")
+	return "np-block-" + strings.ReplaceAll(uciMAC(mac), ":", "")
 }
 
 // findBlockRule busca la regla de bloqueo de una MAC: por sección determinista
@@ -626,7 +639,7 @@ func blockRuleApply(section, mac string) []string {
 		fmt.Sprintf("uci set firewall.%s.src='lan'", section),
 		fmt.Sprintf("uci set firewall.%s.dest='*'", section),
 		fmt.Sprintf("uci set firewall.%s.target='DROP'", section),
-		uciSetCmd("firewall", section, "src_mac", mac),
+		uciSetCmd("firewall", section, "src_mac", uciMAC(mac)),
 	}
 }
 
@@ -636,8 +649,8 @@ func blockRuleRollback(section string) []string {
 
 // handleDeviceBlockGet indica si un dispositivo está bloqueado.
 func (s *server) handleDeviceBlockGet(w http.ResponseWriter, r *http.Request) {
-	mac := normalizeMAC(r.PathValue("mac"))
-	if len(mac) != 17 {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
@@ -665,8 +678,8 @@ func (s *server) handleDeviceBlockGet(w http.ResponseWriter, r *http.Request) {
 func (s *server) handleDeviceBlockPut(w http.ResponseWriter, r *http.Request) {
 	// #2112: uci show + commit + restart del servicio en la unidad antes de responder.
 	setLongWriteDeadline(w, deviceActionWriteCeiling)
-	mac := normalizeMAC(r.PathValue("mac"))
-	if len(mac) != 17 {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
@@ -721,8 +734,8 @@ func (s *server) handleDeviceBlockPut(w http.ResponseWriter, r *http.Request) {
 func (s *server) handleDeviceBlockDelete(w http.ResponseWriter, r *http.Request) {
 	// #2112: uci show + commit + restart del servicio en la unidad antes de responder.
 	setLongWriteDeadline(w, deviceActionWriteCeiling)
-	mac := normalizeMAC(r.PathValue("mac"))
-	if len(mac) != 17 {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}

+ 47 - 0
server-go/internal/httpapi/device_actions_multimac_test.go

@@ -0,0 +1,47 @@
+package httpapi
+
+import (
+	"strings"
+	"testing"
+)
+
+// TestFindDhcpHostMultiMACList comprueba que findDhcpHost reconoce una sección
+// host con `list mac` (varias MACs del mismo equipo). `uci show dhcp` la saca
+// como elementos entre comillas simples separados por espacio, y uciValue solo
+// quita las comillas de fuera.
+func TestFindDhcpHostMultiMACList(t *testing.T) {
+	// Salida real de `uci show dhcp` para una reserva con `list mac`
+	// (dos o tres interfaces del mismo equipo compartiendo IP).
+	raw := strings.Join([]string{
+		"dhcp.cfg0abc12=host",
+		"dhcp.cfg0abc12.name='portatil'",
+		"dhcp.cfg0abc12.mac='aa:bb:cc:00:00:02' 'aa:bb:cc:00:00:03' 'aa:bb:cc:00:00:04'",
+		"dhcp.cfg0abc12.ip='192.168.1.50'",
+	}, "\n")
+
+	hosts := parseDhcpHosts(strings.Split(raw, "\n"))
+	if len(hosts) != 1 {
+		t.Fatalf("esperaba 1 sección host, obtuve %d", len(hosts))
+	}
+
+	cases := []struct {
+		name string
+		mac  string
+	}{
+		{"primera MAC de la lista", "aa:bb:cc:00:00:02"},
+		{"MAC intermedia de la lista", "aa:bb:cc:00:00:03"},
+		{"última MAC de la lista", "aa:bb:cc:00:00:04"},
+		{"primera MAC en mayúsculas", "AA:BB:CC:00:00:02"},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			got := findDhcpHost(hosts, tc.mac)
+			if got == nil {
+				t.Fatalf("esperaba encontrar la sección cfg0abc12 para %s (h.MAC=%q), obtuve nil", tc.mac, hosts[0].MAC)
+			}
+			if got.Section != "cfg0abc12" || got.IP != "192.168.1.50" {
+				t.Errorf("esperaba cfg0abc12 / 192.168.1.50, obtuve %+v", got)
+			}
+		})
+	}
+}

+ 33 - 0
server-go/internal/httpapi/device_actions_test.go

@@ -896,3 +896,36 @@ func TestReservationSkipsAgentOnlyServingRouter(t *testing.T) {
 		t.Error("no debe intentar escribir en el router agent-only")
 	}
 }
+
+// El frontal manda la MAC en mayúsculas: en el router se escribe y se busca en
+// minúsculas, igual que las reglas ya existentes, y la respuesta va en la
+// forma canónica.
+func TestDeviceActionsUpperCaseMACUsesLowerCaseUCI(t *testing.T) {
+	const upper = "AA:BB:CC:DD:EE:FF"
+
+	ssh := newSSH(dhcpEmpty, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+upper+"/reservation", ts.cookie,
+		`{"ip":"192.168.1.60","hostname":"tv-salon"}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT reservation: %d", res.StatusCode)
+	}
+	body := decodeBody(t, res)
+	if body["mac"] != upper {
+		t.Errorf("mac en la respuesta = %v, esperaba %s", body["mac"], upper)
+	}
+	if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.mac='aa:bb:cc:dd:ee:ff'") {
+		t.Error("esperaba la sección y la mac del host en minúsculas")
+	}
+
+	ssh = newSSH(dhcpEmpty, fwBlocked)
+	ts = makeDeviceActionsTestServer(t, ssh)
+	res = deviceReq(t, "PUT", ts.URL, "/api/devices/"+upper+"/block", ts.cookie,
+		`{"router":"`+ts.apID+`"}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT block: %d", res.StatusCode)
+	}
+	if body := decodeBody(t, res); body["already"] != true {
+		t.Errorf("esperaba encontrar la regla existente en minúsculas, already = %v", body["already"])
+	}
+}

+ 5 - 26
server-go/internal/httpapi/device_overrides.go

@@ -12,34 +12,13 @@ package httpapi
 import (
 	"database/sql"
 	"net/http"
-	"regexp"
 	"strings"
 	"time"
 
+	"github.com/gnacho/netpulse/agent/macaddr"
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 )
 
-var macNormalizeRe = regexp.MustCompile(`[^0-9a-fA-F]`)
-
-// normalizeMAC devuelve MAC en minúsculas con ':' (la forma canónica del
-// server y de device_overrides).
-func normalizeMAC(mac string) string {
-	hex := macNormalizeRe.ReplaceAllString(mac, "")
-	hex = strings.ToLower(hex)
-	var out strings.Builder
-	for i := 0; i < len(hex); i += 2 {
-		if i > 0 {
-			out.WriteByte(':')
-		}
-		if i+2 <= len(hex) {
-			out.WriteString(hex[i : i+2])
-		} else {
-			out.WriteString(hex[i:])
-		}
-	}
-	return out.String()
-}
-
 // validateIcon comprueba que el icono enviado es uno de los permitidos por
 // DEVICE_ICONS del frontend. Lista cerrada para evitar inyección de clases.
 func validateIcon(icon string) bool {
@@ -78,8 +57,8 @@ const deviceNameMax = 64
 // handleDeviceOverridePut: campos opcionales {"icon","name","type"}; vacío
 // limpia, ausente no toca. Si los tres quedan vacíos la fila se borra.
 func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request) {
-	mac := normalizeMAC(r.PathValue("mac"))
-	if mac == "" || len(mac) != 17 {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
@@ -170,8 +149,8 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 
 // handleDeviceOverrideGet: devuelve el override actual de un dispositivo.
 func (s *server) handleDeviceOverrideGet(w http.ResponseWriter, r *http.Request) {
-	mac := normalizeMAC(r.PathValue("mac"))
-	if mac == "" || len(mac) != 17 {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}

+ 2 - 2
server-go/internal/httpapi/device_overrides_test.go

@@ -60,7 +60,7 @@ func TestDeviceOverrideNameTypeRoundtrip(t *testing.T) {
 
 func TestDeviceOverrideNotifyOffline(t *testing.T) {
 	s := newOverrideTestServer(t)
-	mac := "aa:bb:cc:dd:ee:ff"
+	mac := "AA:BB:CC:DD:EE:FF"
 
 	// Marcar opt-in: persiste el flag aunque icon/name/type queden vacíos.
 	if rec := doOverridePut(t, s, mac, `{"notifyOffline":true}`); rec.Code != 200 {
@@ -120,7 +120,7 @@ func TestDeviceOverridePartialPutPreservesOthers(t *testing.T) {
 
 func TestDeviceOverrideClearAllDeletesRow(t *testing.T) {
 	s := newOverrideTestServer(t)
-	mac := "aa:bb:cc:dd:ee:ff"
+	mac := "AA:BB:CC:DD:EE:FF"
 	doOverridePut(t, s, mac, `{"icon":"tv","name":"TV","type":"tv"}`)
 	rec := doOverridePut(t, s, mac, `{"icon":"","name":"","type":""}`)
 	if rec.Code != 200 {

+ 3 - 2
server-go/internal/httpapi/dns.go

@@ -10,6 +10,7 @@ import (
 	"net/http"
 	"time"
 
+	"github.com/gnacho/netpulse/agent/macaddr"
 	"github.com/gnacho/netpulse/server-go/internal/dnsactivity"
 )
 
@@ -50,8 +51,8 @@ func (s *server) handleDeviceDNS(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusServiceUnavailable, "unavailable")
 		return
 	}
-	mac := normalizeMAC(r.PathValue("mac"))
-	if len(mac) != len("aa:bb:cc:dd:ee:ff") {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}

+ 1 - 1
server-go/internal/httpapi/httpapi_test.go

@@ -1086,7 +1086,7 @@ func TestDeviceTrafficEndpoint(t *testing.T) {
 	}
 	now := time.Now()
 	err := srv.db.ClientBW.Insert(clientbw.Sample{
-		MAC: "aa:bb:cc:dd:ee:01", RouterID: "rt2", TS: now,
+		MAC: "AA:BB:CC:DD:EE:01", RouterID: "rt2", TS: now,
 		RxBytes: 1000, TxBytes: 2000, RxBps: 8000, TxBps: 16000,
 	})
 	if err != nil {

+ 4 - 7
server-go/internal/httpapi/onboarding.go

@@ -8,7 +8,8 @@ package httpapi
 
 import (
 	"net/http"
-	"strings"
+
+	"github.com/gnacho/netpulse/agent/macaddr"
 )
 
 // handleOnboardingDismiss silencia la alerta "dispositivo desconocido" para
@@ -23,15 +24,11 @@ func (s *server) handleOnboardingDismiss(w http.ResponseWriter, r *http.Request)
 		writeBodyError(w, st, "invalid_body", "body JSON inválido")
 		return
 	}
-	mac := normalizeMAC(body.MAC)
-	if len(mac) != 17 {
+	mac := macaddr.Normalize(body.MAC)
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
-	// La convención de memoria del adapter es MAC en MAYÚSCULAS (las MAC de
-	// los dispositivos viajan así); la clave kv debe coincidir para que la
-	// carga de arranque (unknownAlerted) case con trackUnknownDevices.
-	mac = strings.ToUpper(mac)
 	if s.db != nil {
 		_, _ = s.db.Exec("INSERT INTO kv (key, value) VALUES (?, '1') ON CONFLICT(key) DO NOTHING", "unknown_alerted:"+mac)
 	}

+ 3 - 3
server-go/internal/httpapi/presence.go

@@ -14,6 +14,7 @@ import (
 	"strings"
 	"time"
 
+	"github.com/gnacho/netpulse/agent/macaddr"
 	"github.com/gnacho/netpulse/server-go/internal/deviceevents"
 )
 
@@ -29,12 +30,11 @@ const historyLimitKey = "history.limit_enabled"
 // conexiones en las últimas 24 h. En demo devuelve una muestra sintética
 // determinista para que la UI sea explorable sin red real.
 func (s *server) handleDevicePresence(w http.ResponseWriter, r *http.Request) {
-	mac := normalizeMAC(r.PathValue("mac"))
-	if len(mac) != 17 {
+	mac := macaddr.Normalize(r.PathValue("mac"))
+	if mac == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
-	mac = strings.ToUpper(mac)
 	days := 7
 	if v := r.URL.Query().Get("days"); v != "" {
 		if n, err := strconv.Atoi(v); err == nil && n >= 1 && n <= 30 {

+ 7 - 5
server-go/internal/httpapi/racks.go

@@ -11,8 +11,8 @@ import (
 	"errors"
 	"log"
 	"net/http"
-	"strings"
 
+	"github.com/gnacho/netpulse/agent/macaddr"
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/rack"
@@ -41,14 +41,14 @@ func (s *server) buildRackHints(ctx context.Context, mounts []rack.MountRow) []r
 	mounted := map[string]bool{}
 	for _, m := range mounts {
 		if m.DeviceMAC != "" {
-			mounted[strings.ToLower(m.DeviceMAC)] = true
+			mounted[macaddr.NormalizeLenient(m.DeviceMAC)] = true
 		}
 	}
 	routerMAC := map[string]string{}
 	if ov := s.lastOv(); ov != nil {
 		for _, r := range ov.Routers {
 			if r.MAC != "" {
-				routerMAC[r.ID] = strings.ToLower(r.MAC)
+				routerMAC[r.ID] = macaddr.NormalizeLenient(r.MAC)
 			}
 		}
 	}
@@ -76,7 +76,7 @@ func (s *server) buildRackHints(ctx context.Context, mounts []rack.MountRow) []r
 		if !ok || from == "" {
 			continue
 		}
-		to := strings.ToLower(d.MAC)
+		to := macaddr.NormalizeLenient(d.MAC)
 		if !mounted[from] || !mounted[to] {
 			continue
 		}
@@ -408,7 +408,7 @@ func (s *server) handleRackProfilePut(w http.ResponseWriter, r *http.Request) {
 		writeBodyError(w, st, "invalid_body", "body JSON inválido")
 		return
 	}
-	d.MAC = r.PathValue("mac")
+	d.MAC = macaddr.Normalize(r.PathValue("mac"))
 	if err := rack.UpsertProfile(s.db.DB, dtoToProfile(d)); err != nil {
 		writeError(w, http.StatusBadRequest, "invalid_profile", err.Error())
 		return
@@ -423,6 +423,8 @@ func writeRackStoreError(w http.ResponseWriter, err error) {
 		writeError(w, http.StatusConflict, "conflict", err.Error())
 	case errors.Is(err, rack.ErrUnknownMount), errors.Is(err, sql.ErrNoRows):
 		writeError(w, http.StatusNotFound, "not_found", err.Error())
+	case errors.Is(err, rack.ErrInvalidMAC):
+		writeError(w, http.StatusBadRequest, "invalid_mac", err.Error())
 	case errors.Is(err, rack.ErrUnknownPort):
 		writeError(w, http.StatusBadRequest, "unknown_port", err.Error())
 	default:

+ 19 - 0
server-go/internal/httpapi/racks_error_test.go

@@ -0,0 +1,19 @@
+package httpapi
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/rack"
+)
+
+// TestWriteRackStoreErrorInvalidMAC comprueba que una MAC inválida en el layout
+// es un error del cliente (400 invalid_mac) y no un fallo de base de datos.
+func TestWriteRackStoreErrorInvalidMAC(t *testing.T) {
+	rec := httptest.NewRecorder()
+	writeRackStoreError(rec, rack.ErrInvalidMAC)
+	if rec.Code != http.StatusBadRequest {
+		t.Fatalf("esperaba 400, obtuve %d: %s", rec.Code, rec.Body.String())
+	}
+}

+ 10 - 8
server-go/internal/httpapi/topology_override.go

@@ -4,6 +4,7 @@ package httpapi
 
 import (
 	"net/http"
+	"strings"
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
@@ -37,6 +38,7 @@ func (s *server) handleTopologyOverrideCreate(w http.ResponseWriter, r *http.Req
 		writeBodyError(w, st, "invalid_body", "")
 		return
 	}
+	// MAC del device, o id de router para una unidad sin MAC de bridge (#1485).
 	body.MAC = adapters.NormalizeMAC(body.MAC)
 	if body.MAC == "" {
 		writeError(w, http.StatusBadRequest, "invalid_mac")
@@ -47,14 +49,14 @@ func (s *server) handleTopologyOverrideCreate(w http.ResponseWriter, r *http.Req
 		return
 	}
 	// parent (solo kind=attach) acepta: MAC de device (formato original),
-	// id de router, o "routerId:puerto" (issue #690). Solo se exige no vacío;
-	// la resolución final (adapters.applyTopologyOverrides) ignora formas
-	// que no casen con ningún device/router conocido.
-	if body.Kind == "attach" && adapters.NormalizeMAC(body.Parent) == "" {
-		writeError(w, http.StatusBadRequest, "attach_requires_parent")
-		return
-	}
-	if body.Kind != "attach" {
+	// id de router, o "routerId:puerto" (issue #690). La store lo normaliza
+	// (adapters.NormalizeParentRef) al guardarlo.
+	if body.Kind == "attach" {
+		if strings.TrimSpace(body.Parent) == "" {
+			writeError(w, http.StatusBadRequest, "attach_requires_parent")
+			return
+		}
+	} else {
 		body.Parent = ""
 	}
 	o, err := topooverride.Add(s.db.DB, topooverride.AddInput{

+ 89 - 0
server-go/internal/httpapi/topology_override_test.go

@@ -0,0 +1,89 @@
+package httpapi
+
+import (
+	"encoding/json"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+)
+
+// TestTopologyOverrideCreateNormalizesAndValidatesMAC comprueba que el alta de
+// overrides pasa MAC y parent con ':' a la forma canónica en mayúsculas,
+// conserva referencias routerId:puerto e ids de router (también los que
+// parecen una MAC con guiones) y rechaza un valor vacío con 400.
+func TestTopologyOverrideCreateNormalizesAndValidatesMAC(t *testing.T) {
+	s := newOverrideTestServer(t)
+
+	post := func(body string) *httptest.ResponseRecorder {
+		t.Helper()
+		req := httptest.NewRequest(http.MethodPost, "/api/topology/overrides", strings.NewReader(body))
+		req.Header.Set("Content-Type", "application/json")
+		rec := httptest.NewRecorder()
+		s.handleTopologyOverrideCreate(rec, req)
+		return rec
+	}
+
+	// MAC y parent con ':' en minúsculas → forma canónica en mayúsculas.
+	rec := post(`{"mac":"aa:bb:cc:dd:ee:01","kind":"attach","parent":" c8:ff:bf:08:6f:ba "}`)
+	if rec.Code != http.StatusCreated {
+		t.Fatalf("esperaba 201, got %d: %s", rec.Code, rec.Body.String())
+	}
+	var resp struct {
+		Override adapters.TopologyOverride `json:"override"`
+	}
+	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+		t.Fatalf("decodificar respuesta: %v", err)
+	}
+	if resp.Override.ID != "AA:BB:CC:DD:EE:01" || resp.Override.MAC != "AA:BB:CC:DD:EE:01" {
+		t.Errorf("esperaba id/mac en forma canónica AA:BB:CC:DD:EE:01, got id=%q mac=%q", resp.Override.ID, resp.Override.MAC)
+	}
+	if resp.Override.Parent != "C8:FF:BF:08:6F:BA" {
+		t.Errorf("esperaba parent en forma canónica C8:FF:BF:08:6F:BA, got %q", resp.Override.Parent)
+	}
+
+	// Parent routerId:puerto → se conserva tal cual.
+	rec = post(`{"mac":"aa:bb:cc:dd:ee:02","kind":"attach","parent":"sw1:two-gigabitEthernet 1/0/21"}`)
+	if rec.Code != http.StatusCreated {
+		t.Fatalf("esperaba 201 con parent router:puerto, got %d: %s", rec.Code, rec.Body.String())
+	}
+	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+		t.Fatalf("decodificar respuesta router:puerto: %v", err)
+	}
+	if resp.Override.Parent != "sw1:two-gigabitEthernet 1/0/21" {
+		t.Errorf("esperaba parent router:puerto intacto, got %q", resp.Override.Parent)
+	}
+
+	// Un id de router que parece una MAC con guiones sigue siendo un id de
+	// router, como target y como parent.
+	rec = post(`{"mac":"aa-bb-cc-dd-ee-03","kind":"attach","parent":"ab-cd-ef-01-02-03"}`)
+	if rec.Code != http.StatusCreated {
+		t.Fatalf("esperaba 201 con ids de router con guiones, got %d: %s", rec.Code, rec.Body.String())
+	}
+	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+		t.Fatalf("decodificar respuesta ids con guiones: %v", err)
+	}
+	if resp.Override.MAC != "aa-bb-cc-dd-ee-03" || resp.Override.Parent != "ab-cd-ef-01-02-03" {
+		t.Errorf("esperaba los ids de router intactos, got mac=%q parent=%q", resp.Override.MAC, resp.Override.Parent)
+	}
+
+	// Un id de router (#1485) no es una MAC: se guarda en minúsculas, con sus
+	// guiones intactos.
+	rec = post(`{"mac":" Mi-Router ","kind":"switch"}`)
+	if rec.Code != http.StatusCreated {
+		t.Fatalf("esperaba 201 con id de router, got %d: %s", rec.Code, rec.Body.String())
+	}
+	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+		t.Fatalf("decodificar respuesta id de router: %v", err)
+	}
+	if resp.Override.MAC != "mi-router" {
+		t.Errorf("esperaba id de router mi-router, got %q", resp.Override.MAC)
+	}
+
+	// Vacío → 400 invalid_mac.
+	if rec = post(`{"mac":"  ","kind":"hypervisor"}`); rec.Code != http.StatusBadRequest {
+		t.Errorf("MAC vacía: esperaba 400, got %d", rec.Code)
+	}
+}

+ 3 - 2
server-go/internal/rack/import.go

@@ -12,8 +12,9 @@ import (
 	"database/sql"
 	"fmt"
 	"sort"
-	"strings"
 	"time"
+
+	"github.com/gnacho/netpulse/agent/macaddr"
 )
 
 // CableHint candidato de cable. From/To son MACs normalizadas; ambos
@@ -42,7 +43,7 @@ func pairKey(a, b string) string {
 	return p[0] + "|" + p[1]
 }
 
-func normMac(m string) string { return strings.ToLower(strings.TrimSpace(m)) }
+func normMac(m string) string { return macaddr.NormalizeLenient(m) }
 
 // ImportCables crea cables para los hints cuyos extremos están montados.
 // Elección de puerto en dos niveles: primero uno libre cuyo tipo case con el

+ 5 - 5
server-go/internal/rack/import_test.go

@@ -11,9 +11,9 @@ func escenarioImport(t *testing.T, db *sql.DB) (MountRow, MountRow, MountRow) {
 	t.Helper()
 	rack := createTestRack(t, db)
 
-	sw := "aa:bb:cc:00:01:00"
-	s1 := "aa:bb:cc:00:01:01"
-	s2 := "aa:bb:cc:00:01:02"
+	sw := "AA:BB:CC:00:01:00"
+	s1 := "AA:BB:CC:00:01:01"
+	s2 := "AA:BB:CC:00:01:02"
 	if err := UpsertProfile(db, DeviceProfile{MAC: sw, FaceplateID: "switch", UHeight: 1, ColSpan: 12, Ports: []Port{
 		{ID: "lan1", Kind: PortRJ45}, {ID: "lan2", Kind: PortRJ45}, {ID: "sfp1", Kind: PortSFPPlus},
 	}}); err != nil {
@@ -88,7 +88,7 @@ func TestImportCablesNoFreePortAndUnmounted(t *testing.T) {
 	sw, _, _ := escenarioImport(t, db)
 
 	// s3: un solo puerto, montado y agotado con un cable manual al switch.
-	s3 := "aa:bb:cc:00:01:03"
+	s3 := "AA:BB:CC:00:01:03"
 	if err := UpsertProfile(db, DeviceProfile{MAC: s3, UHeight: 1, ColSpan: 12, Ports: []Port{{ID: "eth0", Kind: PortRJ45}}}); err != nil {
 		t.Fatalf("UpsertProfile s3: %v", err)
 	}
@@ -100,7 +100,7 @@ func TestImportCablesNoFreePortAndUnmounted(t *testing.T) {
 	if err := SaveLayout(db, LayoutChange{RackID: rackID, Upsert: []Mount{{DeviceMAC: s3, UStart: 4, ColStart: 0}}}); err != nil {
 		t.Fatalf("SaveLayout s3: %v", err)
 	}
-	mS1 := mustMount(t, db, "aa:bb:cc:00:01:01")
+	mS1 := mustMount(t, db, "AA:BB:CC:00:01:01")
 	mS3 := mustMount(t, db, s3)
 	// Agota el único puerto de s3 CONTRA OTRO PAR (s1): el par s3<->sw
 	// queda sin cable, pero s3 no tiene puerto libre -> NoFreePort.

+ 11 - 0
server-go/internal/rack/store.go

@@ -14,6 +14,8 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
+
+	"github.com/gnacho/netpulse/agent/macaddr"
 )
 
 // ErrOverlap indica que el estado final del layout tiene dos montajes
@@ -26,6 +28,9 @@ var ErrPortBusy = errors.New("rack: port has no capacity for another cable")
 // ErrUnknownMount / ErrUnknownPort referencian montajes o puertos inexistentes.
 var ErrUnknownMount = errors.New("rack: montaje inexistente")
 
+// ErrInvalidMAC indica que un montaje trae una device_mac que no es una MAC.
+var ErrInvalidMAC = errors.New("rack: invalid device MAC")
+
 // ErrUnknownPort indica un puerto que el dispositivo no declara en su perfil.
 var ErrUnknownPort = errors.New("rack: port not declared by the device")
 
@@ -145,6 +150,7 @@ func ListProfiles(db *sql.DB) ([]DeviceProfile, error) {
 
 // GetProfile devuelve el perfil de una MAC; sql.ErrNoRows si no existe.
 func GetProfile(db *sql.DB, mac string) (DeviceProfile, error) {
+	mac = macaddr.Normalize(mac)
 	var p DeviceProfile
 	var ports string
 	err := db.QueryRow(`SELECT mac, faceplate_id, u_height, col_span, color, ports_json FROM device_rack_profile WHERE mac = ?`, mac).
@@ -158,6 +164,7 @@ func GetProfile(db *sql.DB, mac string) (DeviceProfile, error) {
 
 // UpsertProfile crea o actualiza el modelo físico del dispositivo.
 func UpsertProfile(db *sql.DB, p DeviceProfile) error {
+	p.MAC = macaddr.Normalize(p.MAC)
 	if p.MAC == "" {
 		return fmt.Errorf("rack: mac requerida")
 	}
@@ -309,6 +316,10 @@ func SaveLayout(db *sql.DB, change LayoutChange) error {
 			m.PortVisibility = "auto"
 		}
 		if m.DeviceMAC != "" {
+			m.DeviceMAC = macaddr.Normalize(m.DeviceMAC)
+			if m.DeviceMAC == "" {
+				return ErrInvalidMAC
+			}
 			// Perfil por defecto si el dispositivo aún no tiene: la FK lo exige.
 			if _, err := tx.Exec(`INSERT INTO device_rack_profile (mac) VALUES (?) ON CONFLICT(mac) DO NOTHING`, m.DeviceMAC); err != nil {
 				return err

+ 55 - 2
server-go/internal/rack/store_test.go

@@ -207,8 +207,8 @@ func TestCablesCapacityAndCascade(t *testing.T) {
 	rack := createTestRack(t, db)
 
 	// Dos switches con perfil con puertos sembrados.
-	sw1 := "aa:bb:cc:00:00:01"
-	sw2 := "aa:bb:cc:00:00:02"
+	sw1 := "AA:BB:CC:00:00:01"
+	sw2 := "AA:BB:CC:00:00:02"
 	for i, mac := range []string{sw1, sw2} {
 		if err := UpsertProfile(db, DeviceProfile{MAC: mac, UHeight: 1, ColSpan: 12,
 			Ports: []Port{{ID: "eth0", Kind: PortRJ45}, {ID: "eth1", Kind: PortRJ45}}}); err != nil {
@@ -284,3 +284,56 @@ func TestCablesCapacityAndCascade(t *testing.T) {
 		t.Fatalf("mounts huérfanos tras DeleteRack: %d", len(rows))
 	}
 }
+
+// TestSaveLayoutAndProfileJoinAcrossCases comprueba que guardar un perfil y un
+// montaje con distinto formato/caja de MAC normaliza ambos a la forma canónica
+// sin duplicar filas en device_rack_profile ni perder el JOIN de la huella.
+func TestSaveLayoutAndProfileJoinAcrossCases(t *testing.T) {
+	db := openTestDB(t)
+	rack := createTestRack(t, db)
+
+	if err := UpsertProfile(db, DeviceProfile{
+		MAC: "aa:bb:cc:dd:ee:01", FaceplateID: "server-2u", UHeight: 2, ColSpan: 6,
+	}); err != nil {
+		t.Fatalf("UpsertProfile: %v", err)
+	}
+	if err := SaveLayout(db, LayoutChange{
+		RackID: rack.ID,
+		Upsert: []Mount{{DeviceMAC: "AA-BB-CC-DD-EE-01", UStart: 1, ColStart: 0}},
+	}); err != nil {
+		t.Fatalf("SaveLayout: %v", err)
+	}
+
+	mounts, err := ListMountRows(db)
+	if err != nil || len(mounts) != 1 {
+		t.Fatalf("ListMountRows: len=%d err=%v", len(mounts), err)
+	}
+	if mounts[0].DeviceMAC != "AA:BB:CC:DD:EE:01" {
+		t.Errorf("esperaba DeviceMAC en forma canónica AA:BB:CC:DD:EE:01, got %q", mounts[0].DeviceMAC)
+	}
+	if mounts[0].UHeight != 2 || mounts[0].ColSpan != 6 {
+		t.Errorf("el montaje no cruzó con el perfil 2Ux6: got %dUx%d", mounts[0].UHeight, mounts[0].ColSpan)
+	}
+
+	profiles, err := ListProfiles(db)
+	if err != nil || len(profiles) != 1 {
+		t.Fatalf("esperaba 1 único perfil sin duplicado por defecto, got %d (err=%v)", len(profiles), err)
+	}
+	if profiles[0].MAC != "AA:BB:CC:DD:EE:01" || profiles[0].UHeight != 2 {
+		t.Errorf("perfil inesperado: %+v", profiles[0])
+	}
+}
+
+// TestSaveLayoutRejectsInvalidMAC comprueba que un montaje con una device_mac
+// que no es una MAC devuelve ErrInvalidMAC (el handler lo traduce a 400).
+func TestSaveLayoutRejectsInvalidMAC(t *testing.T) {
+	db := openTestDB(t)
+	rack := createTestRack(t, db)
+	err := SaveLayout(db, LayoutChange{
+		RackID: rack.ID,
+		Upsert: []Mount{{DeviceMAC: "no-es-una-mac", UStart: 1, ColStart: 0}},
+	})
+	if !errors.Is(err, ErrInvalidMAC) {
+		t.Fatalf("esperaba ErrInvalidMAC, obtuve %v", err)
+	}
+}

+ 1 - 1
server-go/internal/rack/types.go

@@ -66,7 +66,7 @@ type Port struct {
 }
 
 // DeviceProfile es el modelo físico compartido del dispositivo: la misma
-// cara frontal en todos los racks. Clave: MAC normalizada (minúsculas, ':').
+// cara frontal en todos los racks. Clave: MAC normalizada (mayúsculas, ':').
 type DeviceProfile struct {
 	MAC         string `json:"mac"`
 	FaceplateID string `json:"faceplateId"`

+ 5 - 2
server-go/internal/topooverride/topooverride.go

@@ -49,11 +49,12 @@ type AddInput struct {
 func Add(db *sql.DB, in AddInput) (adapters.TopologyOverride, error) {
 	now := time.Now().UnixMilli()
 	mac := adapters.NormalizeMAC(in.MAC)
+	parent := adapters.NormalizeParentRef(in.Parent)
 	_, err := db.Exec(
 		`INSERT INTO topology_overrides (id, mac, kind, name, parent, enabled, created_at, updated_at)
 		 VALUES (?, ?, ?, NULLIF(?, ''), NULLIF(?, ''), 1, ?, ?)
 		 ON CONFLICT(id) DO UPDATE SET kind=excluded.kind, name=excluded.name, parent=excluded.parent, updated_at=excluded.updated_at`,
-		mac, mac, in.Kind, in.Name, in.Parent, now, now)
+		mac, mac, in.Kind, in.Name, parent, now, now)
 	if err != nil {
 		return adapters.TopologyOverride{}, err
 	}
@@ -77,6 +78,7 @@ type UpdateInput struct {
 // Update actualiza un override por id (mac). Devuelve la fila o false si no
 // existe.
 func Update(db *sql.DB, id string, in UpdateInput) (adapters.TopologyOverride, bool) {
+	id = adapters.NormalizeMAC(id)
 	now := time.Now().UnixMilli()
 	sets := []string{"updated_at = ?"}
 	args := []any{now}
@@ -90,7 +92,7 @@ func Update(db *sql.DB, id string, in UpdateInput) (adapters.TopologyOverride, b
 	}
 	if in.Parent != nil {
 		sets = append(sets, "parent = NULLIF(?, '')")
-		args = append(args, *in.Parent)
+		args = append(args, adapters.NormalizeParentRef(*in.Parent))
 	}
 	if in.Enabled != nil {
 		en := 0
@@ -119,6 +121,7 @@ func Update(db *sql.DB, id string, in UpdateInput) (adapters.TopologyOverride, b
 
 // Remove borra por id (mac); true si borró (changes > 0).
 func Remove(db *sql.DB, id string) bool {
+	id = adapters.NormalizeMAC(id)
 	res, err := db.Exec("DELETE FROM topology_overrides WHERE id = ?", id)
 	if err != nil {
 		return false

+ 1 - 1
server-go/internal/topooverride/topooverride_test.go

@@ -25,7 +25,7 @@ func TestStoreCRUD(t *testing.T) {
 	if err != nil {
 		t.Fatalf("Add: %v", err)
 	}
-	if o.ID != "c8:ff:bf:08:6f:ba" {
+	if o.ID != "C8:FF:BF:08:6F:BA" {
 		t.Errorf("id debe ser MAC normalizada, got %q", o.ID)
 	}
 	if !o.Enabled {