Przeglądaj źródła

feat(alerts): approve impostor BSSIDs and a global on/off switch for the rule (#1401)

Approve a known BSSID from the impostor alert (persisted, revocable) plus a global on/off switch for the whole SSID impostor rule in the alerts config. For fleets with known APs outside NetPulse (UniFi, Omada...) that broadcast fleet SSIDs.

Closes #1400
Nacho 1 miesiąc temu
rodzic
commit
b85df69a02

+ 3 - 0
app/public/locales/en/translation.json

@@ -27,6 +27,9 @@
     "onlyUnread": "Unread only",
     "silence": "Silence",
     "silenceForever": "Forever",
+    "approveBssid": "This BSSID is ours: approve it and stop impostor alerts for it",
+    "impostorRule": "SSID impostor detection",
+    "impostorRuleDesc": "Alert when an unknown radio broadcasts a network name of your fleet. Turn it off if your own APs outside NetPulse (UniFi, Omada...) trigger false positives.",
     "sevAll": "All",
     "sevInfo": "Info",
     "sevResolved": "Resolved",

+ 3 - 0
app/public/locales/es/translation.json

@@ -27,6 +27,9 @@
     "onlyUnread": "Solo no leídas",
     "silence": "Silenciar",
     "silenceForever": "Siempre",
+    "approveBssid": "Este BSSID es nuestro: aprobarlo y dejar de alertar de impostor por él",
+    "impostorRule": "Detección de impostores de SSID",
+    "impostorRuleDesc": "Avisa cuando una radio desconocida emite el nombre de una red de tu flota. Apágala si tus propios APs fuera de NetPulse (UniFi, Omada...) generan falsos positivos.",
     "sevAll": "Todas",
     "sevInfo": "Info",
     "sevResolved": "Resueltas",

+ 33 - 1
app/src/data/DataProvider.tsx

@@ -189,6 +189,9 @@ export interface NetPulseApi extends NetPulseData {
   clearAllAlerts: () => void
   /** POST /api/alerts/silence (live): silencia alertas con la misma dedup key. */
   silenceAlert: (id: string, duration: '1h' | '24h' | 'forever') => void
+  /** POST /api/alerts/impostor-approve (live): aprueba un BSSID como propio
+   * (#1400); la alerta de impostor de ese BSSID se resuelve y no vuelve. */
+  approveImpostorBssid: (bssid: string) => void
   /** POST /api/alerts/dismiss (live): limpia una alerta del feed (#833). Demo: estado local. Optimista. */
   dismissAlert: (id: string) => void
   /**
@@ -1032,6 +1035,34 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     })()
   }, [])
 
+  /** Aprueba un BSSID como propio (#1400): quita del feed las alertas de
+   * impostor de ese BSSID (optimista) y lo persiste en el backend (live). */
+  const approveImpostorBssid = useCallback((bssid: string) => {
+    setBundle((prev) => {
+      const alerts = prev.alerts.filter(
+        (a) => !(a.type === 'wifi-ssid-impostor' && a.vars?.bssid === bssid),
+      )
+      const unreadAlerts =
+        modeRef.current === 'live'
+          ? prev.unreadAlerts
+          : countUnreadAlerts(alerts, configRef.current)
+      return { ...prev, alerts, unreadAlerts }
+    })
+    if (modeRef.current !== 'live') return
+    void (async () => {
+      try {
+        const res = await fetch('/api/alerts/impostor-approve', {
+          method: 'POST',
+          headers: { 'Content-Type': 'application/json' },
+          body: JSON.stringify({ bssid }),
+        })
+        if (res.status === 401) redirectLogin()
+      } catch {
+        /* resync por snapshot */
+      }
+    })()
+  }, [])
+
   /** Limpia una alerta del feed (issue #833): oculta la fila al instante y,
    * en live, la persiste como dismiss en el backend (no reaparece tras un
    * reinicio; si la condición se re-dispara, vuelve sola). */
@@ -1321,6 +1352,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       markAllAlertsRead,
       clearAllAlerts,
       silenceAlert,
+      approveImpostorBssid,
       dismissAlert,
       rearmAgent,
       upgradeAgent,
@@ -1330,7 +1362,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       removeAgent,
       createAgentInstall,
     }),
