firmware_owut_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. // firmware_owut_test.go - contrato HTTP del ciclo owut completo (#761):
  2. // lista de versiones, instalación, upgrade desatendido y recurrencia.
  3. package httpapi_test
  4. import (
  5. "bytes"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strings"
  11. "testing"
  12. "time"
  13. )
  14. // owutVersionsSample replica `owut versions` (salida real recortada).
  15. const owutVersionsSample = `Available 'version-to' values from https://sysupgrade.openwrt.org:
  16. 24.10 release branch
  17. 24.10.0
  18. 24.10.2 (latest)
  19. 25.12 release branch
  20. 25.12.5
  21. 25.12.7 (latest)
  22. `
  23. func reqJSON(t *testing.T, method, base, path, payload, cookie string) *http.Response {
  24. t.Helper()
  25. var body io.Reader
  26. if payload != "" {
  27. body = bytes.NewBufferString(payload)
  28. }
  29. req, err := http.NewRequest(method, base+path, body)
  30. if err != nil {
  31. t.Fatalf("new request: %v", err)
  32. }
  33. req.Header.Set("Content-Type", "application/json")
  34. if cookie != "" {
  35. req.Header.Set("Cookie", "session="+cookie)
  36. }
  37. res, err := http.DefaultClient.Do(req)
  38. if err != nil {
  39. t.Fatalf("do: %v", err)
  40. }
  41. return res
  42. }
  43. func getJSONPath(t *testing.T, base, path, cookie string) *http.Response {
  44. return reqJSON(t, http.MethodGet, base, path, "", cookie)
  45. }
  46. func putJSONPath(t *testing.T, base, path, payload, cookie string) *http.Response {
  47. return reqJSON(t, http.MethodPut, base, path, payload, cookie)
  48. }
  49. func deleteJSONPath(t *testing.T, base, path, cookie string) *http.Response {
  50. return reqJSON(t, http.MethodDelete, base, path, "", cookie)
  51. }
  52. func TestOwutVersionsEndpoint(t *testing.T) {
  53. ssh := &scriptedSSH{rules: []sshRule{
  54. {contains: "command -v owut", out: "__owut__\n"},
  55. {contains: "owut versions", out: owutVersionsSample},
  56. }}
  57. ts, rid := makeOwutTestServer(t, ssh)
  58. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  59. res := getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
  60. body := readJSON(t, res)
  61. if res.StatusCode != 200 {
  62. t.Fatalf("status %d: %v", res.StatusCode, body)
  63. }
  64. if body["owutAvailable"] != true {
  65. t.Fatalf("owutAvailable: %v", body["owutAvailable"])
  66. }
  67. versions, _ := body["versions"].([]any)
  68. if len(versions) != 4 {
  69. t.Fatalf("esperaba 4 versiones, got %v", versions)
  70. }
  71. }
  72. func TestOwutVersionsEndpointWithoutOwut(t *testing.T) {
  73. ssh := &scriptedSSH{rules: []sshRule{
  74. {contains: "command -v owut", out: "\n"}, // PATH sin owut
  75. }}
  76. ts, rid := makeOwutTestServer(t, ssh)
  77. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  78. res := getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
  79. body := readJSON(t, res)
  80. if res.StatusCode != 200 {
  81. t.Fatalf("status %d: %v", res.StatusCode, body)
  82. }
  83. if body["owutAvailable"] != false {
  84. t.Fatalf("owutAvailable: %v", body["owutAvailable"])
  85. }
  86. if versions, _ := body["versions"].([]any); len(versions) != 0 {
  87. t.Fatalf("sin owut no hay versiones: %v", versions)
  88. }
  89. if ssh.saw("owut versions") {
  90. t.Fatalf("no debe lanzarse owut versions sin owut: %v", ssh.cmdsSnapshot())
  91. }
  92. }
  93. func TestOwutInstallEndpoint(t *testing.T) {
  94. ssh := &scriptedSSH{rules: []sshRule{
  95. {contains: "apk add owut", out: "OK: 1 installed\n__owut_exit__=0\n"},
  96. }}
  97. ts, rid := makeOwutTestServer(t, ssh)
  98. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  99. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
  100. body := readJSON(t, res)
  101. if res.StatusCode != 200 {
  102. t.Fatalf("status %d: %v", res.StatusCode, body)
  103. }
  104. if body["ok"] != true {
  105. t.Fatalf("ok: %v", body)
  106. }
  107. if !ssh.saw("apk add owut") {
  108. t.Fatalf("no se lanzó la instalación: %v", ssh.cmdsSnapshot())
  109. }
  110. }
  111. func TestOwutInstallEndpointNoPackageManager(t *testing.T) {
  112. ssh := &scriptedSSH{rules: []sshRule{
  113. {contains: "apk update", out: "__no_pm__\n__owut_exit__=0\n"},
  114. }}
  115. ts, rid := makeOwutTestServer(t, ssh)
  116. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  117. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
  118. if res.StatusCode != 500 {
  119. t.Fatalf("status %d, esperaba 500", res.StatusCode)
  120. }
  121. }
  122. // waitForUpgradeStatus polea la lista hasta que el upgrade llegue al estado
  123. // terminal (la goroutine del server corre en background).
  124. func waitForUpgradeStatus(t *testing.T, ts *testServer, rid, want, cookie string) map[string]any {
  125. t.Helper()
  126. deadline := time.Now().Add(5 * time.Second)
  127. for time.Now().Before(deadline) {
  128. res := getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
  129. for _, it := range readJSONArray(t, res) {
  130. m, _ := it.(map[string]any)
  131. if m["routerId"] != rid {
  132. continue
  133. }
  134. if up, ok := m["upgrade"].(map[string]any); ok && up["status"] == want {
  135. return up
  136. }
  137. }
  138. time.Sleep(50 * time.Millisecond)
  139. }
  140. t.Fatalf("el upgrade no llegó a %s", want)
  141. return nil
  142. }
  143. func TestOwutUpgradeEndpointNoChanges(t *testing.T) {
  144. ssh := &scriptedSSH{rules: []sshRule{
  145. {contains: "command -v owut", out: "__owut__\n"},
  146. {contains: "owut upgrade", out: "There are no changes to upgrade (see '--force')\n__owut_exit__=0\n"},
  147. }}
  148. ts, rid := makeOwutTestServer(t, ssh)
  149. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  150. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
  151. body := readJSON(t, res)
  152. if res.StatusCode != 202 {
  153. t.Fatalf("status %d: %v", res.StatusCode, body)
  154. }
  155. if body["engine"] != "owut" {
  156. t.Fatalf("engine: %v", body["engine"])
  157. }
  158. up := waitForUpgradeStatus(t, ts, rid, "done", cookie)
  159. if up["engine"] != "owut" {
  160. t.Fatalf("engine del upgrade: %v", up["engine"])
  161. }
  162. if !ssh.saw("owut upgrade -q") {
  163. t.Fatalf("comando lanzado: %v", ssh.cmdsSnapshot())
  164. }
  165. // #761: antes de flashear se preserva el stack en /etc/sysupgrade.conf.
  166. if !ssh.saw("/etc/sysupgrade.conf") {
  167. t.Fatalf("preserve-stack no se ejecutó: %v", ssh.cmdsSnapshot())
  168. }
  169. }
  170. func TestOwutUpgradeEndpointFailure(t *testing.T) {
  171. ssh := &scriptedSSH{rules: []sshRule{
  172. {contains: "command -v owut", out: "__owut__\n"},
  173. {contains: "owut upgrade", out: "Update checks reveal errors, can't proceed\n__owut_exit__=1\n"},
  174. }}
  175. ts, rid := makeOwutTestServer(t, ssh)
  176. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  177. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
  178. if res.StatusCode != 202 {
  179. t.Fatalf("status %d", res.StatusCode)
  180. }
  181. up := waitForUpgradeStatus(t, ts, rid, "failed", cookie)
  182. if msg, _ := up["error"].(string); !strings.Contains(msg, "can't proceed") {
  183. t.Fatalf("error del upgrade: %v", up["error"])
  184. }
  185. }
  186. func TestOwutUpgradeRequiresTarget(t *testing.T) {
  187. ts, rid := makeOwutTestServer(t, nil)
  188. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  189. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{}`, cookie)
  190. if res.StatusCode != 400 {
  191. t.Fatalf("status %d, esperaba 400 sin targetVersion", res.StatusCode)
  192. }
  193. }
  194. // #1978: la lista de exclusión vive en la config UCI del router, que owut lee
  195. // como si fuera un argumento. El comando NO debe repetirla con -r o owut
  196. // aborta con "may only be used once per invocation".
  197. func TestOwutDownloadEndpointPutsRemovePackagesInUCINotInFlag(t *testing.T) {
  198. ssh := &scriptedSSH{rules: []sshRule{
  199. {contains: "command -v owut", out: "__owut__\n"},
  200. {contains: "uci show attendedsysupgrade.owut.remove", out: "attendedsysupgrade.owut.remove='netgrip'\n"},
  201. {contains: "owut download", out: "Downloading image to /tmp/firmware.bin\n__owut_exit__=0\n"},
  202. }}
  203. ts, rid := makeOwutTestServer(t, ssh)
  204. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  205. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-download",
  206. `{"targetVersion":"25.12.6","removePackages":["netgrip"]}`, cookie)
  207. body := readJSON(t, res)
  208. if res.StatusCode != 200 {
  209. t.Fatalf("status %d: %v", res.StatusCode, body)
  210. }
  211. if ssh.saw("owut download -r") {
  212. t.Fatalf("el -r repite la opción que ya está en UCI: %v", ssh.cmdsSnapshot())
  213. }
  214. if !ssh.saw("owut download") {
  215. t.Fatalf("no se lanzó el download: %v", ssh.cmdsSnapshot())
  216. }
  217. // #1978: el comando ejecutado viaja en la respuesta para el admin.
  218. if cmd, _ := body["command"].(string); !strings.Contains(cmd, "owut download") {
  219. t.Fatalf("la respuesta no lleva el comando: %v", body)
  220. }
  221. if out, _ := body["output"].(string); !strings.HasPrefix(out, "$ owut download") {
  222. t.Fatalf("la salida no empieza por el comando: %q", out)
  223. }
  224. }
  225. func TestOwutDownloadOutlivesWriteTimeout(t *testing.T) {
  226. const sshDelay = time.Second
  227. ssh := &scriptedSSH{rules: []sshRule{
  228. {contains: "command -v owut", out: "__owut__\n"},
  229. {contains: "owut download", delay: sshDelay, out: "Downloading image to /tmp/firmware.bin\n__owut_exit__=0\n"},
  230. }}
  231. ts, rid := makeOwutTestServer(t, ssh, 500*time.Millisecond)
  232. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  233. started := time.Now()
  234. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-download", `{"targetVersion":"25.12.6"}`, cookie)
  235. body := readJSON(t, res)
  236. if res.StatusCode != 200 {
  237. t.Fatalf("status %d: %v", res.StatusCode, body)
  238. }
  239. if elapsed := time.Since(started); elapsed < sshDelay {
  240. t.Fatalf("server responded before the simulated command finished: %s", elapsed)
  241. }
  242. if out, _ := body["output"].(string); !strings.Contains(out, "Downloading image") {
  243. t.Fatalf("missing full command output: %v", body)
  244. }
  245. }
  246. func TestOwutDownloadErrorIncludesFullOutput(t *testing.T) {
  247. ssh := &scriptedSSH{rules: []sshRule{
  248. {contains: "command -v owut", out: "__owut__\n"},
  249. {contains: "owut download", out: "Build request started\nASU build failed\n__owut_exit__=1\n"},
  250. }}
  251. ts, rid := makeOwutTestServer(t, ssh)
  252. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  253. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-download", `{"targetVersion":"25.12.6"}`, cookie)
  254. body := readJSON(t, res)
  255. if res.StatusCode != http.StatusBadGateway {
  256. t.Fatalf("status %d: %v", res.StatusCode, body)
  257. }
  258. out, _ := body["output"].(string)
  259. if !strings.HasPrefix(out, "$ owut download") || !strings.Contains(out, "Build request started") || !strings.Contains(out, "ASU build failed") {
  260. t.Fatalf("error response misses full output: %v", body)
  261. }
  262. if cmd, _ := body["command"].(string); !strings.Contains(cmd, "owut download") {
  263. t.Fatalf("error response misses command: %v", body)
  264. }
  265. }
  266. // #1978: sin config UCI donde escribir, el flag -r sigue siendo la única vía
  267. // de excluir paquetes. El fallback no puede perderse.
  268. func TestOwutDownloadEndpointFallsBackToRemoveFlag(t *testing.T) {
  269. ssh := &scriptedSSH{rules: []sshRule{
  270. {contains: "command -v owut", out: "__owut__\n"},
  271. {contains: "uci show attendedsysupgrade.owut.remove", err: errors.New("uci: not found")},
  272. {contains: "owut download", out: "Downloading image to /tmp/firmware.bin\n__owut_exit__=0\n"},
  273. }}
  274. ts, rid := makeOwutTestServer(t, ssh)
  275. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  276. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-download",
  277. `{"targetVersion":"25.12.6","removePackages":["netgrip"]}`, cookie)
  278. if res.StatusCode != 200 {
  279. t.Fatalf("status %d: %v", res.StatusCode, readJSON(t, res))
  280. }
  281. if !ssh.saw("owut download -r 'netgrip'") {
  282. t.Fatalf("sin UCI debe conservar -r: %v", ssh.cmdsSnapshot())
  283. }
  284. }
  285. // #1769: instalar sin imagen previa no entra en la máquina de estados:
  286. // 422 con código accionable y ningún upgrade creado.
  287. func TestOwutInstallImageRequiresDownloadedImage(t *testing.T) {
  288. ssh := &scriptedSSH{rules: []sshRule{
  289. {contains: "command -v owut", out: "__owut__\n"},
  290. {contains: "test -s /tmp/firmware.bin", err: errors.New("exit 1")},
  291. }}
  292. ts, rid := makeOwutTestServer(t, ssh)
  293. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  294. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install-image", `{}`, cookie)
  295. body := readJSON(t, res)
  296. if res.StatusCode != http.StatusPreconditionFailed {
  297. t.Fatalf("status %d: %v", res.StatusCode, body)
  298. }
  299. errObj, _ := body["error"].(string)
  300. if errObj != "owut_no_image" {
  301. t.Fatalf("error: %v", body)
  302. }
  303. deadline := time.Now().Add(2 * time.Second)
  304. for time.Now().Before(deadline) {
  305. res := getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
  306. for _, it := range readJSONArray(t, res) {
  307. m, _ := it.(map[string]any)
  308. if m["routerId"] == rid {
  309. if up, ok := m["upgrade"].(map[string]any); ok {
  310. t.Fatalf("no debió crearse ningún upgrade: %v", up)
  311. }
  312. }
  313. }
  314. time.Sleep(50 * time.Millisecond)
  315. }
  316. }
  317. func TestRecurrencePutGetDelete(t *testing.T) {
  318. ts, rid := makeOwutTestServer(t, nil)
  319. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  320. // weekly válido.
  321. res := putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  322. `{"enabled":true,"kind":"weekly","dayOfWeek":5,"time":"04:00"}`, cookie)
  323. if res.StatusCode != 200 {
  324. t.Fatalf("PUT weekly: %d %v", res.StatusCode, readJSON(t, res))
  325. }
  326. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  327. body := readJSON(t, res)
  328. rc, _ := body["recurrence"].(map[string]any)
  329. if rc["kind"] != "weekly" || rc["enabled"] != true {
  330. t.Fatalf("GET recurrence: %v", body)
  331. }
  332. if _, ok := body["nextRunMs"]; !ok {
  333. t.Fatalf("GET recurrence debe traer nextRunMs: %v", body)
  334. }
  335. // weekly sin time: 400.
  336. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  337. `{"enabled":true,"kind":"weekly","dayOfWeek":5}`, cookie)
  338. if res.StatusCode != 400 {
  339. t.Fatalf("PUT inválido: %d, esperaba 400", res.StatusCode)
  340. }
  341. // monthly y once válidos.
  342. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  343. `{"enabled":true,"kind":"monthly","dayOfMonth":1,"time":"05:30"}`, cookie)
  344. if res.StatusCode != 200 {
  345. t.Fatalf("PUT monthly: %d", res.StatusCode)
  346. }
  347. future := time.Now().Add(48 * time.Hour).UnixMilli()
  348. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  349. fmt.Sprintf(`{"enabled":true,"kind":"once","atMs":%d}`, future), cookie)
  350. if res.StatusCode != 200 {
  351. t.Fatalf("PUT once: %d", res.StatusCode)
  352. }
  353. // DELETE desactiva.
  354. res = deleteJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  355. if res.StatusCode != 200 {
  356. t.Fatalf("DELETE: %d", res.StatusCode)
  357. }
  358. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  359. body = readJSON(t, res)
  360. rc, _ = body["recurrence"].(map[string]any)
  361. if rc["enabled"] != false {
  362. t.Fatalf("tras DELETE debe quedar disabled: %v", body)
  363. }
  364. }
  365. func TestOwutEndpointsBlockedForVendorFirmware(t *testing.T) {
  366. // GL.iNet: la plataforma devuelve __gl__ -> install y upgrade 422, y el
  367. // listado de versiones llega con vendorFirmware y sin sondear ASU.
  368. ssh := &scriptedSSH{rules: []sshRule{
  369. {contains: "fw.gl-inet.com", out: "__gl__\n"},
  370. }}
  371. ts, rid := makeOwutTestServer(t, ssh)
  372. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  373. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
  374. if res.StatusCode != 422 {
  375. t.Fatalf("install status %d, esperaba 422 vendor_firmware", res.StatusCode)
  376. }
  377. res = postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
  378. if res.StatusCode != 422 {
  379. t.Fatalf("upgrade status %d, esperaba 422 vendor_firmware", res.StatusCode)
  380. }
  381. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
  382. body := readJSON(t, res)
  383. if body["vendorFirmware"] != "gl-inet" {
  384. t.Fatalf("vendorFirmware: %v", body["vendorFirmware"])
  385. }
  386. if versions, _ := body["versions"].([]any); len(versions) != 0 {
  387. t.Fatalf("vendor no debe listar versiones: %v", versions)
  388. }
  389. if ssh.saw("owut versions") {
  390. t.Fatalf("vendor no debe sondear versiones ASU: %v", ssh.cmdsSnapshot())
  391. }
  392. }
  393. func TestTargetSaveWithoutURL(t *testing.T) {
  394. // #761: con owut la imagen la construye ASU; el target se guarda sin URL.
  395. ts, rid := makeOwutTestServer(t, nil)
  396. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  397. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/target",
  398. `{"model":"redmi_ax6","currentVersion":"25.12.5","targetVersion":"25.12.5"}`, cookie)
  399. if res.StatusCode != 200 {
  400. t.Fatalf("guardar sin targetUrl: %d %v", res.StatusCode, readJSON(t, res))
  401. }
  402. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
  403. for _, it := range readJSONArray(t, res) {
  404. m, _ := it.(map[string]any)
  405. if m["routerId"] == rid && m["targetVersion"] != "25.12.5" {
  406. t.Fatalf("target no persistió: %v", m)
  407. }
  408. }
  409. }