4
0

firmware_owut_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. // #1769: el download del flujo por pasos propaga removePackages a owut -r,
  195. // igual que el one-shot; sin eso ASU rechaza routers con paquetes de
  196. // terceros y el paso final se queda sin imagen.
  197. func TestOwutDownloadEndpointPassesRemovePackages(t *testing.T) {
  198. ssh := &scriptedSSH{rules: []sshRule{
  199. {contains: "command -v owut", out: "__owut__\n"},
  200. {contains: "owut download", out: "Downloading image to /tmp/firmware.bin\n__owut_exit__=0\n"},
  201. }}
  202. ts, rid := makeOwutTestServer(t, ssh)
  203. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  204. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-download",
  205. `{"targetVersion":"25.12.6","removePackages":["netgrip"]}`, cookie)
  206. body := readJSON(t, res)
  207. if res.StatusCode != 200 {
  208. t.Fatalf("status %d: %v", res.StatusCode, body)
  209. }
  210. if !ssh.saw("owut download -r 'netgrip'") {
  211. t.Fatalf("comando lanzado: %v", ssh.cmdsSnapshot())
  212. }
  213. }
  214. // #1769: instalar sin imagen previa no entra en la máquina de estados:
  215. // 422 con código accionable y ningún upgrade creado.
  216. func TestOwutInstallImageRequiresDownloadedImage(t *testing.T) {
  217. ssh := &scriptedSSH{rules: []sshRule{
  218. {contains: "command -v owut", out: "__owut__\n"},
  219. {contains: "test -s /tmp/firmware.bin", err: errors.New("exit 1")},
  220. }}
  221. ts, rid := makeOwutTestServer(t, ssh)
  222. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  223. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install-image", `{}`, cookie)
  224. body := readJSON(t, res)
  225. if res.StatusCode != http.StatusPreconditionFailed {
  226. t.Fatalf("status %d: %v", res.StatusCode, body)
  227. }
  228. errObj, _ := body["error"].(string)
  229. if errObj != "owut_no_image" {
  230. t.Fatalf("error: %v", body)
  231. }
  232. deadline := time.Now().Add(2 * time.Second)
  233. for time.Now().Before(deadline) {
  234. res := getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
  235. for _, it := range readJSONArray(t, res) {
  236. m, _ := it.(map[string]any)
  237. if m["routerId"] == rid {
  238. if up, ok := m["upgrade"].(map[string]any); ok {
  239. t.Fatalf("no debió crearse ningún upgrade: %v", up)
  240. }
  241. }
  242. }
  243. time.Sleep(50 * time.Millisecond)
  244. }
  245. }
  246. func TestRecurrencePutGetDelete(t *testing.T) {
  247. ts, rid := makeOwutTestServer(t, nil)
  248. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  249. // weekly válido.
  250. res := putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  251. `{"enabled":true,"kind":"weekly","dayOfWeek":5,"time":"04:00"}`, cookie)
  252. if res.StatusCode != 200 {
  253. t.Fatalf("PUT weekly: %d %v", res.StatusCode, readJSON(t, res))
  254. }
  255. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  256. body := readJSON(t, res)
  257. rc, _ := body["recurrence"].(map[string]any)
  258. if rc["kind"] != "weekly" || rc["enabled"] != true {
  259. t.Fatalf("GET recurrence: %v", body)
  260. }
  261. if _, ok := body["nextRunMs"]; !ok {
  262. t.Fatalf("GET recurrence debe traer nextRunMs: %v", body)
  263. }
  264. // weekly sin time: 400.
  265. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  266. `{"enabled":true,"kind":"weekly","dayOfWeek":5}`, cookie)
  267. if res.StatusCode != 400 {
  268. t.Fatalf("PUT inválido: %d, esperaba 400", res.StatusCode)
  269. }
  270. // monthly y once válidos.
  271. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  272. `{"enabled":true,"kind":"monthly","dayOfMonth":1,"time":"05:30"}`, cookie)
  273. if res.StatusCode != 200 {
  274. t.Fatalf("PUT monthly: %d", res.StatusCode)
  275. }
  276. future := time.Now().Add(48 * time.Hour).UnixMilli()
  277. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  278. fmt.Sprintf(`{"enabled":true,"kind":"once","atMs":%d}`, future), cookie)
  279. if res.StatusCode != 200 {
  280. t.Fatalf("PUT once: %d", res.StatusCode)
  281. }
  282. // DELETE desactiva.
  283. res = deleteJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  284. if res.StatusCode != 200 {
  285. t.Fatalf("DELETE: %d", res.StatusCode)
  286. }
  287. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  288. body = readJSON(t, res)
  289. rc, _ = body["recurrence"].(map[string]any)
  290. if rc["enabled"] != false {
  291. t.Fatalf("tras DELETE debe quedar disabled: %v", body)
  292. }
  293. }
  294. func TestOwutEndpointsBlockedForVendorFirmware(t *testing.T) {
  295. // GL.iNet: la plataforma devuelve __gl__ -> install y upgrade 422, y el
  296. // listado de versiones llega con vendorFirmware y sin sondear ASU.
  297. ssh := &scriptedSSH{rules: []sshRule{
  298. {contains: "fw.gl-inet.com", out: "__gl__\n"},
  299. }}
  300. ts, rid := makeOwutTestServer(t, ssh)
  301. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  302. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
  303. if res.StatusCode != 422 {
  304. t.Fatalf("install status %d, esperaba 422 vendor_firmware", res.StatusCode)
  305. }
  306. res = postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
  307. if res.StatusCode != 422 {
  308. t.Fatalf("upgrade status %d, esperaba 422 vendor_firmware", res.StatusCode)
  309. }
  310. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
  311. body := readJSON(t, res)
  312. if body["vendorFirmware"] != "gl-inet" {
  313. t.Fatalf("vendorFirmware: %v", body["vendorFirmware"])
  314. }
  315. if versions, _ := body["versions"].([]any); len(versions) != 0 {
  316. t.Fatalf("vendor no debe listar versiones: %v", versions)
  317. }
  318. if ssh.saw("owut versions") {
  319. t.Fatalf("vendor no debe sondear versiones ASU: %v", ssh.cmdsSnapshot())
  320. }
  321. }
  322. func TestTargetSaveWithoutURL(t *testing.T) {
  323. // #761: con owut la imagen la construye ASU; el target se guarda sin URL.
  324. ts, rid := makeOwutTestServer(t, nil)
  325. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  326. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/target",
  327. `{"model":"redmi_ax6","currentVersion":"25.12.5","targetVersion":"25.12.5"}`, cookie)
  328. if res.StatusCode != 200 {
  329. t.Fatalf("guardar sin targetUrl: %d %v", res.StatusCode, readJSON(t, res))
  330. }
  331. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
  332. for _, it := range readJSONArray(t, res) {
  333. m, _ := it.(map[string]any)
  334. if m["routerId"] == rid && m["targetVersion"] != "25.12.5" {
  335. t.Fatalf("target no persistió: %v", m)
  336. }
  337. }
  338. }