-    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, removeAgent, createAgentInstall],
+    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, approveImpostorBssid, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, removeAgent, createAgentInstall],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

+ 70 - 1
app/src/pages/Alerts.tsx

@@ -21,6 +21,7 @@ import {
   Server,
   Settings2,
   Shield,
+  ShieldCheck,
   Signal,
   Smartphone,
   Tablet,
@@ -36,6 +37,7 @@ import { CountUp } from '@/components/CountUp'
 import { EmptyState } from '@/components/EmptyState'
 import { RowAction } from '@/components/RowAction'
 import { SegmentedControl } from '@/components/SegmentedControl'
+import { Switch } from '@/components/ui/switch'
 import {
   DropdownMenu,
   DropdownMenuContent,
@@ -286,6 +288,55 @@ function ContextPanel({ ev, animateIn }: { ev: FeedEvent; animateIn: boolean })
   )
 }
 
+// ImpostorRuleToggle (#1400): interruptor global de la detección de SSID
+// impostor. Vive en el diálogo "Configurar alertas"; fetch propio (no
+// pertenece al bundle: solo se consulta aquí). En demo es solo local.
+function ImpostorRuleToggle() {
+  const { t } = useTranslation()
+  const { isDemo } = useNetPulse()
+  const [enabled, setEnabled] = useState<boolean | null>(null)
+  useEffect(() => {
+    if (isDemo) {
+      setEnabled(true)
+      return
+    }
+    let cancelled = false
+    void (async () => {
+      try {
+        const res = await fetch('/api/alerts/impostor-rule')
+        if (res.ok && !cancelled) {
+          const data = (await res.json()) as { enabled?: boolean }
+          setEnabled(data.enabled !== false)
+        }
+      } catch {
+        /* sin estado: el toggle queda oculto */
+      }
+    })()
+    return () => {
+      cancelled = true
+    }
+  }, [isDemo])
+  const toggle = (v: boolean) => {
+    setEnabled(v)
+    if (isDemo) return
+    void fetch('/api/alerts/impostor-rule', {
+      method: 'POST',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify({ enabled: v }),
+    }).catch(() => setEnabled((prev) => prev))
+  }
+  if (enabled === null) return null
+  return (
+    <div className="mt-4 flex items-center justify-between gap-4 border-t border-border/60 pt-4">
+      <div className="min-w-0">
+        <div className="text-sm font-medium text-text-primary">{t('alerts.impostorRule')}</div>
+        <p className="mt-0.5 text-caption leading-snug text-text-muted">{t('alerts.impostorRuleDesc')}</p>
+      </div>
+      <Switch checked={enabled} onCheckedChange={toggle} aria-label={t('alerts.impostorRule')} />
+    </div>
+  )
+}
+
 // ---------------------------------------------------------------------------
 // Fila del feed (timeline, alerts.md §④)
 // ---------------------------------------------------------------------------
@@ -299,6 +350,8 @@ interface FeedRowProps {
   reduce: boolean
   onSilence?: (id: string, duration: '1h' | '24h' | 'forever') => void
   onDismiss?: (id: string) => void
+  /** #1400: aprobar el BSSID de una alerta wifi-ssid-impostor como propio. */
+  onApproveImpostor?: (bssid: string) => void
   action?: { icon: LucideIcon; title: string; onClick: () => void }
   /** #1349: feed por id para resolver los eventos que un evento de cierre
    *  (`ev.resolves`) cerró y listarlos al expandirlo. */
@@ -307,7 +360,7 @@ interface FeedRowProps {
 
 // #862: RowAction vive en components/RowAction.tsx (compartido con AlertItem).
 
-function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence, onDismiss, action, feedById }: FeedRowProps) {
+function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence, onDismiss, onApproveImpostor, action, feedById }: FeedRowProps) {
   const { t } = useTranslation()
   const sev = SEVERITY[ev.severity]
   const Icon = ev.icon ?? sev.icon
@@ -403,6 +456,19 @@ function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence, onDis
                   />
                 )}
               </AnimatePresence>
