firmware_owut_internal_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // firmware_owut_internal_test.go - tests internos (package httpapi) del
  2. // disparo recurrente: idempotencia cuando la versión instalada coincide con
  3. // el target, y autodesactivación con config inválida (#761).
  4. package httpapi
  5. import (
  6. "errors"
  7. "strings"
  8. "sync"
  9. "testing"
  10. "time"
  11. "github.com/gnacho/netpulse/server-go/internal/adapters"
  12. "github.com/gnacho/netpulse/server-go/internal/auth"
  13. "github.com/gnacho/netpulse/server-go/internal/config"
  14. "github.com/gnacho/netpulse/server-go/internal/db"
  15. "github.com/gnacho/netpulse/server-go/internal/firmware"
  16. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  17. "github.com/gnacho/netpulse/server-go/internal/sse"
  18. )
  19. // recFakeSSH registra comandos y responde owut instalado (para el camino
  20. // owut del disparo) sin tocar ningún router real.
  21. type recFakeSSH struct {
  22. mu sync.Mutex
  23. cmds []string
  24. }
  25. func (f *recFakeSSH) Run(host, cmd string, _ time.Duration) (string, error) {
  26. f.mu.Lock()
  27. defer f.mu.Unlock()
  28. f.cmds = append(f.cmds, cmd)
  29. if strings.Contains(cmd, "command -v owut") {
  30. return "__owut__\n", nil
  31. }
  32. if strings.Contains(cmd, "owut upgrade") {
  33. return "There are no changes to upgrade\n__owut_exit__=0\n", nil
  34. }
  35. return "", nil
  36. }
  37. func (f *recFakeSSH) saw(substr string) bool {
  38. f.mu.Lock()
  39. defer f.mu.Unlock()
  40. for _, c := range f.cmds {
  41. if strings.Contains(c, substr) {
  42. return true
  43. }
  44. }
  45. return false
  46. }
  47. // makeRecServer monta un server mínimo (sin HTTP) con la BD, el store de
  48. // firmware, el pool fake y el hook de versión instalada.
  49. func makeRecServer(t *testing.T, installed string) (*server, string, *recFakeSSH) {
  50. t.Helper()
  51. dataDir := t.TempDir()
  52. cfg, err := config.Load(map[string]string{
  53. "AUTH_USER": "admin", "AUTH_PASS": "test123456",
  54. "DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
  55. }, dataDir)
  56. if err != nil {
  57. t.Fatalf("config: %v", err)
  58. }
  59. d, err := db.Open(dataDir)
  60. if err != nil {
  61. t.Fatalf("db: %v", err)
  62. }
  63. t.Cleanup(func() { d.Close() })
  64. secret, err := auth.EnsureSessionSecret(d, cfg)
  65. if err != nil {
  66. t.Fatalf("secret: %v", err)
  67. }
  68. if err := auth.EnsureUsers(d, cfg); err != nil {
  69. t.Fatalf("users: %v", err)
  70. }
  71. r, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
  72. Name: "RecRouter", Host: "192.168.1.60", Type: "openwrt",
  73. })
  74. if err != nil {
  75. t.Fatalf("add router: %v", err)
  76. }
  77. pool := &recFakeSSH{}
  78. s := &server{
  79. cfg: cfg, db: d, adapter: nil,
  80. hub: sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
  81. secret: secret, pool: pool,
  82. firmware: firmware.NewStore(d.DB),
  83. firmwareEngine: firmware.NewEngine(firmware.NewStore(d.DB), nil),
  84. }
  85. s.boardVersionFn = func(string) string { return installed }
  86. return s, r.ID, pool
  87. }
  88. func TestRunRecurrenceShotNoOpWhenUpToDate(t *testing.T) {
  89. s, rid, pool := makeRecServer(t, "25.12.5")
  90. if err := s.firmware.SetTarget(firmware.Target{
  91. RouterID: rid, Model: "x", CurrentVersion: "25.12.5",
  92. TargetVersion: "25.12.5", TargetURL: "http://x/i.bin",
  93. }); err != nil {
  94. t.Fatalf("target: %v", err)
  95. }
  96. if err := firmware.SaveRecurrence(s.db.DB, rid, firmware.Recurrence{
  97. Enabled: true, Kind: firmware.RecurrenceWeekly, DayOfWeek: func() *int { v := 0; return &v }(), Time: "00:00",
  98. }); err != nil {
  99. t.Fatalf("recurrence: %v", err)
  100. }
  101. s.runRecurrenceShot(rid)
  102. if pool.saw("owut upgrade") {
  103. t.Fatalf("al día no debe flashear: %v", pool.cmds)
  104. }
  105. if got := firmware.LoadRecurrence(s.db.DB, rid).LastRunMs; got == 0 {
  106. t.Fatalf("lastRun debe quedar marcado tras el disparo")
  107. }
  108. }
  109. func TestRunRecurrenceShotDisablesWithoutTarget(t *testing.T) {
  110. s, rid, _ := makeRecServer(t, "25.12.5")
  111. if err := firmware.SaveRecurrence(s.db.DB, rid, firmware.Recurrence{
  112. Enabled: true, Kind: firmware.RecurrenceWeekly, DayOfWeek: func() *int { v := 1; return &v }(), Time: "00:00",
  113. }); err != nil {
  114. t.Fatalf("recurrence: %v", err)
  115. }
  116. s.runRecurrenceShot(rid)
  117. if firmware.LoadRecurrence(s.db.DB, rid).Enabled {
  118. t.Fatalf("sin target guardado la recurrencia debe autodesactivarse")
  119. }
  120. }
  121. func TestRunRecurrenceShotLaunchesOwutWhenOutdated(t *testing.T) {
  122. s, rid, pool := makeRecServer(t, "25.12.5")
  123. if err := s.firmware.SetTarget(firmware.Target{
  124. RouterID: rid, Model: "x", CurrentVersion: "25.12.5",
  125. TargetVersion: "25.12.7", TargetURL: "",
  126. }); err != nil {
  127. t.Fatalf("target: %v", err)
  128. }
  129. if err := firmware.SaveRecurrence(s.db.DB, rid, firmware.Recurrence{
  130. Enabled: true, Kind: firmware.RecurrenceWeekly, DayOfWeek: func() *int { v := 2; return &v }(), Time: "00:00",
  131. }); err != nil {
  132. t.Fatalf("recurrence: %v", err)
  133. }
  134. s.runRecurrenceShot(rid)
  135. // El upgrade corre en goroutine: esperar a que el comando llegue al fake.
  136. deadline := time.Now().Add(2 * time.Second)
  137. for time.Now().Before(deadline) {
  138. if pool.saw("owut upgrade -q -V '25.12.7'") {
  139. if got := firmware.LoadRecurrence(s.db.DB, rid).LastRunMs; got == 0 {
  140. t.Fatalf("lastRun debe quedar marcado tras el disparo")
  141. }
  142. return
  143. }
  144. time.Sleep(20 * time.Millisecond)
  145. }
  146. t.Fatalf("desfasado debe lanzar owut upgrade -V 25.12.7: %v", pool.cmds)
  147. }
  148. // rebootFakeSSH (#1771): variante del fake que simula el corte de sesión SSH
  149. // de un flash real: el comando muere con error dejando la salida de owut a
  150. // medias. El resto de comandos (detección, preserve-stack) responde vacío.
  151. type rebootFakeSSH struct {
  152. recFakeSSH
  153. installOut string
  154. installErr error
  155. upgradeOut string
  156. upgradeErr error
  157. }
  158. func (f *rebootFakeSSH) Run(host, cmd string, _ time.Duration) (string, error) {
  159. f.mu.Lock()
  160. defer f.mu.Unlock()
  161. f.cmds = append(f.cmds, cmd)
  162. switch {
  163. case strings.Contains(cmd, "owut install"):
  164. return f.installOut, f.installErr
  165. case strings.Contains(cmd, "owut upgrade"):
  166. if f.upgradeOut != "" || f.upgradeErr != nil {
  167. return f.upgradeOut, f.upgradeErr
  168. }
  169. return "There are no changes to upgrade\n__owut_exit__=0\n", nil
  170. case strings.Contains(cmd, "command -v owut"):
  171. return "__owut__\n", nil
  172. }
  173. return "", nil
  174. }
  175. // staticBoardAdapter: adapter mínimo que reporta siempre la misma versión de
  176. // board info (lo que haría el router tras completar el flash). El embedding
  177. // de Demo cubre el resto del interfaz Snapshotter: estos tests solo llegan a
  178. // BoardInfoFor vía detectedFirmwareVersion.
  179. type staticBoardAdapter struct {
  180. *adapters.Demo
  181. version string
  182. }
  183. func (a *staticBoardAdapter) BoardInfoFor(string) *adapters.BoardInfo {
  184. return &adapters.BoardInfo{Release: struct {
  185. Version string `json:"version"`
  186. Description string `json:"description"`
  187. Target string `json:"target"`
  188. }{Version: a.version}}
  189. }
  190. // shortenOwutRebootTimers: gracia y sondeo cortos para no alargar los tests.
  191. func shortenOwutRebootTimers(t *testing.T) {
  192. t.Helper()
  193. oldGrace, oldPoll := owutRebootGrace, owutRebootPoll
  194. owutRebootGrace = 2 * time.Second
  195. owutRebootPoll = 50 * time.Millisecond
  196. t.Cleanup(func() { owutRebootGrace, owutRebootPoll = oldGrace, oldPoll })
  197. }
  198. // waitUpgradeStatus sondea el store hasta que el upgrade llega a uno de los
  199. // estados pedidos (el flash corre en goroutine en el flujo real; aquí las
  200. // llamadas son directas, pero awaitReboot sondea con su timer).
  201. func waitUpgradeStatus(t *testing.T, s *server, id int64, want ...string) *firmware.Upgrade {
  202. t.Helper()
  203. deadline := time.Now().Add(5 * time.Second)
  204. for time.Now().Before(deadline) {
  205. if up, err := s.firmware.GetUpgradeByID(id); err == nil && up != nil {
  206. for _, w := range want {
  207. if up.Status == w {
  208. return up
  209. }
  210. }
  211. }
  212. time.Sleep(20 * time.Millisecond)
  213. }
  214. up, _ := s.firmware.GetUpgradeByID(id)
  215. t.Fatalf("upgrade %d no llegó a %v: %+v", id, want, up)
  216. return nil
  217. }
  218. // #1771: "Installing ... and rebooting..." con la sesión SSH muerta termina
  219. // en done, no en failed, aunque el flash muera antes de owutSSHMinRun
  220. // (install por pasos).
  221. func TestOwutInstallRebootLineGoesToDone(t *testing.T) {
  222. shortenOwutRebootTimers(t)
  223. s, rid, _ := makeRecServer(t, "25.12.5")
  224. re := &rebootFakeSSH{
  225. installOut: "Installing /tmp/firmware.bin and rebooting...\n",
  226. installErr: errors.New("ssh: session closed"),
  227. }
  228. s.pool = re
  229. s.adapter = &staticBoardAdapter{version: "25.12.6"}
  230. id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
  231. if err != nil {
  232. t.Fatalf("begin: %v", err)
  233. }
  234. s.runOwutInstallImage(id, rid, "192.168.1.60", "25.12.6")
  235. up := waitUpgradeStatus(t, s, id, "done")
  236. if up.Status != "done" {
  237. t.Fatalf("status = %q (%q), esperaba done", up.Status, up.Error)
  238. }
  239. if !re.saw("owut install") {
  240. t.Fatalf("el fake no vio owut install: %v", re.cmds)
  241. }
  242. }
  243. // #1771: mismo caso en el one-shot `owut upgrade`.
  244. func TestOwutUpgradeRebootLineGoesToDone(t *testing.T) {
  245. shortenOwutRebootTimers(t)
  246. s, rid, _ := makeRecServer(t, "25.12.5")
  247. re := &rebootFakeSSH{
  248. upgradeOut: "Installing /tmp/firmware.bin and rebooting...\n",
  249. upgradeErr: errors.New("ssh: session closed"),
  250. }
  251. s.pool = re
  252. s.adapter = &staticBoardAdapter{version: "25.12.6"}
  253. id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
  254. if err != nil {
  255. t.Fatalf("begin: %v", err)
  256. }
  257. s.runOwutUpgrade(id, rid, "192.168.1.60", "25.12.6", "manual", nil)
  258. waitUpgradeStatus(t, s, id, "done")
  259. }
  260. // #1771: al reiniciar, la sesión SSH puede cerrar LIMPIA (err nil) y sin el
  261. // marcador __owut_exit__ (el shell muere antes del printf): la línea de
  262. // reboot debe clasificar flash en curso, no "terminó sin flashear".
  263. func TestOwutInstallCleanCloseGoesToDone(t *testing.T) {
  264. shortenOwutRebootTimers(t)
  265. s, rid, _ := makeRecServer(t, "25.12.5")
  266. re := &rebootFakeSSH{
  267. installOut: "Installing /tmp/firmware.bin and rebooting...\n",
  268. }
  269. s.pool = re
  270. s.adapter = &staticBoardAdapter{version: "25.12.6"}
  271. id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
  272. if err != nil {
  273. t.Fatalf("begin: %v", err)
  274. }
  275. s.runOwutInstallImage(id, rid, "192.168.1.60", "25.12.6")
  276. up := waitUpgradeStatus(t, s, id, "done")
  277. if up.Status != "done" {
  278. t.Fatalf("status = %q (%q), esperaba done", up.Status, up.Error)
  279. }
  280. }
  281. // El caso opuesto (sesión limpia, sin línea de reboot) sigue siendo el
  282. // no-op "terminó sin flashear".
  283. func TestOwutInstallCleanCloseWithoutRebootStillNoOp(t *testing.T) {
  284. shortenOwutRebootTimers(t)
  285. s, rid, _ := makeRecServer(t, "25.12.5")
  286. re := &rebootFakeSSH{
  287. installOut: "Image verifier: /tmp/firmware.bin OK\n",
  288. }
  289. s.pool = re
  290. s.adapter = &staticBoardAdapter{version: "25.12.5"}
  291. id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
  292. if err != nil {
  293. t.Fatalf("begin: %v", err)
  294. }
  295. s.runOwutInstallImage(id, rid, "192.168.1.60", "25.12.6")
  296. up := waitUpgradeStatus(t, s, id, "failed")
  297. if !strings.Contains(up.Error, "Image verifier") {
  298. t.Fatalf("error = %q, esperaba la salida cruda del no-op", up.Error)
  299. }
  300. }
  301. // Un error real (sin línea de reboot) sigue clasificando failed, con el
  302. // texto accionable de #1769 cuando el motivo es la imagen ausente.
  303. func TestOwutInstallRealErrorStillFailed(t *testing.T) {
  304. shortenOwutRebootTimers(t)
  305. s, rid, _ := makeRecServer(t, "25.12.5")
  306. re := &rebootFakeSSH{
  307. installOut: "sysupgrade: ERROR: Image file '/tmp/firmware.bin' does not exist\n",
  308. installErr: errors.New("exit status 1"),
  309. }
  310. s.pool = re
  311. s.adapter = &staticBoardAdapter{version: "25.12.5"}
  312. id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
  313. if err != nil {
  314. t.Fatalf("begin: %v", err)
  315. }
  316. s.runOwutInstallImage(id, rid, "192.168.1.60", "25.12.6")
  317. up := waitUpgradeStatus(t, s, id, "failed")
  318. if !strings.Contains(up.Error, "No hay imagen descargada") {
  319. t.Fatalf("error = %q, esperaba el texto accionable de #1769", up.Error)
  320. }
  321. }
  322. // #1771: sin target en memoria, el cambio de versión reportado por el board
  323. // info también confirma el flash (v != from).
  324. func TestOwutInstallNoTargetStillDoneWhenVersionChanges(t *testing.T) {
  325. shortenOwutRebootTimers(t)
  326. s, rid, _ := makeRecServer(t, "25.12.5")
  327. re := &rebootFakeSSH{
  328. installOut: "Installing /tmp/firmware.bin and rebooting...\n",
  329. installErr: errors.New("ssh: session closed"),
  330. }
  331. s.pool = re
  332. s.adapter = &staticBoardAdapter{version: "25.12.6"}
  333. id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
  334. if err != nil {
  335. t.Fatalf("begin: %v", err)
  336. }
  337. s.runOwutInstallImage(id, rid, "192.168.1.60", "")
  338. waitUpgradeStatus(t, s, id, "done")
  339. }