firmware_owut_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. "fmt"
  7. "io"
  8. "net/http"
  9. "strings"
  10. "testing"
  11. "time"
  12. )
  13. // owutVersionsSample replica `owut versions` (salida real recortada).
  14. const owutVersionsSample = `Available 'version-to' values from https://sysupgrade.openwrt.org:
  15. 24.10 release branch
  16. 24.10.0
  17. 24.10.2 (latest)
  18. 25.12 release branch
  19. 25.12.5
  20. 25.12.7 (latest)
  21. `
  22. func reqJSON(t *testing.T, method, base, path, payload, cookie string) *http.Response {
  23. t.Helper()
  24. var body io.Reader
  25. if payload != "" {
  26. body = bytes.NewBufferString(payload)
  27. }
  28. req, err := http.NewRequest(method, base+path, body)
  29. if err != nil {
  30. t.Fatalf("new request: %v", err)
  31. }
  32. req.Header.Set("Content-Type", "application/json")
  33. if cookie != "" {
  34. req.Header.Set("Cookie", "session="+cookie)
  35. }
  36. res, err := http.DefaultClient.Do(req)
  37. if err != nil {
  38. t.Fatalf("do: %v", err)
  39. }
  40. return res
  41. }
  42. func getJSONPath(t *testing.T, base, path, cookie string) *http.Response {
  43. return reqJSON(t, http.MethodGet, base, path, "", cookie)
  44. }
  45. func putJSONPath(t *testing.T, base, path, payload, cookie string) *http.Response {
  46. return reqJSON(t, http.MethodPut, base, path, payload, cookie)
  47. }
  48. func deleteJSONPath(t *testing.T, base, path, cookie string) *http.Response {
  49. return reqJSON(t, http.MethodDelete, base, path, "", cookie)
  50. }
  51. func TestOwutVersionsEndpoint(t *testing.T) {
  52. ssh := &scriptedSSH{rules: []sshRule{
  53. {contains: "command -v owut", out: "__owut__\n"},
  54. {contains: "owut versions", out: owutVersionsSample},
  55. }}
  56. ts, rid := makeOwutTestServer(t, ssh)
  57. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  58. res := getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
  59. body := readJSON(t, res)
  60. if res.StatusCode != 200 {
  61. t.Fatalf("status %d: %v", res.StatusCode, body)
  62. }
  63. if body["owutAvailable"] != true {
  64. t.Fatalf("owutAvailable: %v", body["owutAvailable"])
  65. }
  66. versions, _ := body["versions"].([]any)
  67. if len(versions) != 4 {
  68. t.Fatalf("esperaba 4 versiones, got %v", versions)
  69. }
  70. }
  71. func TestOwutVersionsEndpointWithoutOwut(t *testing.T) {
  72. ssh := &scriptedSSH{rules: []sshRule{
  73. {contains: "command -v owut", out: "\n"}, // PATH sin owut
  74. }}
  75. ts, rid := makeOwutTestServer(t, ssh)
  76. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  77. res := getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
  78. body := readJSON(t, res)
  79. if res.StatusCode != 200 {
  80. t.Fatalf("status %d: %v", res.StatusCode, body)
  81. }
  82. if body["owutAvailable"] != false {
  83. t.Fatalf("owutAvailable: %v", body["owutAvailable"])
  84. }
  85. if versions, _ := body["versions"].([]any); len(versions) != 0 {
  86. t.Fatalf("sin owut no hay versiones: %v", versions)
  87. }
  88. if ssh.saw("owut versions") {
  89. t.Fatalf("no debe lanzarse owut versions sin owut: %v", ssh.cmdsSnapshot())
  90. }
  91. }
  92. func TestOwutInstallEndpoint(t *testing.T) {
  93. ssh := &scriptedSSH{rules: []sshRule{
  94. {contains: "apk add owut", out: "OK: 1 installed\n__owut_exit__=0\n"},
  95. }}
  96. ts, rid := makeOwutTestServer(t, ssh)
  97. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  98. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
  99. body := readJSON(t, res)
  100. if res.StatusCode != 200 {
  101. t.Fatalf("status %d: %v", res.StatusCode, body)
  102. }
  103. if body["ok"] != true {
  104. t.Fatalf("ok: %v", body)
  105. }
  106. if !ssh.saw("apk add owut") {
  107. t.Fatalf("no se lanzó la instalación: %v", ssh.cmdsSnapshot())
  108. }
  109. }
  110. func TestOwutInstallEndpointNoPackageManager(t *testing.T) {
  111. ssh := &scriptedSSH{rules: []sshRule{
  112. {contains: "apk update", out: "__no_pm__\n__owut_exit__=0\n"},
  113. }}
  114. ts, rid := makeOwutTestServer(t, ssh)
  115. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  116. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
  117. if res.StatusCode != 500 {
  118. t.Fatalf("status %d, esperaba 500", res.StatusCode)
  119. }
  120. }
  121. // waitForUpgradeStatus polea la lista hasta que el upgrade llegue al estado
  122. // terminal (la goroutine del server corre en background).
  123. func waitForUpgradeStatus(t *testing.T, ts *testServer, rid, want, cookie string) map[string]any {
  124. t.Helper()
  125. deadline := time.Now().Add(5 * time.Second)
  126. for time.Now().Before(deadline) {
  127. res := getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
  128. for _, it := range readJSONArray(t, res) {
  129. m, _ := it.(map[string]any)
  130. if m["routerId"] != rid {
  131. continue
  132. }
  133. if up, ok := m["upgrade"].(map[string]any); ok && up["status"] == want {
  134. return up
  135. }
  136. }
  137. time.Sleep(50 * time.Millisecond)
  138. }
  139. t.Fatalf("el upgrade no llegó a %s", want)
  140. return nil
  141. }
  142. func TestOwutUpgradeEndpointNoChanges(t *testing.T) {
  143. ssh := &scriptedSSH{rules: []sshRule{
  144. {contains: "command -v owut", out: "__owut__\n"},
  145. {contains: "owut upgrade", out: "There are no changes to upgrade (see '--force')\n__owut_exit__=0\n"},
  146. }}
  147. ts, rid := makeOwutTestServer(t, ssh)
  148. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  149. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
  150. body := readJSON(t, res)
  151. if res.StatusCode != 202 {
  152. t.Fatalf("status %d: %v", res.StatusCode, body)
  153. }
  154. if body["engine"] != "owut" {
  155. t.Fatalf("engine: %v", body["engine"])
  156. }
  157. up := waitForUpgradeStatus(t, ts, rid, "done", cookie)
  158. if up["engine"] != "owut" {
  159. t.Fatalf("engine del upgrade: %v", up["engine"])
  160. }
  161. if !ssh.saw("owut upgrade -q") {
  162. t.Fatalf("comando lanzado: %v", ssh.cmdsSnapshot())
  163. }
  164. // #761: antes de flashear se preserva el stack en /etc/sysupgrade.conf.
  165. if !ssh.saw("/etc/sysupgrade.conf") {
  166. t.Fatalf("preserve-stack no se ejecutó: %v", ssh.cmdsSnapshot())
  167. }
  168. }
  169. func TestOwutUpgradeEndpointFailure(t *testing.T) {
  170. ssh := &scriptedSSH{rules: []sshRule{
  171. {contains: "command -v owut", out: "__owut__\n"},
  172. {contains: "owut upgrade", out: "Update checks reveal errors, can't proceed\n__owut_exit__=1\n"},
  173. }}
  174. ts, rid := makeOwutTestServer(t, ssh)
  175. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  176. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
  177. if res.StatusCode != 202 {
  178. t.Fatalf("status %d", res.StatusCode)
  179. }
  180. up := waitForUpgradeStatus(t, ts, rid, "failed", cookie)
  181. if msg, _ := up["error"].(string); !strings.Contains(msg, "can't proceed") {
  182. t.Fatalf("error del upgrade: %v", up["error"])
  183. }
  184. }
  185. func TestOwutUpgradeRequiresTarget(t *testing.T) {
  186. ts, rid := makeOwutTestServer(t, nil)
  187. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  188. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{}`, cookie)
  189. if res.StatusCode != 400 {
  190. t.Fatalf("status %d, esperaba 400 sin targetVersion", res.StatusCode)
  191. }
  192. }
  193. func TestRecurrencePutGetDelete(t *testing.T) {
  194. ts, rid := makeOwutTestServer(t, nil)
  195. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  196. // weekly válido.
  197. res := putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  198. `{"enabled":true,"kind":"weekly","dayOfWeek":5,"time":"04:00"}`, cookie)
  199. if res.StatusCode != 200 {
  200. t.Fatalf("PUT weekly: %d %v", res.StatusCode, readJSON(t, res))
  201. }
  202. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  203. body := readJSON(t, res)
  204. rc, _ := body["recurrence"].(map[string]any)
  205. if rc["kind"] != "weekly" || rc["enabled"] != true {
  206. t.Fatalf("GET recurrence: %v", body)
  207. }
  208. if _, ok := body["nextRunMs"]; !ok {
  209. t.Fatalf("GET recurrence debe traer nextRunMs: %v", body)
  210. }
  211. // weekly sin time: 400.
  212. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  213. `{"enabled":true,"kind":"weekly","dayOfWeek":5}`, cookie)
  214. if res.StatusCode != 400 {
  215. t.Fatalf("PUT inválido: %d, esperaba 400", res.StatusCode)
  216. }
  217. // monthly y once válidos.
  218. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  219. `{"enabled":true,"kind":"monthly","dayOfMonth":1,"time":"05:30"}`, cookie)
  220. if res.StatusCode != 200 {
  221. t.Fatalf("PUT monthly: %d", res.StatusCode)
  222. }
  223. future := time.Now().Add(48 * time.Hour).UnixMilli()
  224. res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
  225. fmt.Sprintf(`{"enabled":true,"kind":"once","atMs":%d}`, future), cookie)
  226. if res.StatusCode != 200 {
  227. t.Fatalf("PUT once: %d", res.StatusCode)
  228. }
  229. // DELETE desactiva.
  230. res = deleteJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  231. if res.StatusCode != 200 {
  232. t.Fatalf("DELETE: %d", res.StatusCode)
  233. }
  234. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
  235. body = readJSON(t, res)
  236. rc, _ = body["recurrence"].(map[string]any)
  237. if rc["enabled"] != false {
  238. t.Fatalf("tras DELETE debe quedar disabled: %v", body)
  239. }
  240. }
  241. func TestOwutEndpointsBlockedForVendorFirmware(t *testing.T) {
  242. // GL.iNet: la plataforma devuelve __gl__ -> install y upgrade 422, y el
  243. // listado de versiones llega con vendorFirmware y sin sondear ASU.
  244. ssh := &scriptedSSH{rules: []sshRule{
  245. {contains: "fw.gl-inet.com", out: "__gl__\n"},
  246. }}
  247. ts, rid := makeOwutTestServer(t, ssh)
  248. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  249. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
  250. if res.StatusCode != 422 {
  251. t.Fatalf("install status %d, esperaba 422 vendor_firmware", res.StatusCode)
  252. }
  253. res = postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
  254. if res.StatusCode != 422 {
  255. t.Fatalf("upgrade status %d, esperaba 422 vendor_firmware", res.StatusCode)
  256. }
  257. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
  258. body := readJSON(t, res)
  259. if body["vendorFirmware"] != "gl-inet" {
  260. t.Fatalf("vendorFirmware: %v", body["vendorFirmware"])
  261. }
  262. if versions, _ := body["versions"].([]any); len(versions) != 0 {
  263. t.Fatalf("vendor no debe listar versiones: %v", versions)
  264. }
  265. if ssh.saw("owut versions") {
  266. t.Fatalf("vendor no debe sondear versiones ASU: %v", ssh.cmdsSnapshot())
  267. }
  268. }
  269. func TestTargetSaveWithoutURL(t *testing.T) {
  270. // #761: con owut la imagen la construye ASU; el target se guarda sin URL.
  271. ts, rid := makeOwutTestServer(t, nil)
  272. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  273. res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/target",
  274. `{"model":"redmi_ax6","currentVersion":"25.12.5","targetVersion":"25.12.5"}`, cookie)
  275. if res.StatusCode != 200 {
  276. t.Fatalf("guardar sin targetUrl: %d %v", res.StatusCode, readJSON(t, res))
  277. }
  278. res = getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
  279. for _, it := range readJSONArray(t, res) {
  280. m, _ := it.(map[string]any)
  281. if m["routerId"] == rid && m["targetVersion"] != "25.12.5" {
  282. t.Fatalf("target no persistió: %v", m)
  283. }
  284. }
  285. }