+              {/* #1400: en alertas de impostor, aprobar el BSSID como
+                  propio (AP conocido fuera de la flota: UniFi, Omada...).
+                  Persiste en el backend y resuelve la alerta. */}
+              {onApproveImpostor && ev.type === 'wifi-ssid-impostor' && ev.vars?.bssid && (
+                <button
+                  type="button"
+                  onClick={(e) => { e.stopPropagation(); onApproveImpostor(ev.vars!.bssid!) }}
+                  className="rounded-md p-1 opacity-0 group-hover:opacity-100 transition-opacity text-text-muted hover:text-ok pointer-coarse:opacity-100 pointer-coarse:p-2"
+                  title={t('alerts.approveBssid')}
+                >
+                  <ShieldCheck className="h-4 w-4" strokeWidth={1.75} />
+                </button>
+              )}
               {onSilence && (
                 <button
                   type="button"
@@ -543,6 +609,7 @@ export default function Alerts() {
     clearAllAlerts,
     silenceAlert,
     dismissAlert,
+    approveImpostorBssid,
   } = useNetPulse()
   // Feed: demo = diseño enriquecido del mockup; live = SOLO alertas reales
   const alertFeed = useMemo(
@@ -936,6 +1003,7 @@ export default function Alerts() {
                   )
                 })}
               </ul>
+              <ImpostorRuleToggle />
               <div className="mt-4 border-t border-border/60 pt-4">
                 <RulesManager />
               </div>
