Bläddra i källkod

fix(httpapi): validate and normalize MACs on usteer, links and impostor (#2244)

The usteer kick only upper-cased the MAC, so a hyphenated or separator-free value never matched and returned 404 or invalid input. Device links accepted any non-empty string as a MAC. Both use macaddr.Normalize now and answer invalid_mac when the value is not one.

Co-authored-by: Mike Grupenhoff <2231096+mgrupenhoff@users.noreply.github.com>
Mike Grupenhoff 2 dagar sedan
förälder
incheckning
9bfffbbfe0

+ 8 - 5
server-go/internal/adapters/impostor.go

@@ -25,6 +25,7 @@ import (
 	"strings"
 	"time"
 
+	"github.com/gnacho/netpulse/agent/macaddr"
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
 )
 
@@ -247,11 +248,10 @@ func (l *Live) ImpostorApproved() []string {
 // no forma parte de la flota NetPulse). Persiste en kv y, si hay una alerta
 // de impostor activa para él, la resuelve al momento.
 func (l *Live) ApproveImpostorBssid(bssid string) error {
-	mac, err := net.ParseMAC(strings.TrimSpace(bssid))
-	if err != nil {
-		return fmt.Errorf("invalid bssid %q: %w", bssid, err)
+	norm := macaddr.Normalize(bssid)
+	if norm == "" {
+		return fmt.Errorf("invalid bssid %q", bssid)
 	}
-	norm := strings.ToUpper(mac.String())
 	l.mu.Lock()
 	defer l.mu.Unlock()
 	l.impostorAllow[norm] = true
@@ -267,7 +267,10 @@ func (l *Live) ApproveImpostorBssid(bssid string) error {
 // el BSSID sigue visible, la regla vuelve a alertar en la próxima evaluación
 // (con la confirmación anti-transitorio de siempre).
 func (l *Live) RevokeImpostorBssid(bssid string) {
-	norm := strings.ToUpper(strings.TrimSpace(bssid))
+	norm := macaddr.Normalize(bssid)
+	if norm == "" {
+		return
+	}
 	l.mu.Lock()
 	defer l.mu.Unlock()
 	delete(l.impostorAllow, norm)

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

@@ -370,3 +370,37 @@ func TestImpostorRuleDisableResolvesActive(t *testing.T) {
 		t.Fatalf("re-activar debe re-alertar con evidencia vigente; alertas: %d", len(got))
 	}
 }
+
+func TestImpostorApproveAndRevokeMACNormalization(t *testing.T) {
+	t.Run("revocar con guiones quita el BSSID aprobado con guiones", func(t *testing.T) {
+		l, _ := newImpostorLive(t)
+		if err := l.ApproveImpostorBssid("02-00-00-00-00-aa"); err != nil {
+			t.Fatalf("ApproveImpostorBssid con guiones falló: %v", err)
+		}
+		l.RevokeImpostorBssid("02-00-00-00-00-aa")
+		if got := l.ImpostorApproved(); len(got) != 0 {
+			t.Fatalf("tras revocar con guiones, la lista aprobada debe quedar vacía; obtuve %v", got)
+		}
+	})
+
+	t.Run("revocar con 12 hex quita el BSSID aprobado con 12 hex", func(t *testing.T) {
+		l, _ := newImpostorLive(t)
+		if err := l.ApproveImpostorBssid("0200000000bb"); err != nil {
+			t.Fatalf("ApproveImpostorBssid con 12 hex falló: %v", err)
+		}
+		l.RevokeImpostorBssid("0200000000bb")
+		if got := l.ImpostorApproved(); len(got) != 0 {
+			t.Fatalf("tras revocar con 12 hex, la lista aprobada debe quedar vacía; obtuve %v", got)
+		}
+	})
+
+	t.Run("aprobar rechaza EUI-64 de 8 bytes y Cisco con puntos", func(t *testing.T) {
+		l, _ := newImpostorLive(t)
+		if err := l.ApproveImpostorBssid("02:00:00:00:00:00:00:01"); err == nil {
+			t.Errorf("ApproveImpostorBssid aceptó EUI-64 de 8 bytes; esperaba error")
+		}
+		if err := l.ApproveImpostorBssid("0200.0000.0001"); err == nil {
+			t.Errorf("ApproveImpostorBssid aceptó formato Cisco con puntos; esperaba error")
+		}
+	})
+}

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

@@ -5920,8 +5920,8 @@ type sshRunner interface {
 // cada uno hasta que un intento tenga éxito. Solo devuelve error cuando el
 // cliente no está en ningún router o cuando todos los intentos fallan.
 func (l *Live) KickUsteerClient(ctx context.Context, mac string) error {
-	target := strings.ToUpper(strings.TrimSpace(mac))
-	if target == "" || !validMAC(target) {
+	target := macaddr.Normalize(mac)
+	if target == "" {
 		return fmt.Errorf("invalid MAC")
 	}
 	l.mu.Lock()
@@ -5932,6 +5932,10 @@ func (l *Live) KickUsteerClient(ctx context.Context, mac string) error {
 }
 
 func kickUsteerClient(target string, routers []RouterConfig, runner sshRunner) error {
+	target = macaddr.Normalize(target)
+	if target == "" {
+		return fmt.Errorf("invalid MAC")
+	}
 	var failures []string
 
 	for _, cfg := range routers {
@@ -5976,12 +5980,6 @@ func kickUsteerClient(target string, routers []RouterConfig, runner sshRunner) e
 	return fmt.Errorf("client not found")
 }
 
-// validMAC acepta MAC con separadores ':' o '-'. Exige 17 caracteres (con
-// separador) porque el llamador pasa target tal cual a usteer sin insertar ':'.
-func validMAC(s string) bool {
-	return macaddr.NormalizeSeparated(s) != ""
-}
-
 // buildUsteerAP construye un UsteerAP desde una entrada cruda de local_info.
 // Band se deriva de freq (>= 5000 MHz → 5 GHz). Función pura para testear.
 func buildUsteerAP(iface string, raw usteerAPRaw, hostname string, local bool) UsteerAP {

+ 37 - 0
server-go/internal/adapters/live_kick_test.go

@@ -1,6 +1,7 @@
 package adapters
 
 import (
+	"context"
 	"errors"
 	"fmt"
 	"testing"
@@ -115,3 +116,39 @@ func TestKickUsteerClient_ConnectedClientsFails(t *testing.T) {
 		t.Fatalf("expected 3 calls, got %d", len(runner.calls))
 	}
 }
+
+func TestKickUsteerClient_HyphenatedAndBareMAC(t *testing.T) {
+	t.Run("MAC con guiones encuentra al cliente conectado", func(t *testing.T) {
+		runner := &fakeKickRunner{
+			responses: map[string]string{
+				"192.0.2.2|ubus call usteer connected_clients": `{"hostapd.phy1-ap0":{"02:00:00:00:00:aa":{"signal":-52}}}`,
+				fmt.Sprintf("192.0.2.2|ubus call hostapd.phy1-ap0 del_client '%s'", `{"addr":"02:00:00:00:00:AA","reason":5,"deauth":true,"ban_time":120000}`): "",
+			},
+		}
+		routers := []RouterConfig{{ID: "ap1", Name: "ap1", Host: "192.0.2.2"}}
+		if err := kickUsteerClient("02-00-00-00-00-aa", routers, runner); err != nil {
+			t.Fatalf("expulsar MAC con guiones falló: %v", err)
+		}
+	})
+
+	t.Run("MAC de 12 hex sin separador encuentra al cliente conectado", func(t *testing.T) {
+		runner := &fakeKickRunner{
+			responses: map[string]string{
+				"192.0.2.2|ubus call usteer connected_clients": `{"hostapd.phy1-ap0":{"02:00:00:00:00:aa":{"signal":-52}}}`,
+				fmt.Sprintf("192.0.2.2|ubus call hostapd.phy1-ap0 del_client '%s'", `{"addr":"02:00:00:00:00:AA","reason":5,"deauth":true,"ban_time":120000}`): "",
+			},
+		}
+		routers := []RouterConfig{{ID: "ap1", Name: "ap1", Host: "192.0.2.2"}}
+		if err := kickUsteerClient("0200000000aa", routers, runner); err != nil {
+			t.Fatalf("expulsar MAC de 12 hex sin separador falló: %v", err)
+		}
+	})
+
+	t.Run("KickUsteerClient acepta MAC de 12 hex sin separador", func(t *testing.T) {
+		l := &Live{}
+		err := l.KickUsteerClient(context.Background(), "0200000000aa")
+		if err != nil && err.Error() == "invalid MAC" {
+			t.Fatalf("KickUsteerClient rechazó MAC de 12 hex sin separador con %q", err)
+		}
+	})
+}

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

@@ -711,16 +711,12 @@ func (s *server) handleUsteer(w http.ResponseWriter, r *http.Request) {
 // handleUsteerKick: POST /api/usteer/{mac}/kick - expulsa un cliente de su AP
 // usteer actual para forzar la reconexión a otro AP.
 func (s *server) handleUsteerKick(w http.ResponseWriter, r *http.Request) {
-	mac := r.PathValue("mac")
+	mac := macaddr.Normalize(r.PathValue("mac"))
 	if mac == "" {
-		writeError(w, http.StatusBadRequest, "invalid_input", "mac is required")
+		writeError(w, http.StatusBadRequest, "invalid_mac", "invalid MAC")
 		return
 	}
 	if err := s.adapter.KickUsteerClient(r.Context(), mac); err != nil {
-		if err.Error() == "invalid MAC" {
-			writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
-			return
-		}
 		if strings.Contains(err.Error(), "client not found") {
 			writeError(w, http.StatusNotFound, "not_found", err.Error())
 			return

+ 67 - 0
server-go/internal/httpapi/data_internal_test.go

@@ -4,9 +4,13 @@
 package httpapi
 
 import (
+	"net/http"
+	"net/http/httptest"
+	"strings"
 	"testing"
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/db"
 )
 
 // TestEnrichOverviewPlanFromContract: sin plan pero con contrato → plan
@@ -64,3 +68,66 @@ func TestEnrichOverviewPlanSinContrato(t *testing.T) {
 		t.Fatalf("plan = %q, esperado sin cambios", out.WAN.Plan)
 	}
 }
+
+// TestHandleUsteerKickRejectsInvalidMAC verifica que POST /api/usteer/{mac}/kick
+// valida la MAC en la frontera HTTP y devuelve 400 invalid_mac tanto en Demo
+// como en Live.
+func TestHandleUsteerKickRejectsInvalidMAC(t *testing.T) {
+	modes := []struct {
+		name    string
+		adapter adapters.Snapshotter
+	}{
+		{"demo", adapters.NewDemo()},
+		{"live", &adapters.Live{}},
+	}
+	cases := []struct {
+		name string
+		raw  string
+	}{
+		{"MAC vacía", ""},
+		{"MAC mal formada", "no-es-mac"},
+	}
+	for _, m := range modes {
+		s := &server{adapter: m.adapter}
+		for _, tc := range cases {
+			t.Run(m.name+"/"+tc.name, func(t *testing.T) {
+				req := httptest.NewRequest(http.MethodPost, "/api/usteer/"+tc.raw+"/kick", nil)
+				req.SetPathValue("mac", tc.raw)
+				rec := httptest.NewRecorder()
+				s.handleUsteerKick(rec, req)
+				if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "invalid_mac") {
+					t.Fatalf("modo=%s mac=%q: esperaba 400 invalid_mac, obtuve %d: %s", m.name, tc.raw, rec.Code, rec.Body.String())
+				}
+			})
+		}
+	}
+}
+
+// TestHandleAlertsImpostorApproveRejectsNonEthernet verifica que aprobar un
+// BSSID con formato EUI-64 o Cisco con puntos se rechaza conservando el código
+// HTTP 400 invalid_input.
+func TestHandleAlertsImpostorApproveRejectsNonEthernet(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	s := &server{adapter: adapters.NewLive(nil, d, nil, nil), db: d}
+
+	for _, tc := range []struct {
+		name  string
+		bssid string
+	}{
+		{"EUI-64 de 8 bytes", "02:00:00:00:00:00:00:01"},
+		{"Cisco con puntos", "0200.0000.0001"},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			req := httptest.NewRequest(http.MethodPost, "/api/alerts/impostor-approve", strings.NewReader(`{"bssid":"`+tc.bssid+`"}`))
+			rec := httptest.NewRecorder()
+			s.handleAlertsImpostorApprove(rec, req)
+			if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "invalid_input") {
+				t.Fatalf("bssid=%q: esperaba 400 invalid_input, obtuve %d: %s", tc.bssid, rec.Code, rec.Body.String())
+			}
+		})
+	}
+}

+ 10 - 4
server-go/internal/httpapi/device_links.go

@@ -7,6 +7,8 @@ package httpapi
 import (
 	"net/http"
 	"strings"
+
+	"github.com/gnacho/netpulse/agent/macaddr"
 )
 
 // handleDeviceLinkPut: body {"target": "<mac>"} — enlaza la MAC {mac} como
@@ -21,10 +23,14 @@ func (s *server) handleDeviceLinkPut(w http.ResponseWriter, r *http.Request) {
 		writeBodyError(w, st, "invalid_body", "body JSON inválido")
 		return
 	}
-	alias := normalizeMACKey(r.PathValue("mac"))
-	target := normalizeMACKey(body.Target)
-	if alias == "" || target == "" {
-		writeError(w, http.StatusBadRequest, "invalid_input", "missing mac")
+	alias := macaddr.Normalize(r.PathValue("mac"))
+	if alias == "" {
+		writeError(w, http.StatusBadRequest, "invalid_mac", "invalid mac")
+		return
+	}
+	target := macaddr.Normalize(body.Target)
+	if target == "" {
+		writeError(w, http.StatusBadRequest, "invalid_mac", "invalid target mac")
 		return
 	}
 	if alias == target {

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

@@ -207,9 +207,11 @@ func (s *server) handleDeviceDelete(w http.ResponseWriter, r *http.Request) {
 	// #1278: lápida. Sin ella, la siguiente fuente que reporte la MAC como
 	// online (una entrada cacheada del AP, un colector) la re-daba de alta y
 	// el borrado "no funcionaba".
-	if err := s.db.AddDeletedClient(mac); err != nil {
-		writeError(w, http.StatusInternalServerError, "storage_error", "")
-		return
+	if norm := macaddr.Normalize(raw); norm != "" {
+		if err := s.db.AddDeletedClient(norm); err != nil {
+			writeError(w, http.StatusInternalServerError, "storage_error", "")
+			return
+		}
 	}
 	if n, _ := res.RowsAffected(); n == 0 {
 		writeError(w, http.StatusNotFound, "not_found", "")

+ 94 - 0
server-go/internal/httpapi/device_overrides_test.go

@@ -257,3 +257,97 @@ func TestDeviceLinkPutDelete(t *testing.T) {
 		t.Fatalf("unlink de nuevo = %d, want 404", rec.Code)
 	}
 }
+
+// TestDeviceLinkPutRejectsInvalidMAC verifica que PUT /api/devices/{mac}/link
+// rechaza MACs inválidas en el path o en target con 400 invalid_mac.
+func TestDeviceLinkPutRejectsInvalidMAC(t *testing.T) {
+	s := newOverrideTestServer(t)
+
+	t.Run("path con MAC inválida", func(t *testing.T) {
+		req := httptest.NewRequest(http.MethodPut, "/api/devices/no-es-mac/link", strings.NewReader(`{"target":"02:00:00:00:00:01"}`))
+		req.SetPathValue("mac", "no-es-mac")
+		rec := httptest.NewRecorder()
+		s.handleDeviceLinkPut(rec, req)
+		if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "invalid_mac") {
+			t.Fatalf("esperaba 400 invalid_mac, obtuve %d: %s", rec.Code, rec.Body.String())
+		}
+	})
+
+	t.Run("target con MAC inválida", func(t *testing.T) {
+		req := httptest.NewRequest(http.MethodPut, "/api/devices/02:00:00:00:00:01/link", strings.NewReader(`{"target":"basura"}`))
+		req.SetPathValue("mac", "02:00:00:00:00:01")
+		rec := httptest.NewRecorder()
+		s.handleDeviceLinkPut(rec, req)
+		if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "invalid_mac") {
+			t.Fatalf("esperaba 400 invalid_mac, obtuve %d: %s", rec.Code, rec.Body.String())
+		}
+	})
+}
+
+// TestDeviceLinkDeleteLegacyNonMAC garantiza que DELETE /api/devices/{mac}/link
+// sigue siendo permisivo para poder retirar filas heredadas no-MAC.
+func TestDeviceLinkDeleteLegacyNonMAC(t *testing.T) {
+	s := newOverrideTestServer(t)
+	if _, err := s.db.Exec("INSERT INTO device_links (mac, canonical) VALUES (?, ?)", "LEGACY:ALIAS", "02:00:00:00:00:01"); err != nil {
+		t.Fatalf("sembrar device_links: %v", err)
+	}
+	del := func(raw string) int {
+		req := httptest.NewRequest(http.MethodDelete, "/api/devices/x/link", nil)
+		req.SetPathValue("mac", raw)
+		rec := httptest.NewRecorder()
+		s.handleDeviceLinkDelete(rec, req)
+		return rec.Code
+	}
+	if code := del("no-existe"); code != http.StatusNotFound {
+		t.Fatalf("clave desconocida: esperaba 404, obtuve %d", code)
+	}
+	if code := del("legacy-alias"); code != http.StatusNoContent {
+		t.Fatalf("fila heredada: esperaba 204, obtuve %d", code)
+	}
+}
+
+// TestDeviceDeleteLegacyNonMAC garantiza que DELETE /api/devices/{mac} sigue
+// borrando filas heredadas no-MAC de device_seen con 204.
+func TestDeviceDeleteLegacyNonMAC(t *testing.T) {
+	s := panelTestServer(t)
+	if _, err := s.db.Exec("INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES ('legacy-non-mac', 1, 2, 'legacy')"); err != nil {
+		t.Fatalf("sembrar device_seen: %v", err)
+	}
+	r := httptest.NewRequest(http.MethodDelete, "/api/devices/legacy-non-mac", nil)
+	r.SetPathValue("mac", "legacy-non-mac")
+	rec := httptest.NewRecorder()
+	s.handleDeviceDelete(rec, r)
+	if rec.Code != http.StatusNoContent {
+		t.Fatalf("esperaba 204, obtuve %d (%s)", rec.Code, rec.Body.String())
+	}
+	var n int
+	if err := s.db.QueryRow("SELECT COUNT(*) FROM device_seen WHERE mac = 'legacy-non-mac'").Scan(&n); err != nil {
+		t.Fatal(err)
+	}
+	if n != 0 {
+		t.Fatalf("filas restantes = %d, esperaba 0", n)
+	}
+}
+
+// TestDeviceDeleteLegacyNonMACNoGarbageTombstone verifica que borrar una fila
+// heredada no-MAC de device_seen no inserta una lápida basura en deleted_clients.
+func TestDeviceDeleteLegacyNonMACNoGarbageTombstone(t *testing.T) {
+	s := panelTestServer(t)
+	if _, err := s.db.Exec("INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES ('legacy-non-mac', 1, 2, 'legacy')"); err != nil {
+		t.Fatalf("sembrar device_seen: %v", err)
+	}
+	r := httptest.NewRequest(http.MethodDelete, "/api/devices/legacy-non-mac", nil)
+	r.SetPathValue("mac", "legacy-non-mac")
+	rec := httptest.NewRecorder()
+	s.handleDeviceDelete(rec, r)
+	if rec.Code != http.StatusNoContent {
+		t.Fatalf("esperaba 204, obtuve %d (%s)", rec.Code, rec.Body.String())
+	}
+	var tombs int
+	if err := s.db.QueryRow("SELECT COUNT(*) FROM deleted_clients").Scan(&tombs); err != nil {
+		t.Fatal(err)
+	}
+	if tombs != 0 {
+		t.Fatalf("no debía guardarse lápida para clave no-MAC, obtuve %d filas en deleted_clients", tombs)
+	}
+}