firmware_owut_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. // #1978: sin config UCI donde escribir, el flag -r sigue siendo la única vía
  226. // de excluir paquetes. El fallback no puede perderse.
  227. func TestOwutDownloadEndpointFallsBackToRemoveFlag(t *testing.T) {
  228. ssh := &scriptedSSH{rules: []sshRule{
  229. {contains: "command -v owut", out: "__owut__\n"},
  230. {contains: "uci show attendedsysupgrade.owut.remove", err: errors.New("uci: not found")},
  231. {contains: "owut download", out: "Downloading image to /tmp/firmware.bin\n__owut_exit__=0\n"},
  232. }}
  233. ts, rid := makeOwutTestServer(t, ssh)
  234. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  235. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-download",
  236. `{"targetVersion":"25.12.6","removePackages":["netgrip"]}`, cookie)
  237. if res.StatusCode != 200 {
  238. t.Fatalf("status %d: %v", res.StatusCode, readJSON(t, res))
  239. }
  240. if !ssh.saw("owut download -r 'netgrip'") {
  241. t.Fatalf("sin UCI debe conservar -r: %v", ssh.cmdsSnapshot())
  242. }
  243. }
  244. // #1769: instalar sin imagen previa no entra en la máquina de estados:
  245. // 422 con código accionable y ningún upgrade creado.
  246. func TestOwutInstallImageRequiresDownloadedImage(t *testing.T) {
  247. ssh := &scriptedSSH{rules: []sshRule{
  248. {contains: "command -v owut", out: "__owut__\n"},
  249. {contains: "test -s /tmp/firmware.bin", err: errors.New("exit 1")},
  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-install-image", `{}`, cookie)
  254. body := readJSON(t, res)
  255. if res.StatusCode != http.StatusPreconditionFailed {
  256. t.Fatalf("status %d: %v", res.StatusCode, body)
  257. }
  258. errObj, _ := body["error"].(string)
  259. if errObj != "owut_no_image" {
  260. t.Fatalf("error: %v", body)
  261. }
  262. deadline := time.Now().Add(2 * time.Second)
  263. for time.Now().Before(deadline) {
  264. res := getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
  265. for _, it := range readJSONArray(t, res) {
  266. m, _ := it.(map[string]any)
  267. if m["routerId"] == rid {
  268. if up, ok := m["upgrade"].(map[string]any); ok {
  269. t.Fatalf("no debió crearse ningún upgrade: %v", up)
  270. }
  271. }
  272. }
  273. time.Sleep(50 * time.Millisecond)
  274. }
  275. }
  276. func TestRecurrencePutGetDelete(t *testing.T) {
  277. ts, rid := makeOwutTestServer(t, nil)
  278. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  279. // weekly válido.
  280. res := putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  281. `{"enabled":true,"kind":"weekly","dayOfWeek":5,"time":"04:00"}`, cookie)
  282. if res.StatusCode != 200 {
  283. t.Fatalf("PUT weekly: %d %v", res.StatusCode, readJSON(t, res))
  284. }
  285. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  286. body := readJSON(t, res)
  287. rc, _ := body["recurrence"].(map[string]any)
  288. if rc["kind"] != "weekly" || rc["enabled"] != true {
  289. t.Fatalf("GET recurrence: %v", body)
  290. }
  291. if _, ok := body["nextRunMs"]; !ok {
  292. t.Fatalf("GET recurrence debe traer nextRunMs: %v", body)
  293. }
  294. // weekly sin time: 400.
  295. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  296. `{"enabled":true,"kind":"weekly","dayOfWeek":5}`, cookie)
  297. if res.StatusCode != 400 {
  298. t.Fatalf("PUT inválido: %d, esperaba 400", res.StatusCode)
  299. }
  300. // monthly y once válidos.
  301. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  302. `{"enabled":true,"kind":"monthly","dayOfMonth":1,"time":"05:30"}`, cookie)
  303. if res.StatusCode != 200 {
  304. t.Fatalf("PUT monthly: %d", res.StatusCode)
  305. }
  306. future := time.Now().Add(48 * time.Hour).UnixMilli()
  307. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  308. fmt.Sprintf(`{"enabled":true,"kind":"once","atMs":%d}`, future), cookie)
  309. if res.StatusCode != 200 {
  310. t.Fatalf("PUT once: %d", res.StatusCode)
  311. }
  312. // DELETE desactiva.
  313. res = deleteJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  314. if res.StatusCode != 200 {
  315. t.Fatalf("DELETE: %d", res.StatusCode)
  316. }
  317. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  318. body = readJSON(t, res)
  319. rc, _ = body["recurrence"].(map[string]any)
  320. if rc["enabled"] != false {
  321. t.Fatalf("tras DELETE debe quedar disabled: %v", body)
  322. }
  323. }
  324. func TestOwutEndpointsBlockedForVendorFirmware(t *testing.T) {
  325. // GL.iNet: la plataforma devuelve __gl__ -> install y upgrade 422, y el
  326. // listado de versiones llega con vendorFirmware y sin sondear ASU.
  327. ssh := &scriptedSSH{rules: []sshRule{
  328. {contains: "fw.gl-inet.com", out: "__gl__\n"},
  329. }}
  330. ts, rid := makeOwutTestServer(t, ssh)
  331. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  332. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
  333. if res.StatusCode != 422 {
  334. t.Fatalf("install status %d, esperaba 422 vendor_firmware", res.StatusCode)
  335. }
  336. res = postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
  337. if res.StatusCode != 422 {
  338. t.Fatalf("upgrade status %d, esperaba 422 vendor_firmware", res.StatusCode)
  339. }
  340. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
  341. body := readJSON(t, res)
  342. if body["vendorFirmware"] != "gl-inet" {
  343. t.Fatalf("vendorFirmware: %v", body["vendorFirmware"])
  344. }
  345. if versions, _ := body["versions"].([]any); len(versions) != 0 {
  346. t.Fatalf("vendor no debe listar versiones: %v", versions)
  347. }
  348. if ssh.saw("owut versions") {
  349. t.Fatalf("vendor no debe sondear versiones ASU: %v", ssh.cmdsSnapshot())
  350. }
  351. }
  352. func TestTargetSaveWithoutURL(t *testing.T) {
  353. // #761: con owut la imagen la construye ASU; el target se guarda sin URL.
  354. ts, rid := makeOwutTestServer(t, nil)
  355. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  356. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/target",
  357. `{"model":"redmi_ax6","currentVersion":"25.12.5","targetVersion":"25.12.5"}`, cookie)
  358. if res.StatusCode != 200 {
  359. t.Fatalf("guardar sin targetUrl: %d %v", res.StatusCode, readJSON(t, res))
  360. }
  361. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
  362. for _, it := range readJSONArray(t, res) {
  363. m, _ := it.(map[string]any)
  364. if m["routerId"] == rid && m["targetVersion"] != "25.12.5" {
  365. t.Fatalf("target no persistió: %v", m)
  366. }
  367. }
  368. }