@@ -1038,6 +1106,7 @@ export default function Alerts() {
                     reduce={reduce}
                     onSilence={silenceAlert}
                     onDismiss={dismissAlert}
+                    onApproveImpostor={approveImpostorBssid}
                     action={actionOf(ev)}
                     feedById={feedById}
                   />

+ 118 - 1
server-go/internal/adapters/impostor.go

@@ -18,7 +18,10 @@ package adapters
 // configurar para el caso común.
 
 import (
+	"encoding/json"
 	"fmt"
+	"net"
+	"sort"
 	"strings"
 	"time"
 
@@ -36,6 +39,14 @@ const (
 	impostorRecent = 2 * time.Hour
 	// impostorWindow: sightings más viejos que esto no cuentan.
 	impostorWindow = 6 * time.Hour
+	// impostorAllowKey (#1400): clave kv con la lista persistida de BSSIDs
+	// aprobados a mano (APs conocidos fuera de la flota NetPulse: UniFi,
+	// Omada... cuyos BSSIDs no llegan por agentes/SSH/DAWN).
+	impostorAllowKey = "impostor_allowlist_v1"
+	// impostorEnabledKey (#1400): clave kv con el interruptor global de la
+	// regla ("1"/"0"; ausente = activada). Apagarla para la detección y
+	// resuelve las alertas de impostor activas.
+	impostorEnabledKey = "alerts.impostor_enabled"
 )
 
 // EvalSsidImpostors: una pasada sobre wifi_scans recientes. La llama el
@@ -45,6 +56,12 @@ func (l *Live) EvalSsidImpostors() {
 	if l.db == nil || l.agents == nil || l.engine == nil {
 		return
 	}
+	l.mu.Lock()
+	ruleEnabled := l.impostorEnabled
+	l.mu.Unlock()
+	if !ruleEnabled {
+		return // #1400: regla desactivada globalmente desde Configurar alertas
+	}
 	now := time.Now()
 
 	ownBssids := map[string]bool{}
@@ -62,6 +79,12 @@ func (l *Live) EvalSsidImpostors() {
 			}
 		}
 	}
+	// #1400: BSSIDs aprobados a mano (lista persistida en kv). Copia local
+	// para evaluar fuera del mutex.
+	approved := make(map[string]bool, len(l.impostorAllow))
+	for b := range l.impostorAllow {
+		approved[b] = true
+	}
 	l.mu.Unlock()
 	fleetSsids := map[string]bool{}
 	for _, s := range l.agents.LocalSsids() {
@@ -93,7 +116,7 @@ func (l *Live) EvalSsidImpostors() {
 			continue
 		}
 		bssid = strings.ToUpper(strings.TrimSpace(bssid))
-		if bssid == "" || !fleetSsids[ssid] || ownBssids[bssid] {
+		if bssid == "" || !fleetSsids[ssid] || ownBssids[bssid] || approved[bssid] {
 			continue
 		}
 		s := byBssid[bssid]
@@ -168,3 +191,97 @@ func (l *Live) EvalSsidImpostors() {
 		}
 	}
 }
+
+// ImpostorApproved (#1400): BSSIDs aprobados a mano, ordenados. La UI la
+// muestra y permite revocar.
+func (l *Live) ImpostorApproved() []string {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	out := make([]string, 0, len(l.impostorAllow))
+	for b := range l.impostorAllow {
+		out = append(out, b)
+	}
+	sort.Strings(out)
+	return out
+}
+
+// ApproveImpostorBssid (#1400): marca un BSSID como propio (AP conocido que
+// 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 := strings.ToUpper(mac.String())
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	l.impostorAllow[norm] = true
+	l.saveImpostorAllowLocked()
+	if alertID, ok := l.impostorActive[norm]; ok {
+		l.engine.Resolve(alertID)
+		delete(l.impostorActive, norm)
+	}
+	return nil
+}
+
+// RevokeImpostorBssid (#1400): quita un BSSID de la lista de aprobados. Si
+// 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))
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	delete(l.impostorAllow, norm)
+	l.saveImpostorAllowLocked()
+}
+
+// saveImpostorAllowLocked: persiste la lista en kv. Caller holds l.mu.
+func (l *Live) saveImpostorAllowLocked() {
+	if l.db == nil {
+		return
+	}
+	list := make([]string, 0, len(l.impostorAllow))
+	for b := range l.impostorAllow {
+		list = append(list, b)
+	}
+	raw, err := json.Marshal(list)
+	if err != nil {
+		return
+	}
+	_, _ = l.db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+		impostorAllowKey, string(raw))
+}
+
+// ImpostorRuleEnabled (#1400): interruptor global de la regla (default on).
+func (l *Live) ImpostorRuleEnabled() bool {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	return l.impostorEnabled
+}
+
+// SetImpostorRuleEnabled (#1400): activa/desactiva la detección de
+// impostores de SSID. Persistido en kv. Al desactivar, las alertas de
+// impostor activas se resuelven (dejan de molestar al momento); al activar,
+// la próxima evaluación vuelve a detectar desde cero.
+func (l *Live) SetImpostorRuleEnabled(enabled bool) {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	l.impostorEnabled = enabled
+	if l.db != nil {
+		v := "0"
+		if enabled {
+			v = "1"
+		}
+		_, _ = l.db.Exec(
+			"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+			impostorEnabledKey, v)
+	}
+	if !enabled {
+		for bssid, alertID := range l.impostorActive {
+			l.engine.Resolve(alertID)
+			delete(l.impostorActive, bssid)
+		}
+	}
+}

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

@@ -206,3 +206,139 @@ func TestImpostorAlertUsesLatestSighting(t *testing.T) {
 		t.Fatalf("vars deben ser del sighting más reciente: %+v", got[0].Vars)
 	}
 }
