rtlconsole_test.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // rtlconsole_test.go — #639: sondeo HTTP de la consola RTLPlayground.
  2. // El test levanta un httptest que emula el firmware (login por POST /login
  3. // con Set-Cookie session, /information.json con sw_ver/hw_ver, /cmd time con
  4. // el contador en hex) y verifica fetch/snapshot/attach contra él.
  5. package httpapi
  6. import (
  7. "fmt"
  8. "net/http"
  9. "net/http/httptest"
  10. "strings"
  11. "sync/atomic"
  12. "testing"
  13. "time"
  14. "github.com/gnacho/netpulse/agent/probe"
  15. "github.com/gnacho/netpulse/server-go/internal/config"
  16. "github.com/gnacho/netpulse/server-go/internal/db"
  17. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  18. )
  19. // srvRequests cuenta las peticiones que recibe el servidor fake de consola
  20. // (issue #863: con el toggle OFF no debe recibir NINGUNA).
  21. var srvRequests int32
  22. // newRTLConsoleServer: emula la consola RTLPlayground. uptimeSec es el valor
  23. // que devuelve /cmd time (en segundos); el servidor lo convierte a "0x…".
  24. func newRTLConsoleServer(t *testing.T, uptimeSec uint64) *httptest.Server {
  25. t.Helper()
  26. atomic.StoreInt32(&srvRequests, 0)
  27. mux := http.NewServeMux()
  28. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  29. atomic.AddInt32(&srvRequests, 1)
  30. })
  31. mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
  32. if err := r.ParseForm(); err != nil || r.Form.Get("pwd") != "1234" {
  33. http.Error(w, "bad", http.StatusUnauthorized)
  34. return
  35. }
  36. w.Header().Set("Set-Cookie", "session=test-session-abc; SameSite=Strict")
  37. w.Header().Set("Location", "index.html")
  38. w.WriteHeader(http.StatusFound)
  39. })
  40. mux.HandleFunc("/information.json", func(w http.ResponseWriter, r *http.Request) {
  41. if !strings.Contains(r.Header.Get("Cookie"), "session=") {
  42. http.Error(w, "no auth", http.StatusUnauthorized)
  43. return
  44. }
  45. w.Header().Set("Content-Type", "application/json")
  46. fmt.Fprintf(w, `{"sw_ver":"v0.1.0-e1fa080-dirty","hw_ver":"keepLink KP-9000-9XHML-X V3.1","mac_address":"78:d8:00:32:31:49"}`)
  47. })
  48. mux.HandleFunc("/cmd", func(w http.ResponseWriter, r *http.Request) {
  49. if !strings.Contains(r.Header.Get("Cookie"), "session=") {
  50. http.Error(w, "no auth", http.StatusUnauthorized)
  51. return
  52. }
  53. // El firmware exige Content-Type en todo POST (sin él responde 404).
  54. if r.Header.Get("Content-Type") == "" {
  55. http.Error(w, "no content type", http.StatusNotFound)
  56. return
  57. }
  58. body := make([]byte, 32)
  59. n, _ := r.Body.Read(body)
  60. if strings.TrimSpace(string(body[:n])) != "time" {
  61. http.Error(w, "unknown command", http.StatusBadRequest)
  62. return
  63. }
  64. fmt.Fprintf(w, "0x%08x\n", uptimeSec)
  65. })
  66. return httptest.NewServer(mux)
  67. }
  68. func TestRtlConsoleFetch(t *testing.T) {
  69. srv := newRTLConsoleServer(t, 167581) // ~46.5 h
  70. defer srv.Close()
  71. host := strings.TrimPrefix(srv.URL, "http://")
  72. c := newRtlConsoleCache("1234", 300)
  73. e, err := c.fetch(host)
  74. if err != nil {
  75. t.Fatalf("fetch: %v", err)
  76. }
  77. if e.Firmware != "v0.1.0-e1fa080-dirty" {
  78. t.Fatalf("Firmware = %q, esperaba v0.1.0-e1fa080-dirty", e.Firmware)
  79. }
  80. if e.Model != "keepLink KP-9000-9XHML-X V3.1" {
  81. t.Fatalf("Model = %q", e.Model)
  82. }
  83. if e.MAC != "78:d8:00:32:31:49" {
  84. t.Fatalf("MAC = %q, esperaba 78:d8:00:32:31:49", e.MAC)
  85. }
  86. // bootUnix ≈ now - 167581s
  87. age := time.Since(e.BootUnix)
  88. if age < 167580*time.Second || age > 167582*time.Second {
  89. t.Fatalf("BootUnix no cuadra con uptime 167581s: age=%v", age)
  90. }
  91. }
  92. func TestRtlConsoleSnapshotAttachesSystem(t *testing.T) {
  93. srv := newRTLConsoleServer(t, 3600)
  94. defer srv.Close()
  95. host := strings.TrimPrefix(srv.URL, "http://")
  96. c := newRtlConsoleCache("1234", 300)
  97. // snapshot dispara el poll en background; esperamos a que haya datos.
  98. var e *rtlConsoleEntry
  99. deadline := time.Now().Add(3 * time.Second)
  100. for time.Now().Before(deadline) {
  101. e = c.snapshot("switch16", host)
  102. if e != nil {
  103. break
  104. }
  105. time.Sleep(50 * time.Millisecond)
  106. }
  107. if e == nil {
  108. t.Fatal("snapshot no produjo datos en 3 s")
  109. }
  110. // attach sobre un payload de beacon: System debe llevar board+uptime.
  111. s := &server{rtlConsole: c}
  112. pl := &probe.Payload{Data: probe.PayloadData{}}
  113. s.attachRTLConsole("switch16", host, pl)
  114. if pl.Data.System == nil {
  115. t.Fatal("attach no adjuntó System")
  116. }
  117. if pl.Data.System.Board == nil || pl.Data.System.Board.Release.Description != "RTLPlayground v0.1.0-e1fa080-dirty" {
  118. t.Fatalf("Board inesperado: %+v", pl.Data.System.Board)
  119. }
  120. // uptime derivado ≈ 1h (3600 s) ± margen del poll.
  121. if pl.Data.System.SysInfo == nil || pl.Data.System.SysInfo.Uptime < 3590 || pl.Data.System.SysInfo.Uptime > 3700 {
  122. t.Fatalf("Uptime inesperado: %+v", pl.Data.System.SysInfo)
  123. }
  124. // BridgeMAC normalizada a mayúsculas (formato canónico del resto de la app).
  125. if pl.Data.System.BridgeMAC != "78:D8:00:32:31:49" {
  126. t.Fatalf("BridgeMAC = %q, esperaba 78:D8:00:32:31:49", pl.Data.System.BridgeMAC)
  127. }
  128. }
  129. func TestRtlConsoleInvalidaTrasReboot(t *testing.T) {
  130. srv := newRTLConsoleServer(t, 3600)
  131. defer srv.Close()
  132. host := strings.TrimPrefix(srv.URL, "http://")
  133. c := newRtlConsoleCache("1234", 300)
  134. var e *rtlConsoleEntry
  135. deadline := time.Now().Add(3 * time.Second)
  136. for time.Now().Before(deadline) {
  137. e = c.snapshot("switch16", host)
  138. if e != nil {
  139. break
  140. }
  141. time.Sleep(50 * time.Millisecond)
  142. }
  143. if e == nil {
  144. t.Fatal("snapshot inicial sin datos")
  145. }
  146. c.invalidate("switch16")
  147. c.mu.Lock()
  148. polledAt := c.byID["switch16"].PolledAt
  149. c.mu.Unlock()
  150. if !polledAt.IsZero() {
  151. t.Fatalf("invalidate no reseteó PolledAt: %v", polledAt)
  152. }
  153. }
  154. func TestRtlConsoleFetchLoginFalloNoAdjunta(t *testing.T) {
  155. // El servidor rechaza el login (pass distinta): fetch devuelve error.
  156. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  157. w.WriteHeader(http.StatusUnauthorized)
  158. }))
  159. defer srv.Close()
  160. host := strings.TrimPrefix(srv.URL, "http://")
  161. c := newRtlConsoleCache("1234", 300)
  162. if _, err := c.fetch(host); err == nil {
  163. t.Fatal("fetch debería fallar con login 401")
  164. }
  165. }
  166. // #785: el parser de uptime debe aceptar el formato nuevo (Tick/Sec counter)
  167. // además del hex plano legado.
  168. func TestParseTimeUptimeFormats(t *testing.T) {
  169. cases := []struct {
  170. name string
  171. body string
  172. want uint64
  173. }{
  174. {"legado hex con 0x", "0x00028e9d\n", 0x28e9d},
  175. {"legado hex sin prefijo", "00028e9d", 0x28e9d},
  176. {"nuevo dos líneas (KP-9000 v0.1.0-ad9e2ee)", " Tick counter: 0x0244599a Sec Counter: 0x0002e6d0\n", 0x2e6d0},
  177. {"nuevo con saltos de línea", "Tick counter: 0x0244599a\nSec Counter: 0x0002e6d0\n", 0x2e6d0},
  178. {"nuevo sec counter sin 0x", "Tick counter: 0x99 Sec Counter: 2e6d0", 0x2e6d0},
  179. }
  180. for _, tc := range cases {
  181. got, err := parseTimeUptime(tc.body)
  182. if err != nil {
  183. t.Fatalf("%s: %v", tc.name, err)
  184. }
  185. if got != tc.want {
  186. t.Fatalf("%s: uptime = %#x, want %#x", tc.name, got, tc.want)
  187. }
  188. }
  189. for _, bad := range []string{"", "garbage", "Tick counter: 0x1", "Sec Counter: zz"} {
  190. if _, err := parseTimeUptime(bad); err == nil {
  191. t.Fatalf("entrada inválida %q no devolvió error", bad)
  192. }
  193. }
  194. }
  195. // #863: con el toggle de sondeo por consola DESACTIVADO para el router, el
  196. // attach no consulta la consola (cero requests al firmware: cada login tumba
  197. // la sesión humana) y no inyecta System. Con el toggle activo (default) el
  198. // comportamiento es el de siempre.
  199. func TestRtlConsoleTogglePorRouter(t *testing.T) {
  200. srv := newRTLConsoleServer(t, 3600)
  201. defer srv.Close()
  202. host := strings.TrimPrefix(srv.URL, "http://")
  203. cfg := &config.Config{DataDir: t.TempDir(), AuthUser: "admin", AuthPass: "test12345678"}
  204. d, err := db.Open(cfg.DataDir)
  205. if err != nil {
  206. t.Fatalf("db: %v", err)
  207. }
  208. off := false
  209. on := true
  210. if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
  211. Name: "switch-off", Host: host, Type: "managed-switch", ConsolePolling: &off,
  212. }); err != nil {
  213. t.Fatalf("add switch-off: %v", err)
  214. }
  215. if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
  216. Name: "switch-on", Host: host, Type: "managed-switch", ConsolePolling: &on,
  217. }); err != nil {
  218. t.Fatalf("add switch-on: %v", err)
  219. }
  220. // Un tercer router heredado: columna a DEFAULT 1 (alta sin el campo).
  221. if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
  222. Name: "switch-legacy", Host: host, Type: "managed-switch",
  223. }); err != nil {
  224. t.Fatalf("add switch-legacy: %v", err)
  225. }
  226. c := newRtlConsoleCache("1234", 300)
  227. s := &server{rtlConsole: c, db: d}
  228. // OFF: el attach no toca la consola ni inyecta System.
  229. plOff := &probe.Payload{Data: probe.PayloadData{}}
  230. s.attachRTLConsole("switch-off", host, plOff)
  231. if plOff.Data.System != nil {
  232. t.Fatalf("toggle OFF inyectó System: %+v", plOff.Data.System)
  233. }
  234. if got := atomic.LoadInt32(&srvRequests); got != 0 {
  235. t.Fatalf("toggle OFF hizo %d requests a la consola, esperaba 0", got)
  236. }
  237. // ON explícito: inyecta System como siempre.
  238. plOn := &probe.Payload{Data: probe.PayloadData{}}
  239. s.attachRTLConsole("switch-on", host, plOn)
  240. deadline := time.Now().Add(3 * time.Second)
  241. for plOn.Data.System == nil && time.Now().Before(deadline) {
  242. s.attachRTLConsole("switch-on", host, plOn)
  243. time.Sleep(50 * time.Millisecond)
  244. }
  245. if plOn.Data.System == nil {
  246. t.Fatal("toggle ON no inyectó System")
  247. }
  248. // Legacy (DEFAULT 1): también inyecta.
  249. plLegacy := &probe.Payload{Data: probe.PayloadData{}}
  250. s.attachRTLConsole("switch-legacy", host, plLegacy)
  251. deadline = time.Now().Add(3 * time.Second)
  252. for plLegacy.Data.System == nil && time.Now().Before(deadline) {
  253. s.attachRTLConsole("switch-legacy", host, plLegacy)
  254. time.Sleep(50 * time.Millisecond)
  255. }
  256. if plLegacy.Data.System == nil {
  257. t.Fatal("router legacy (default ON) no inyectó System")
  258. }
  259. }