alerts_live_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. // alerts_live_test.go — taxonomía SPEC-ALERTAS §1 en la demo y en los
  2. // eventos live nuevos (router recuperado, WAN caído, desconocido se conecta)
  3. // y migración de los 4 sitios históricos al motor.
  4. package adapters
  5. import (
  6. "fmt"
  7. "strings"
  8. "testing"
  9. "github.com/gnacho/netpulse/server-go/internal/alerts"
  10. "github.com/gnacho/netpulse/server-go/internal/db"
  11. )
  12. // Las 5 alertas canon pasan por el motor con config default y sobreviven
  13. // (SPEC-ALERTAS §5), con Category/Urgent/Ts correctos.
  14. func TestDemoCanonAlertsThroughEngine(t *testing.T) {
  15. d := NewDemo()
  16. list := d.GetAlerts(t.Context())
  17. if len(list) != 5 {
  18. t.Fatalf("canon: %d alertas, esperaba 5", len(list))
  19. }
  20. want := map[string]struct {
  21. cat string
  22. urgent bool
  23. sev string
  24. read bool
  25. }{
  26. "alert-temp-patio": {alerts.CatRouter, true, "warn", false},
  27. "alert-firmware-estudio": {alerts.CatSystem, false, "warn", false},
  28. "alert-nuevo-tab": {alerts.CatClients, false, "info", true},
  29. "alert-handshake-wg": {alerts.CatVPN, false, "info", true},
  30. "alert-backup-adguard": {alerts.CatSystem, false, "ok", true},
  31. }
  32. for _, a := range list {
  33. w, ok := want[a.ID]
  34. if !ok {
  35. t.Fatalf("alerta inesperada: %s", a.ID)
  36. }
  37. if a.Category != w.cat || a.Urgent != w.urgent || a.Severity != w.sev {
  38. t.Fatalf("%s taxonomía: (%s,%v,%s), esperaba (%s,%v,%s)",
  39. a.ID, a.Category, a.Urgent, a.Severity, w.cat, w.urgent, w.sev)
  40. }
  41. if a.Read != w.read {
  42. t.Fatalf("%s read: %v, esperaba %v", a.ID, a.Read, w.read)
  43. }
  44. if a.Ts <= 0 {
  45. t.Fatalf("%s sin Ts", a.ID)
  46. }
  47. if a.Time == "" {
  48. t.Fatalf("%s sin Time legado", a.ID)
  49. }
  50. }
  51. // El orden canónico se conserva (seed en inverso + prepend).
  52. order := []string{"alert-temp-patio", "alert-firmware-estudio", "alert-nuevo-tab", "alert-handshake-wg", "alert-backup-adguard"}
  53. for i, id := range order {
  54. if list[i].ID != id {
  55. t.Fatalf("orden canon: posición %d = %s, esperaba %s", i, list[i].ID, id)
  56. }
  57. }
  58. // UnreadAlerts del overview = no leídas del motor (2 en el canon).
  59. ov, err := d.GetOverview(t.Context())
  60. if err != nil {
  61. t.Fatal(err)
  62. }
  63. if ov.UnreadAlerts != 2 {
  64. t.Fatalf("unreadAlerts: %d, esperaba 2", ov.UnreadAlerts)
  65. }
  66. }
  67. // liveTestLive: Live mínimo con motor en memoria para probar las emisiones.
  68. func liveTestLive() *Live {
  69. return &Live{
  70. engine: alerts.New(nil, nil),
  71. lastStatus: map[string]string{},
  72. wanDown: map[string]int{},
  73. onlineMacs: map[string]bool{},
  74. unknownGrace: map[string]int{},
  75. unknownAlerted: map[string]bool{},
  76. unknownGraceNum: 3,
  77. }
  78. }
  79. func TestLiveRouterRecoveredTaxonomy(t *testing.T) {
  80. l := liveTestLive()
  81. // Semántica #1413: la config ya no filtra la ingesta, así que con el
  82. // default router:urgent el evento (urgent=false) SE GUARDA igual.
  83. l.mu.Lock()
  84. l.emitRouterRecovered("patio", "Patio")
  85. l.mu.Unlock()
  86. list := l.engine.List()
  87. if len(list) != 1 {
  88. t.Fatalf("alertas: %d, esperaba 1 (la ingesta ya no se filtra)", len(list))
  89. }
  90. if a := list[0]; a.Category != alerts.CatRouter || a.Urgent || a.Severity != "ok" {
  91. t.Fatalf("recuperado: (%s,%v,%s), esperaba (router,false,ok)", a.Category, a.Urgent, a.Severity)
  92. }
  93. // Con router:all la taxonomía es la misma (no cambia la ingesta, solo la
  94. // notificación; el SPEC §1 se cumple en ambos niveles).
  95. if err := l.engine.SetConfig(map[string]string{"router": "all"}); err != nil {
  96. t.Fatal(err)
  97. }
  98. l.mu.Lock()
  99. l.emitRouterRecovered("patio", "Patio")
  100. l.mu.Unlock()
  101. list = l.engine.List()
  102. if len(list) != 1 {
  103. t.Fatalf("alertas tras re-emitir: %d, esperaba 1 (mismo ID, update)", len(list))
  104. }
  105. a := list[0]
  106. if a.Category != alerts.CatRouter || a.Urgent || a.Severity != "ok" {
  107. t.Fatalf("recuperado: (%s,%v,%s), esperaba (router,false,ok)", a.Category, a.Urgent, a.Severity)
  108. }
  109. if a.RouterID != "patio" || a.Ts == 0 {
  110. t.Fatalf("recuperado: %+v", a)
  111. }
  112. }
  113. // Issue #846: la alerta crítica de offline de un router se ELIMINA cuando el
  114. // router vuelve a responder de forma estable; con APs que flapean no quedan
  115. // caídas fantasma en el feed (antes, #256, solo se marcaba leída).
  116. func TestLiveRouterOfflineAlertResolvedOnRecovery(t *testing.T) {
  117. l := liveTestLive()
  118. offlineID := "alert-offline-patio-1"
  119. l.engine.Emit(AlertEvent{
  120. ID: offlineID, Category: alerts.CatRouter, Urgent: true,
  121. Severity: "critical", Title: "Patio offline", RouterID: "patio", Time: "ahora mismo",
  122. })
  123. if len(l.engine.List()) != 1 {
  124. t.Fatalf("alerta de caída: %d", len(l.engine.List()))
  125. }
  126. // El router vuelve online → las caídas pendientes se eliminan del feed.
  127. l.mu.Lock()
  128. l.resolveOfflineAlerts("patio")
  129. l.mu.Unlock()
  130. if list := l.engine.List(); len(list) != 0 {
  131. t.Fatalf("la caída debería eliminarse tras la recuperación: %+v", list)
  132. }
  133. // Las caídas de OTROS routers no se tocan.
  134. l.engine.Emit(AlertEvent{
  135. ID: "alert-offline-living-1", Category: alerts.CatRouter, Urgent: true,
  136. Severity: "critical", Title: "Living offline", RouterID: "living", Time: "ahora mismo",
  137. })
  138. l.mu.Lock()
  139. l.resolveOfflineAlerts("patio")
  140. l.mu.Unlock()
  141. if list := l.engine.List(); len(list) != 1 || list[0].ID != "alert-offline-living-1" {
  142. t.Fatalf("la caída de living no debía tocarse: %+v", list)
  143. }
  144. }
  145. // Issue #846: mientras el incidente de offline está abierto no se re-emite
  146. // la alerta aunque el estado flapee (offline → online → offline), y la
  147. // recuperación hay que estabilizarla (offlineRecoverTicks éxitos seguidos)
  148. // antes de cerrar el incidente (borrar la caída + emitir "recuperado").
  149. func TestLiveRouterOfflineFlappingDoesNotRearm(t *testing.T) {
  150. l := liveTestLive()
  151. if err := l.engine.SetConfig(map[string]string{"router": "all"}); err != nil {
  152. t.Fatal(err)
  153. }
  154. cfg := &RouterConfig{ID: "patio", Name: "Patio", Host: "10.0.0.1"}
  155. errDown := fmt.Errorf("timeout")
  156. l.mu.Lock()
  157. l.trackRouterOffline(cfg, errDown, 2) // caída: primera alerta
  158. l.trackRouterOffline(cfg, errDown, 3) // sigue caído: NO re-emite
  159. l.mu.Unlock()
  160. if list := l.engine.List(); len(list) != 1 || !strings.HasPrefix(list[0].ID, "alert-offline-patio-") {
  161. t.Fatalf("un incidente = una alerta: %+v", list)
  162. }
  163. // Flap: éxitos aislados no cierran el incidente ni rearman.
  164. l.mu.Lock()
  165. l.trackRouterRecovered(cfg) // streak 1
  166. l.trackRouterRecovered(cfg) // streak 2
  167. l.trackRouterOffline(cfg, errDown, 2) // vuelve a caer: sin alerta nueva
  168. l.mu.Unlock()
  169. if list := l.engine.List(); len(list) != 1 || !strings.HasPrefix(list[0].ID, "alert-offline-patio-") {
  170. t.Fatalf("el flap no debía rearmar ni cerrar: %+v", list)
  171. }
  172. // Recuperación estable: offlineRecoverTicks éxitos seguidos cierran el
  173. // incidente: la caída se elimina y el "recuperado" queda como relevo.
  174. l.mu.Lock()
  175. l.trackRouterRecovered(cfg) // streak 3 → cierra
  176. l.mu.Unlock()
  177. list := l.engine.List()
  178. if len(list) != 1 || list[0].Type != alerts.TypeRouterRecovered {
  179. t.Fatalf("tras recuperación estable: %+v", list)
  180. }
  181. for _, ev := range list {
  182. if strings.HasPrefix(ev.ID, "alert-offline-") {
  183. t.Fatalf("la caída debía eliminarse: %+v", ev)
  184. }
  185. }
  186. }
  187. // Issue #846: cerrar un incidente y reabrirlo DENTRO de la ventana de dedup
  188. // (5 min, misma key cat|título|routerId) debe emitir la alerta nueva igual
  189. // (EmitNoDedup): al cerrar, la alerta anterior se retiró del feed y el dedup
  190. // dejaría el incidente nuevo invisible.
  191. func TestLiveRouterOfflineReopenWithinDedupWindow(t *testing.T) {
  192. l := liveTestLive()
  193. if err := l.engine.SetConfig(map[string]string{"router": "all"}); err != nil {
  194. t.Fatal(err)
  195. }
  196. cfg := &RouterConfig{ID: "patio", Name: "Patio", Host: "10.0.0.1"}
  197. errDown := fmt.Errorf("timeout")
  198. l.mu.Lock()
  199. l.trackRouterOffline(cfg, errDown, 2) // incidente A
  200. l.trackRouterRecovered(cfg) // streak 1
  201. l.trackRouterRecovered(cfg) // streak 2
  202. l.trackRouterRecovered(cfg) // streak 3 → cierra A
  203. l.mu.Unlock()
  204. if list := l.engine.List(); len(list) != 1 || list[0].Type != alerts.TypeRouterRecovered {
  205. t.Fatalf("tras el cierre solo queda el recuperado: %+v", list)
  206. }
  207. l.mu.Lock()
  208. l.trackRouterOffline(cfg, errDown, 2) // incidente B, misma dedup-key <5 min
  209. l.mu.Unlock()
  210. list := l.engine.List()
  211. offline := 0
  212. for _, ev := range list {
  213. if strings.HasPrefix(ev.ID, "alert-offline-") {
  214. offline++
  215. }
  216. }
  217. if offline != 1 {
  218. t.Fatalf("el incidente B debe tener exactamente 1 alerta offline, hay %d: %+v", offline, list)
  219. }
  220. }
  221. // Issue #846: tras un reinicio del servidor las alertas de offline de un
  222. // proceso anterior quedan huérfanas (el incidente vivía en memoria). Los
  223. // routers que responden SIN incidente abierto se reconcilian cada ciclo: la
  224. // huérfana se retira SIN evento "recuperado" (no se observó recuperación:
  225. // el servidor estaba caído, no el router). Los routers caídos conservan la
  226. // suya; los de incidente abierto también.
  227. func TestLiveRouterReconcileRemovesOrphan(t *testing.T) {
  228. l := liveTestLive()
  229. if err := l.engine.SetConfig(map[string]string{"router": "all"}); err != nil {
  230. t.Fatal(err)
  231. }
  232. // Huérfana "del proceso anterior" (misma shape que emite trackRouterOffline)
  233. // y una de OTRO router que no responde en este ciclo.
  234. l.engine.Emit(alerts.AlertEvent{
  235. ID: "alert-offline-patio-111", Category: alerts.CatRouter, Urgent: true,
  236. Severity: "critical", Title: "Patio offline", Type: alerts.TypeRouterOffline,
  237. RouterID: "patio",
  238. })
  239. l.engine.Emit(alerts.AlertEvent{
  240. ID: "alert-offline-living-222", Category: alerts.CatRouter, Urgent: true,
  241. Severity: "critical", Title: "Living offline", Type: alerts.TypeRouterOffline,
  242. RouterID: "living",
  243. })
  244. if n := len(l.engine.List()); n != 2 {
  245. t.Fatalf("previo: %d alertas", n)
  246. }
  247. l.mu.Lock()
  248. // Patio responde y SIN incidente abierto → su huérfana se retira.
  249. l.reconcileOfflineOrphans(map[string]*routerPolled{"patio": {}})
  250. l.mu.Unlock()
  251. list := l.engine.List()
  252. if len(list) != 1 || list[0].RouterID != "living" {
  253. t.Fatalf("solo la huérfana de living debe sobrevivir: %+v", list)
  254. }
  255. // Con incidente abierto NO se toca aunque responda: la alerta es la del
  256. // incidente vivo, no una huérfana.
  257. l.mu.Lock()
  258. if l.offlineOpen == nil {
  259. l.offlineOpen = map[string]bool{}
  260. }
  261. l.offlineOpen["living"] = true
  262. l.reconcileOfflineOrphans(map[string]*routerPolled{"living": {}})
  263. l.mu.Unlock()
  264. if list := l.engine.List(); len(list) != 1 || list[0].RouterID != "living" {
  265. t.Fatalf("con incidente abierto no se debe tocar: %+v", list)
  266. }
  267. }
  268. // Issue #846: al abrir un incidente con huérfanas previas (reinicio durante
  269. // la caída), la alerta nueva las sustituye: nunca dos alertas offline del
  270. // mismo router.
  271. func TestLiveRouterOfflineOpenReplacesOrphans(t *testing.T) {
  272. l := liveTestLive()
  273. if err := l.engine.SetConfig(map[string]string{"router": "all"}); err != nil {
  274. t.Fatal(err)
  275. }
  276. l.engine.Emit(alerts.AlertEvent{
  277. ID: "alert-offline-patio-111", Category: alerts.CatRouter, Urgent: true,
  278. Severity: "critical", Title: "Patio offline", Type: alerts.TypeRouterOffline,
  279. RouterID: "patio",
  280. })
  281. // Segunda huérfana con la misma key de dedup: solo entra sin dedup (es el
  282. // shape real tras reinicios seguidos durante una caída larga).
  283. l.engine.EmitNoDedup(alerts.AlertEvent{
  284. ID: "alert-offline-patio-222", Category: alerts.CatRouter, Urgent: true,
  285. Severity: "critical", Title: "Patio offline", Type: alerts.TypeRouterOffline,
  286. RouterID: "patio",
  287. })
  288. cfg := &RouterConfig{ID: "patio", Name: "Patio", Host: "10.0.0.1"}
  289. l.mu.Lock()
  290. l.trackRouterOffline(cfg, fmt.Errorf("timeout"), 2)
  291. l.mu.Unlock()
  292. list := l.engine.List()
  293. if len(list) != 1 {
  294. t.Fatalf("una sola alerta tras abrir el incidente: %+v", list)
  295. }
  296. if list[0].ID == "alert-offline-patio-111" || list[0].ID == "alert-offline-patio-222" {
  297. t.Fatalf("la alerta debe ser la del incidente nuevo, no una huérfana: %+v", list[0])
  298. }
  299. }
  300. func TestLiveWanDownTaxonomyAndDebounce(t *testing.T) {
  301. l := liveTestLive()
  302. cfg := &RouterConfig{ID: "flint2", Name: "Flint 2", Host: "192.168.8.1"}
  303. loss0, loss100 := 0.0, 100.0
  304. // 1er sondeo con 100 % pérdida: aún no alerta (debounce 2 como offline)
  305. l.mu.Lock()
  306. l.trackWanDown(cfg, &routerPolled{lossPct: &loss100})
  307. l.mu.Unlock()
  308. if len(l.engine.List()) != 0 {
  309. t.Fatal("WAN down no debía alertar al primer sondeo")
  310. }
  311. // 2º seguido: alerta internet/urgent/critical
  312. l.mu.Lock()
  313. l.trackWanDown(cfg, &routerPolled{lossPct: &loss100})
  314. l.mu.Unlock()
  315. list := l.engine.List()
  316. if len(list) != 1 {
  317. t.Fatalf("WAN down: %d alertas", len(list))
  318. }
  319. a := list[0]
  320. if a.Category != alerts.CatInternet || !a.Urgent || a.Severity != "critical" {
  321. t.Fatalf("WAN down: (%s,%v,%s), esperaba (internet,true,critical)", a.Category, a.Urgent, a.Severity)
  322. }
  323. // 3er sondeo: no re-alerta (estado ya "down"); el dedup también lo evita
  324. l.mu.Lock()
  325. l.trackWanDown(cfg, &routerPolled{lossPct: &loss100})
  326. l.mu.Unlock()
  327. if len(l.engine.List()) != 1 {
  328. t.Fatal("WAN down re-alertó sin recuperación")
  329. }
  330. // Recuperación: pérdida < 100 resetea (próxima caída vuelve a alertar)
  331. l.mu.Lock()
  332. l.trackWanDown(cfg, &routerPolled{lossPct: &loss0})
  333. l.mu.Unlock()
  334. if l.lastStatus["flint2:wan"] != "up" || l.wanDown["flint2"] != 0 {
  335. t.Fatalf("reset WAN: %v", l.lastStatus)
  336. }
  337. }
  338. func TestLiveUnknownDeviceTaxonomy(t *testing.T) {
  339. l := liveTestLive()
  340. l.mu.Lock()
  341. l.emitUnknownDevice(Device{MAC: "AA:BB:CC:DD:EE:FF", Name: "AA:BB:CC:DD:EE:FF", RouterID: "living", Online: true}, nil, nil)
  342. l.mu.Unlock()
  343. list := l.engine.List()
  344. if len(list) != 1 {
  345. t.Fatalf("desconocido: %d alertas", len(list))
  346. }
  347. a := list[0]
  348. // #772: la alerta de desconocido ES urgente para cruzar al Notifier
  349. // (push/ntfy/telegram); el nivel por categoría en Ajustes sigue
  350. // pudiendo silenciarla (clients=none). Antes de #772 era warn no urgente.
  351. if a.Category != alerts.CatClients || !a.Urgent || a.Severity != "warn" {
  352. t.Fatalf("desconocido: (%s,%v,%s), esperaba (clients,true,warn)", a.Category, a.Urgent, a.Severity)
  353. }
  354. if a.Vars["mac"] != "AA:BB:CC:DD:EE:FF" || a.Vars["router"] != "living" {
  355. t.Fatalf("vars incompletas: %+v", a.Vars)
  356. }
  357. }
  358. func TestLiveTrackUnknownDevices(t *testing.T) {
  359. l := liveTestLive()
  360. unknown := Device{MAC: "11:22:33:44:55:66", Name: "11:22:33:44:55:66", RouterID: "living", Online: true, Band: "5 GHz"}
  361. named := Device{MAC: "77:88:99:AA:BB:CC", Name: "Galaxy Tab", RouterID: "living", Online: true}
  362. // Primer ciclo: siembra de base, NUNCA alerta (anti-avalancha de arranque)
  363. l.trackUnknownDevices([]Device{unknown, named}, nil)
  364. if len(l.engine.List()) != 0 {
  365. t.Fatal("primer ciclo no debía alertar")
  366. }
  367. // Sigue online: no re-alerta
  368. l.trackUnknownDevices([]Device{unknown, named}, nil)
  369. if len(l.engine.List()) != 0 {
  370. t.Fatal("reconexión sin caída no debía alertar")
  371. }
  372. // Se desconecta y vuelve: la gracia de N ticks (issue #234) evita alertar
  373. // mientras el lease aún no se resuelve tras reconectar.
  374. l.trackUnknownDevices([]Device{named}, nil)
  375. l.trackUnknownDevices([]Device{unknown, named}, nil)
  376. if len(l.engine.List()) != 0 {
  377. t.Fatal("1 tick nameless no debía alertar (gracia)")
  378. }
  379. l.trackUnknownDevices([]Device{unknown, named}, nil)
  380. if len(l.engine.List()) != 0 {
  381. t.Fatal("2 ticks nameless no debían alertar (gracia)")
  382. }
  383. // Al tercer tick consecutivo online+sin nombre, el desconocido real alerta
  384. l.trackUnknownDevices([]Device{unknown, named}, nil)
  385. list := l.engine.List()
  386. if len(list) != 1 {
  387. t.Fatalf("desconocido tras gracia: %d alertas", len(list))
  388. }
  389. if list[0].Category != alerts.CatClients || !list[0].Urgent {
  390. t.Fatalf("taxonomía: %+v", list[0])
  391. }
  392. // Issue #248: la reconexión posterior de la MISMA MAC ya no alerta
  393. l.trackUnknownDevices([]Device{named}, nil)
  394. l.trackUnknownDevices([]Device{unknown, named}, nil)
  395. l.trackUnknownDevices([]Device{unknown, named}, nil)
  396. l.trackUnknownDevices([]Device{unknown, named}, nil)
  397. if len(l.engine.List()) != 1 {
  398. t.Fatal("memoria per-MAC (#248): no debía re-alertar")
  399. }
  400. // El dispositivo CON nombre nunca alerta aunque se reconecte
  401. l.trackUnknownDevices([]Device{unknown}, nil)
  402. l.trackUnknownDevices([]Device{unknown, named}, nil)
  403. if len(l.engine.List()) != 1 {
  404. t.Fatal("dispositivo conocido no debía alertar")
  405. }
  406. }
  407. // Issue #234: un dispositivo conocido cuyo lease DHCP tarda un par de ticks
  408. // en resolverse tras reconectar NO dispara la alerta de desconocido.
  409. func TestLiveTrackUnknownDevicesGraciaConocido(t *testing.T) {
  410. l := liveTestLive()
  411. d := Device{MAC: "77:88:99:AA:BB:CC", Name: "77:88:99:AA:BB:CC", RouterID: "living", Online: true, Band: "5 GHz"}
  412. // Siembra; desconexión; reconexión SIN lease resuelto durante 2 ticks…
  413. l.trackUnknownDevices([]Device{d}, nil)
  414. l.trackUnknownDevices([]Device{}, nil)
  415. l.trackUnknownDevices([]Device{d}, nil) // tick 1 sin nombre
  416. l.trackUnknownDevices([]Device{d}, nil) // tick 2 sin nombre
  417. if len(l.engine.List()) != 0 {
  418. t.Fatal("no debía alertar antes de resolver el lease")
  419. }
  420. // …y al tercer tick el lease ya está (Name != MAC) → nunca llega al umbral
  421. d.Name = "Galaxy Tab"
  422. l.trackUnknownDevices([]Device{d}, nil)
  423. if len(l.engine.List()) != 0 {
  424. t.Fatal("con hostname resuelto no debía alertar")
  425. }
  426. // La gracia se reseteó al ver el nombre: una reconexión futura sin nombre
  427. // parte de cero y vuelve a necesitar los N ticks completos (no 1).
  428. l.trackUnknownDevices([]Device{}, nil)
  429. l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true, Band: "5 GHz"}}, nil)
  430. if len(l.engine.List()) != 0 {
  431. t.Fatal("tras reset, tick 1 no debía alertar")
  432. }
  433. l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true, Band: "5 GHz"}}, nil)
  434. if len(l.engine.List()) != 0 {
  435. t.Fatal("tras reset, tick 2 no debía alertar")
  436. }
  437. l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true, Band: "5 GHz"}}, nil)
  438. if len(l.engine.List()) != 1 {
  439. t.Fatalf("tras reset y gracia completa: %d alertas", len(l.engine.List()))
  440. }
  441. }
  442. // Issue #248: la memoria per-MAC es PERSISTENTE (kv) y sobrevive a un reinicio
  443. // del servidor: una MAC que ya alertó no vuelve a alertar en un proceso nuevo.
  444. func TestLiveUnknownDeviceMemoryPersisted(t *testing.T) {
  445. d := openLiveTestDB(t)
  446. l := NewLive(nil, d, nil, nil)
  447. mac := "AA:BB:CC:DD:EE:0F"
  448. unknown := Device{MAC: mac, Name: mac, RouterID: "living", Online: true, Band: "5 GHz"}
  449. // Reconexión simulada: siembra, caída, vuelve → tras la gracia alerta.
  450. l.trackUnknownDevices([]Device{unknown}, nil)
  451. l.trackUnknownDevices([]Device{}, nil)
  452. l.trackUnknownDevices([]Device{unknown}, nil)
  453. l.trackUnknownDevices([]Device{unknown}, nil)
  454. l.trackUnknownDevices([]Device{unknown}, nil)
  455. if len(l.engine.List()) != 1 {
  456. t.Fatalf("primera alerta: %d", len(l.engine.List()))
  457. }
  458. // "Reinicio": un Live nuevo sobre la MISMA BD carga la memoria persistida.
  459. l2 := NewLive(nil, d, nil, nil)
  460. if !l2.unknownAlerted[mac] {
  461. t.Fatal("la memoria per-MAC no se cargó desde kv")
  462. }
  463. l2.trackUnknownDevices([]Device{unknown}, nil)
  464. l2.trackUnknownDevices([]Device{}, nil)
  465. l2.trackUnknownDevices([]Device{unknown}, nil)
  466. l2.trackUnknownDevices([]Device{unknown}, nil)
  467. l2.trackUnknownDevices([]Device{unknown}, nil)
  468. // #798: el log de alertas sobrevive al reinicio, así que la alerta
  469. // histórica sigue visible; lo que no debe pasar es que se EMITA una nueva.
  470. if len(l2.engine.List()) != 1 {
  471. t.Fatalf("tras reinicio no debía re-alertar (memoria persistida); historial=%d", len(l2.engine.List()))
  472. }
  473. }
  474. func TestLiveTrackUnknownDevicesTrustedAllowlist(t *testing.T) {
  475. l := liveTestLive()
  476. l.db = openLiveTestDB(t) // allowlist en BD real
  477. trusted := Device{MAC: "A4:7E:FA:65:0C:AA", Name: "A4:7E:FA:65:0C:AA", RouterID: "living", Online: true}
  478. if err := l.db.UpsertKnownMac(db.KnownMac{MAC: "A4:7E:FA:65:0C:AA", Name: "Withings"}); err != nil {
  479. t.Fatal(err)
  480. }
  481. // Primer ciclo siembra; desconexión; reconexión: la MAC de la allowlist
  482. // NUNCA alerta, aunque siga sin nombre/lease (issue #196).
  483. l.trackUnknownDevices([]Device{trusted}, nil)
  484. l.trackUnknownDevices([]Device{}, nil)
  485. l.trackUnknownDevices([]Device{trusted}, nil)
  486. if len(l.engine.List()) != 0 {
  487. t.Fatalf("MAC confiable alertó: %d", len(l.engine.List()))
  488. }
  489. }
  490. // #772: dismiss ("dejar como anónimo") silencia la alerta de desconocido para
  491. // la MAC: aunque complete la gracia de ticks, nunca alerta.
  492. func TestLiveDismissUnknownDevice(t *testing.T) {
  493. l := liveTestLive()
  494. unknown := Device{MAC: "11:22:33:44:55:66", Name: "11:22:33:44:55:66", RouterID: "living", Online: true}
  495. l.DismissUnknownDevice("11:22:33:44:55:66")
  496. for i := 0; i < 5; i++ {
  497. l.trackUnknownDevices([]Device{unknown}, nil)
  498. }
  499. if len(l.engine.List()) != 0 {
  500. t.Fatal("dismiss (#772): la MAC no debía alertar")
  501. }
  502. // MAC inválida: no-op sin pánico.
  503. l.DismissUnknownDevice("no-es-una-mac")
  504. }
  505. // Issue #1818: una MAC sin nombre que solo está en una FDB (bridge, AP o
  506. // switch) no alerta. El NMRP de Netgear publica direcciones así mientras la
  507. // unidad reinicia para flashear, y no hay ningún host detrás. En cuanto
  508. // aparece una prueba real (IP resuelta, wireless o LLDP) sí alerta.
  509. func TestLiveTrackUnknownDevicesIgnoresFdbOnlyMac(t *testing.T) {
  510. l := liveTestLive()
  511. fdbOnly := Device{MAC: "D2:95:DE:65:C5:B0", Name: "D2:95:DE:65:C5:B0", RouterID: "living", Online: true, Port: "lan3"}
  512. l.trackUnknownDevices([]Device{fdbOnly}, nil) // siembra
  513. l.trackUnknownDevices([]Device{}, nil) // la MAC parpadea en la FDB
  514. for i := 0; i < 6; i++ {
  515. l.trackUnknownDevices([]Device{fdbOnly}, nil)
  516. }
  517. if got := len(l.engine.List()); got != 0 {
  518. t.Fatalf("MAC solo-FDB no debía alertar: %d alertas", got)
  519. }
  520. if _, ok := l.unknownGrace[fdbOnly.MAC]; ok {
  521. t.Fatal("la MAC solo-FDB no debía acumular gracia")
  522. }
  523. // La misma MAC con una prueba real (asociación wireless) sí alerta.
  524. withEvidence := fdbOnly
  525. withEvidence.Band = "5 GHz"
  526. l.trackUnknownDevices([]Device{}, nil)
  527. for i := 0; i < 3; i++ {
  528. l.trackUnknownDevices([]Device{withEvidence}, nil)
  529. }
  530. if got := len(l.engine.List()); got != 1 {
  531. t.Fatalf("con evidencia wireless debía alertar: %d alertas", got)
  532. }
  533. }
  534. func TestUnknownDeviceHasEvidence(t *testing.T) {
  535. cases := []struct {
  536. name string
  537. d Device
  538. want bool
  539. }{
  540. {"ip", Device{IP: "192.168.1.50"}, true},
  541. {"wireless", Device{Band: "2.4 GHz"}, true},
  542. {"lldp", Device{Lldp: &LldpInfo{}}, true},
  543. {"fdb-only", Device{Port: "lan3", Band: "cable"}, false},
  544. {"dash-band", Device{Band: "—"}, false},
  545. {"empty", Device{}, false},
  546. }
  547. for _, c := range cases {
  548. if got := unknownDeviceHasEvidence(c.d); got != c.want {
  549. t.Errorf("%s: got %v, want %v", c.name, got, c.want)
  550. }
  551. }
  552. }