+
+func TestImpostorApprovedDoesNotAlert(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	now := time.Now()
+	// #1400: BSSID aprobado a mano (AP UniFi ajeno a la flota NetPulse).
+	if err := l.ApproveImpostorBssid("de:ad:be:ef:00:10"); err != nil {
+		t.Fatalf("approve: %v", err)
+	}
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:10", "temiscira", now.Add(-40*time.Minute))
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:10", "temiscira", now)
+	l.EvalSsidImpostors()
+	if got := impostorAlerts(l); len(got) != 0 {
+		t.Fatalf("BSSID aprobado no debe alertar; alertas: %+v", got)
+	}
+	if got := l.ImpostorApproved(); len(got) != 1 || got[0] != "DE:AD:BE:EF:00:10" {
+		t.Fatalf("ImpostorApproved = %v", got)
+	}
+}
+
+func TestImpostorApproveResolvesActiveAlert(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	now := time.Now()
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:11", "temiscira", now.Add(-40*time.Minute))
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:11", "temiscira", now)
+	l.EvalSsidImpostors()
+	if got := impostorAlerts(l); len(got) != 1 {
+		t.Fatalf("debió alertar; alertas: %d", len(got))
+	}
+	if err := l.ApproveImpostorBssid("DE:AD:BE:EF:00:11"); err != nil {
+		t.Fatalf("approve: %v", err)
+	}
+	if got := impostorAlerts(l); len(got) != 0 {
+		t.Fatalf("aprobar debe resolver la alerta activa; alertas: %+v", got)
+	}
+	if len(l.impostorActive) != 0 {
+		t.Fatalf("tracking residual tras aprobar: %+v", l.impostorActive)
+	}
+	// Re-evaluar con la evidencia intacta: no re-alerta (aprobado).
+	l.EvalSsidImpostors()
+	if got := impostorAlerts(l); len(got) != 0 {
+		t.Fatalf("aprobado no debe re-alertar; alertas: %+v", got)
+	}
+}
+
+func TestImpostorRevokeReAlerts(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	now := time.Now()
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:12", "temiscira", now.Add(-40*time.Minute))
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:12", "temiscira", now)
+	if err := l.ApproveImpostorBssid("DE:AD:BE:EF:00:12"); err != nil {
+		t.Fatalf("approve: %v", err)
+	}
+	l.EvalSsidImpostors()
+	if got := impostorAlerts(l); len(got) != 0 {
+		t.Fatalf("aprobado no debe alertar; alertas: %+v", got)
+	}
+	l.RevokeImpostorBssid("DE:AD:BE:EF:00:12")
+	if got := l.ImpostorApproved(); len(got) != 0 {
+		t.Fatalf("revoke debe vaciar la lista; got %v", got)
+	}
+	l.EvalSsidImpostors()
+	if got := impostorAlerts(l); len(got) != 1 {
+		t.Fatalf("revocado y visible debe re-alertar; alertas: %d", len(got))
+	}
+}
+
+func TestImpostorApproveInvalidBssid(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	for _, bad := range []string{"", "no-es-mac", "DE:AD:BE:EF:00", "zz:zz:zz:zz:zz:zz"} {
+		if err := l.ApproveImpostorBssid(bad); err == nil {
+			t.Fatalf("bssid inválido %q debe dar error", bad)
+		}
+	}
+	if got := l.ImpostorApproved(); len(got) != 0 {
+		t.Fatalf("ningún inválido debe entrar en la lista; got %v", got)
+	}
+}
+
+func TestImpostorAllowlistPersistsAcrossRestart(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	if err := l.ApproveImpostorBssid("DE:AD:BE:EF:00:13"); err != nil {
+		t.Fatalf("approve: %v", err)
+	}
+	// Simula un reinicio: Live NUEVO sobre la misma BD (mismo dir).
+	dir := t.TempDir() // dummy para no confundir; la BD real es la de l
+	_ = dir
+	d2 := l.db // misma BD abierta
+	l2 := NewLive(nil, d2, []RouterConfig{{ID: "ap1", Name: "AP Uno"}}, nil)
+	if got := l2.ImpostorApproved(); len(got) != 1 || got[0] != "DE:AD:BE:EF:00:13" {
+		t.Fatalf("la lista debe sobrevivir al reinicio; got %v", got)
+	}
+}
+
+func TestImpostorRuleDisabledNoAlerts(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	now := time.Now()
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:20", "temiscira", now.Add(-40*time.Minute))
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:20", "temiscira", now)
+	l.SetImpostorRuleEnabled(false)
+	if l.ImpostorRuleEnabled() {
+		t.Fatal("la regla debe quedar desactivada")
+	}
+	l.EvalSsidImpostors()
+	if got := impostorAlerts(l); len(got) != 0 {
+		t.Fatalf("regla desactivada no debe alertar; alertas: %+v", got)
+	}
+	// Persistencia: un Live nuevo sobre la misma BD arranca desactivado.
+	l2 := NewLive(nil, l.db, []RouterConfig{{ID: "ap1", Name: "AP Uno"}}, nil)
+	if l2.ImpostorRuleEnabled() {
+		t.Fatal("el interruptor debe sobrevivir al reinicio")
+	}
+}
+
+func TestImpostorRuleDisableResolvesActive(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	now := time.Now()
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:21", "temiscira", now.Add(-40*time.Minute))
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:21", "temiscira", now)
+	l.EvalSsidImpostors()
+	if got := impostorAlerts(l); len(got) != 1 {
+		t.Fatalf("debió alertar; alertas: %d", len(got))
+	}
+	l.SetImpostorRuleEnabled(false)
+	if got := impostorAlerts(l); len(got) != 0 {
+		t.Fatalf("desactivar debe resolver las activas; alertas: %+v", got)
+	}
+	if len(l.impostorActive) != 0 {
+		t.Fatalf("tracking residual tras desactivar: %+v", l.impostorActive)
+	}
+	// Re-activar: la evidencia sigue ahí, vuelve a alertar.
+	l.SetImpostorRuleEnabled(true)
+	l.EvalSsidImpostors()
+	if got := impostorAlerts(l); len(got) != 1 {
+		t.Fatalf("re-activar debe re-alertar con evidencia vigente; alertas: %d", len(got))
+	}
+}

+ 24 - 0
server-go/internal/adapters/live.go

@@ -323,6 +323,13 @@ type Live struct {
 	// memoria a propósito: si el server reinicia y el impostor sigue
 	// visible, la alerta se re-emite (seguridad prima sobre re-aviso).
 	impostorActive map[string]string
+	// impostorAllow (#1400): BSSIDs aprobados a mano como propios (APs
+	// conocidos fuera de la flota: UniFi, Omada...). Persistido en kv
+	// (impostorAllowKey) para sobrevivir reinicios.
+	impostorAllow map[string]bool
+	// impostorEnabled (#1400): interruptor global de la regla de impostores
+	// (default true; persistido en kv impostorEnabledKey).
+	impostorEnabled bool
 	// Presencia wireless (issue #184): devicePresence = MAC → online del
 	// último ciclo evaluado; presenceMisses = ticks seguidos sin verse.
 	// presenceSeen evita la avalancha del primer ciclo (anti-arranque).
@@ -471,6 +478,8 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		unknownAlerted:       map[string]bool{},
 		unknownGraceNum:      3, // default de #234; el engine/demo puede afinarlo
 		impostorActive:       map[string]string{},
+		impostorAllow:        map[string]bool{},
+		impostorEnabled:      true,
 		devicePresence:       map[string]bool{},
 		presenceMisses:       map[string]int{},
 		presenceOfflineAfter: 3,
@@ -517,6 +526,21 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 			}
 			rows.Close()
 		}
+		// #1400: BSSIDs de impostor aprobados a mano, persistidos en kv.
+		var allowRaw string
+		if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", "impostor_allowlist_v1").Scan(&allowRaw); err == nil {
+			var list []string
+			if json.Unmarshal([]byte(allowRaw), &list) == nil {
+				for _, b := range list {
+					l.impostorAllow[strings.ToUpper(strings.TrimSpace(b))] = true
+				}
+			}
+		}
+		// #1400: interruptor global de la regla (ausente = activada).
+		var enRaw string
+		if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", "alerts.impostor_enabled").Scan(&enRaw); err == nil {
+			l.impostorEnabled = enRaw != "0"
+		}
 	}
 	l.SetRouters(initial)
 	return l

+ 87 - 0
server-go/internal/httpapi/data.go

@@ -469,6 +469,93 @@ func (s *server) handleAlertsSilenced(w http.ResponseWriter, _ *http.Request) {
 	writeJSON(w, http.StatusOK, s.adapter.AlertsEngine().Silenced())
 }
 
+// handleAlertsImpostorApprove (POST): body {"bssid":"AA:BB:..."} → aprueba el
+// BSSID como propio (#1400): la regla wifi-ssid-impostor lo ignora y la
+// alerta activa (si la hay) se resuelve. Persistido en kv.
+func (s *server) handleAlertsImpostorApprove(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		Bssid string `json:"bssid"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	ap, ok := s.adapter.(interface{ ApproveImpostorBssid(string) error })
+	if !ok {
+		writeError(w, http.StatusNotImplemented, "not_supported", "adapter does not support impostor approval")
+		return
+	}
+	if err := ap.ApproveImpostorBssid(body.Bssid); err != nil {
+		writeError(w, http.StatusBadRequest, "invalid_input", "invalid bssid")
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+// handleAlertsImpostorRevoke (POST): body {"bssid":"..."} → quita el BSSID de
+// la lista de aprobados (#1400); si sigue visible, la regla re-alerta.
+func (s *server) handleAlertsImpostorRevoke(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		Bssid string `json:"bssid"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	ap, ok := s.adapter.(interface{ RevokeImpostorBssid(string) })
+	if !ok {
+		writeError(w, http.StatusNotImplemented, "not_supported", "adapter does not support impostor approval")
+		return
+	}
+	ap.RevokeImpostorBssid(body.Bssid)
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+// handleAlertsImpostorApproved (GET): lista de BSSIDs aprobados (#1400).
+func (s *server) handleAlertsImpostorApproved(w http.ResponseWriter, _ *http.Request) {
+	ap, ok := s.adapter.(interface{ ImpostorApproved() []string })
+	if !ok {
+		writeJSON(w, http.StatusOK, []string{})
+		return
+	}
+	writeJSON(w, http.StatusOK, ap.ImpostorApproved())
+}
+
+// handleAlertsImpostorRuleGet (GET): interruptor global de la regla de
+// impostores (#1400) → {"enabled": bool}. Default true.
+func (s *server) handleAlertsImpostorRuleGet(w http.ResponseWriter, _ *http.Request) {
+	ap, ok := s.adapter.(interface{ ImpostorRuleEnabled() bool })
+	if !ok {
+		writeJSON(w, http.StatusOK, map[string]bool{"enabled": true})
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]bool{"enabled": ap.ImpostorRuleEnabled()})
+}
+
+// handleAlertsImpostorRuleSet (POST): body {"enabled": bool} → activa o
+// desactiva la regla entera (#1400). Al desactivar, las alertas de impostor
+// activas se resuelven.
+func (s *server) handleAlertsImpostorRuleSet(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		Enabled *bool `json:"enabled"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	if body.Enabled == nil {
+		writeError(w, http.StatusBadRequest, "invalid_input", "enabled is required")
+		return
+	}
+	ap, ok := s.adapter.(interface{ SetImpostorRuleEnabled(bool) })
+	if !ok {
+		writeError(w, http.StatusNotImplemented, "not_supported", "adapter does not support impostor rule toggle")
+		return
+	}
+	ap.SetImpostorRuleEnabled(*body.Enabled)
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true, "enabled": *body.Enabled})
+}
+
 // handleTopology: {routers, devices} sin paginar.
 func (s *server) handleTopology(w http.ResponseWriter, r *http.Request) {
 	routers := s.adapter.GetRouters(r.Context())

+ 5 - 0
server-go/internal/httpapi/server.go

@@ -394,6 +394,11 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("POST /api/alerts/silence", s.handleAlertsSilence)
 	mux.HandleFunc("POST /api/alerts/unsilence", s.handleAlertsUnsilence)
 	mux.HandleFunc("GET /api/alerts/silenced", s.handleAlertsSilenced)
+	mux.HandleFunc("POST /api/alerts/impostor-approve", s.handleAlertsImpostorApprove)
+	mux.HandleFunc("POST /api/alerts/impostor-revoke", s.handleAlertsImpostorRevoke)
+	mux.HandleFunc("GET /api/alerts/impostor-approved", s.handleAlertsImpostorApproved)
+	mux.HandleFunc("GET /api/alerts/impostor-rule", s.handleAlertsImpostorRuleGet)
+	mux.HandleFunc("POST /api/alerts/impostor-rule", s.handleAlertsImpostorRuleSet)
 	mux.HandleFunc("GET /api/alert-rules", s.handleAlertRulesList)
 	mux.HandleFunc("GET /api/alert-rules/{id}", s.handleAlertRulesGet)
 	mux.HandleFunc("POST /api/alert-rules", s.handleAlertRulesCreate)