4
0

upgrade_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // upgrade_test.go - Fase 6.3 (issue #243): tests de la lógica de self-update
  2. // del agente (mapeo de arquitectura, descarga+verificación y swap atómico).
  3. // #284: progreso de descarga y pasos reportados al servidor.
  4. package runtime
  5. import (
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "encoding/json"
  9. "net/http"
  10. "net/http/httptest"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. "sync"
  15. "testing"
  16. )
  17. func TestNetpulseArch(t *testing.T) {
  18. cases := map[string]string{
  19. "amd64": "amd64",
  20. "arm64": "arm64",
  21. "arm": "armv7", // GOARCH arm (GOARM=7) → sufijo de binario embebido
  22. "mips": "mips", // desconocido: se conserva
  23. }
  24. for in, want := range cases {
  25. if got := netpulseArch(in); got != want {
  26. t.Fatalf("netpulseArch(%q) = %q, want %q", in, got, want)
  27. }
  28. }
  29. }
  30. // fakeBinaryServer sirve un binario de prueba y ejercita auth/status/empty.
  31. func fakeBinaryServer(t *testing.T, token string) *httptest.Server {
  32. t.Helper()
  33. return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  34. switch r.URL.Path {
  35. case "/missing":
  36. w.WriteHeader(http.StatusNotFound)
  37. return
  38. case "/empty":
  39. w.WriteHeader(http.StatusOK)
  40. return
  41. }
  42. if r.Header.Get("Authorization") != "Bearer "+token {
  43. w.WriteHeader(http.StatusUnauthorized)
  44. return
  45. }
  46. w.WriteHeader(http.StatusOK)
  47. _, _ = w.Write([]byte("\x7fELF-fake-binary-content"))
  48. }))
  49. }
  50. func TestDownloadBinaryOK(t *testing.T) {
  51. srv := fakeBinaryServer(t, "tok")
  52. defer srv.Close()
  53. dest := filepath.Join(t.TempDir(), "agent.new")
  54. hc := &http.Client{}
  55. if _, err := downloadBinary(t.Context(), hc, srv.URL+"/binary", "tok", dest, nil); err != nil {
  56. t.Fatalf("downloadBinary: %v", err)
  57. }
  58. data, err := os.ReadFile(dest)
  59. if err != nil {
  60. t.Fatalf("ReadFile: %v", err)
  61. }
  62. if string(data) != "\x7fELF-fake-binary-content" {
  63. t.Fatalf("contenido: %q", data)
  64. }
  65. st, err := os.Stat(dest)
  66. if err != nil {
  67. t.Fatalf("Stat: %v", err)
  68. }
  69. if st.Mode().Perm() != 0o755 {
  70. t.Fatalf("permisos: %o, want 755", st.Mode().Perm())
  71. }
  72. }
  73. func TestDownloadBinaryAuth404Empty(t *testing.T) {
  74. srv := fakeBinaryServer(t, "tok")
  75. defer srv.Close()
  76. dest := filepath.Join(t.TempDir(), "agent.new")
  77. hc := &http.Client{}
  78. // Token inválido → 401 → error.
  79. if _, err := downloadBinary(t.Context(), hc, srv.URL+"/binary", "wrong", dest, nil); err == nil {
  80. t.Fatal("token inválido: quiero error")
  81. }
  82. // 404 → error.
  83. if _, err := downloadBinary(t.Context(), hc, srv.URL+"/missing", "tok", dest, nil); err == nil {
  84. t.Fatal("404: quiero error")
  85. }
  86. // Cuerpo vacío → error (verificación de no-vacío).
  87. if _, err := downloadBinary(t.Context(), hc, srv.URL+"/empty", "tok", dest, nil); err == nil {
  88. t.Fatal("body vacío: quiero error")
  89. }
  90. }
  91. func TestSwapBinary(t *testing.T) {
  92. dir := t.TempDir()
  93. src := filepath.Join(dir, "src")
  94. dst := filepath.Join(dir, "dst")
  95. if err := os.WriteFile(src, []byte("nuevo-binario"), 0o755); err != nil {
  96. t.Fatalf("WriteFile: %v", err)
  97. }
  98. if err := swapBinary(src, dst); err != nil {
  99. t.Fatalf("swapBinary: %v", err)
  100. }
  101. data, err := os.ReadFile(dst)
  102. if err != nil {
  103. t.Fatalf("ReadFile dst: %v", err)
  104. }
  105. if string(data) != "nuevo-binario" {
  106. t.Fatalf("contenido dst: %q", data)
  107. }
  108. st, _ := os.Stat(dst)
  109. if st.Mode().Perm() != 0o755 {
  110. t.Fatalf("permisos dst: %o, want 755", st.Mode().Perm())
  111. }
  112. if _, err := os.Stat(src); !os.IsNotExist(err) {
  113. t.Fatal("src debe desaparecer tras el swap")
  114. }
  115. }
  116. // TestDownloadBinaryProgress: el callback de progreso dispara al cruzar cada
  117. // frontera del 10% del total (100% incluido) y termina en el 100 (#284).
  118. // El payload es 10x el buffer de io.Copy (32 KiB) para que cada lectura cruce
  119. // exactamente una frontera; con payloads pequeños una sola Read puede saltar
  120. // varias fronteras de golpe (comportamiento aceptable en producción).
  121. func TestDownloadBinaryProgress(t *testing.T) {
  122. payload := make([]byte, 320_000)
  123. for i := range payload {
  124. payload[i] = byte('A' + i%26)
  125. }
  126. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  127. w.Header().Set("Content-Length", "320000")
  128. _, _ = w.Write(payload)
  129. }))
  130. defer srv.Close()
  131. var got []int
  132. dest := filepath.Join(t.TempDir(), "agent.new")
  133. if _, err := downloadBinary(t.Context(), &http.Client{}, srv.URL+"/binary", "tok", dest, func(pct int) {
  134. got = append(got, pct)
  135. }); err != nil {
  136. t.Fatalf("downloadBinary: %v", err)
  137. }
  138. want := []int{5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100}
  139. if len(got) != len(want) {
  140. t.Fatalf("progreso: got %v, want %v", got, want)
  141. }
  142. for i := range want {
  143. if got[i] != want[i] {
  144. t.Fatalf("progreso[%d]: got %d, want %d (full: %v)", i, got[i], want[i], got)
  145. }
  146. }
  147. }
  148. // TestReportUpgradeProgressSteps: handleUpgrade informa los pasos
  149. // downloading/swapping/restarting al servidor antes del resultado final.
  150. // El reinicio real no ocurre (no hay init script en el entorno de test),
  151. // así que el flujo para en restartService y el test observa los POSTs.
  152. func TestReportUpgradeProgressSteps(t *testing.T) {
  153. var mu sync.Mutex
  154. var steps []string
  155. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  156. switch r.URL.Path {
  157. case "/api/agents/patio/upgrade-progress":
  158. var body struct {
  159. Step string `json:"step"`
  160. Pct int `json:"pct"`
  161. }
  162. _ = json.NewDecoder(r.Body).Decode(&body)
  163. mu.Lock()
  164. steps = append(steps, body.Step)
  165. mu.Unlock()
  166. w.WriteHeader(http.StatusOK)
  167. case "/api/agents/patio/binary":
  168. data := make([]byte, 64)
  169. sum := sha256.Sum256(data)
  170. w.Header().Set("Content-Length", "64")
  171. w.Header().Set("X-Checksum-Sha256", hex.EncodeToString(sum[:]))
  172. _, _ = w.Write(data)
  173. case "/api/agents/patio/upgrade-result":
  174. w.WriteHeader(http.StatusOK)
  175. default:
  176. w.WriteHeader(http.StatusNotFound)
  177. }
  178. }))
  179. defer srv.Close()
  180. // Binario "en marcha" en un temp dir: el swap cae al fallback de copia
  181. // (distinto filesystem) y funciona sin permisos de root.
  182. exe := filepath.Join(t.TempDir(), "netpulse-agent")
  183. if err := os.WriteFile(exe, []byte("viejo"), 0o755); err != nil {
  184. t.Fatalf("WriteFile exe: %v", err)
  185. }
  186. oldPath := currentBinPath
  187. currentBinPath = func() string { return exe }
  188. defer func() { currentBinPath = oldPath }()
  189. cfg := Options{Server: srv.URL, Slug: "patio", Token: "tok"}
  190. handleUpgrade(cfg, nil, "")
  191. mu.Lock()
  192. defer mu.Unlock()
  193. if len(steps) < 3 {
  194. t.Fatalf("pasos reportados: %v, quiero al menos downloading+swapping+restarting", steps)
  195. }
  196. if steps[0] != "downloading" {
  197. t.Fatalf("primer paso: %q, want downloading", steps[0])
  198. }
  199. hasSwapping, hasRestarting := false, false
  200. for _, s := range steps {
  201. if s == "swapping" {
  202. hasSwapping = true
  203. }
  204. if s == "restarting" {
  205. hasRestarting = true
  206. }
  207. }
  208. if !hasSwapping || !hasRestarting {
  209. t.Fatalf("pasos incompletos: %v", steps)
  210. }
  211. }
  212. func TestUpgradeRejectsMissingOrMismatchedDigest(t *testing.T) {
  213. for _, tc := range []struct {
  214. name string
  215. digest string
  216. }{
  217. {"sin digest", ""},
  218. {"digest que no coincide", strings.Repeat("0", 64)},
  219. } {
  220. t.Run(tc.name, func(t *testing.T) {
  221. var mu sync.Mutex
  222. var steps []string
  223. var result map[string]any
  224. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  225. switch r.URL.Path {
  226. case "/api/agents/patio/upgrade-progress":
  227. var body struct {
  228. Step string `json:"step"`
  229. }
  230. _ = json.NewDecoder(r.Body).Decode(&body)
  231. mu.Lock()
  232. steps = append(steps, body.Step)
  233. mu.Unlock()
  234. w.WriteHeader(http.StatusOK)
  235. case "/api/agents/patio/binary":
  236. data := make([]byte, 64)
  237. if tc.digest != "" {
  238. w.Header().Set("X-Checksum-Sha256", tc.digest)
  239. }
  240. _, _ = w.Write(data)
  241. case "/api/agents/patio/upgrade-result":
  242. mu.Lock()
  243. result = nil
  244. _ = json.NewDecoder(r.Body).Decode(&result)
  245. mu.Unlock()
  246. w.WriteHeader(http.StatusOK)
  247. default:
  248. w.WriteHeader(http.StatusNotFound)
  249. }
  250. }))
  251. defer srv.Close()
  252. oldTmp := tmpBinPath
  253. tmpBinPath = filepath.Join(t.TempDir(), "netpulse-agent.new")
  254. defer func() { tmpBinPath = oldTmp }()
  255. oldPath := currentBinPath
  256. currentBinPath = func() string { return filepath.Join(t.TempDir(), "netpulse-agent") }
  257. defer func() { currentBinPath = oldPath }()
  258. handleUpgrade(Options{Server: srv.URL, Slug: "patio", Token: "tok"}, nil, "")
  259. mu.Lock()
  260. defer mu.Unlock()
  261. for _, step := range steps {
  262. if step == "swapping" || step == "restarting" {
  263. t.Fatalf("no debía instalar nada, pasos: %v", steps)
  264. }
  265. }
  266. if result == nil {
  267. t.Fatal("no se reportó el resultado del upgrade")
  268. }
  269. if ok, _ := result["ok"].(bool); ok {
  270. t.Fatalf("el upgrade debía fallar, resultado: %v", result)
  271. }
  272. })
  273. }
  274. }
  275. // stubNoInitScript apunta el script procd a una ruta que no existe y devuelve
  276. // la restauración, para ejercitar la vía sin supervisor (#1900).
  277. func stubNoInitScript(t *testing.T) {
  278. t.Helper()
  279. old := agentInitScript
  280. agentInitScript = filepath.Join(t.TempDir(), "sin-init")
  281. t.Cleanup(func() { agentInitScript = old })
  282. }
  283. // stubExecSelf sustituye el exec del proceso y registra con qué se llamó.
  284. func stubExecSelf(t *testing.T, err error) *[]string {
  285. t.Helper()
  286. var calls []string
  287. old := execSelf
  288. execSelf = func(bin string, argv []string, env []string) error {
  289. calls = append(calls, bin)
  290. return err
  291. }
  292. t.Cleanup(func() { execSelf = old })
  293. return &calls
  294. }
  295. // #1900 pata 1: sin script procd el agente se reemplaza a sí mismo con el
  296. // binario que acaba de instalar. Antes devolvía error, el proceso seguía con
  297. // el binario viejo en memoria y el equipo quedaba mintiendo hasta el reboot.
  298. func TestRestartServiceExecsTheNewBinaryWithoutProcd(t *testing.T) {
  299. stubNoInitScript(t)
  300. calls := stubExecSelf(t, nil)
  301. bin := filepath.Join(t.TempDir(), "netpulse-agent")
  302. if err := restartService(bin); err != nil {
  303. t.Fatalf("restartService: %v", err)
  304. }
  305. if len(*calls) != 1 || (*calls)[0] != bin {
  306. t.Fatalf("exec con %v, quiero exactamente %q", *calls, bin)
  307. }
  308. }
  309. // Con script procd se le pide el reinicio y no se toca el proceso: el
  310. // supervisor es quien lo relanza.
  311. func TestRestartServiceUsesTheProcdScriptWhenItExists(t *testing.T) {
  312. dir := t.TempDir()
  313. marker := filepath.Join(dir, "reiniciado")
  314. script := filepath.Join(dir, "netpulse-agent")
  315. body := "#!/bin/sh\ntouch " + marker + "\nexit 0\n"
  316. if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
  317. t.Fatalf("WriteFile script: %v", err)
  318. }
  319. old := agentInitScript
  320. agentInitScript = script
  321. defer func() { agentInitScript = old }()
  322. calls := stubExecSelf(t, nil)
  323. if err := restartService("/tmp/otro"); err != nil {
  324. t.Fatalf("restartService: %v", err)
  325. }
  326. if len(*calls) != 0 {
  327. t.Fatalf("con script procd no se debe hacer exec: %v", *calls)
  328. }
  329. if _, err := os.Stat(marker); err != nil {
  330. t.Fatalf("el script no llegó a ejecutarse: %v", err)
  331. }
  332. }
  333. // Si el exec también falla, el error dice por dónde se intentó.
  334. func TestRestartServiceReportsExecFailure(t *testing.T) {
  335. stubNoInitScript(t)
  336. stubExecSelf(t, os.ErrPermission)
  337. err := restartService("/tmp/netpulse-agent")
  338. if err == nil || !strings.Contains(err.Error(), "/tmp/netpulse-agent") {
  339. t.Fatalf("error = %v, quiero uno que nombre el binario", err)
  340. }
  341. }
  342. // #1900 de punta a punta: el agente reporta ok antes de reiniciar y, si el
  343. // reinicio no arranca, reporta el fallo con el motivo para que el servidor no
  344. // se quede en "restarting" y la UI no diga que está al día.
  345. func TestUpgradeReportsRestartFailure(t *testing.T) {
  346. var mu sync.Mutex
  347. var results []map[string]any
  348. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  349. switch r.URL.Path {
  350. case "/api/agents/patio/binary":
  351. data := make([]byte, 64)
  352. sum := sha256.Sum256(data)
  353. w.Header().Set("Content-Length", "64")
  354. w.Header().Set("X-Checksum-Sha256", hex.EncodeToString(sum[:]))
  355. _, _ = w.Write(data)
  356. case "/api/agents/patio/upgrade-result":
  357. var body map[string]any
  358. _ = json.NewDecoder(r.Body).Decode(&body)
  359. mu.Lock()
  360. results = append(results, body)
  361. mu.Unlock()
  362. w.WriteHeader(http.StatusOK)
  363. default:
  364. w.WriteHeader(http.StatusOK)
  365. }
  366. }))
  367. defer srv.Close()
  368. dir := t.TempDir()
  369. oldTmp := tmpBinPath
  370. tmpBinPath = filepath.Join(dir, "agent.new")
  371. defer func() { tmpBinPath = oldTmp }()
  372. exe := filepath.Join(dir, "netpulse-agent")
  373. if err := os.WriteFile(exe, []byte("viejo"), 0o755); err != nil {
  374. t.Fatalf("WriteFile exe: %v", err)
  375. }
  376. oldPath := currentBinPath
  377. currentBinPath = func() string { return exe }
  378. defer func() { currentBinPath = oldPath }()
  379. stubNoInitScript(t)
  380. stubExecSelf(t, os.ErrPermission)
  381. handleUpgrade(Options{Server: srv.URL, Slug: "patio", Token: "tok"}, nil, "")
  382. mu.Lock()
  383. defer mu.Unlock()
  384. if len(results) != 2 {
  385. t.Fatalf("resultados = %v, quiero ok y then fallo", results)
  386. }
  387. if ok, _ := results[0]["ok"].(bool); !ok {
  388. t.Fatalf("primer resultado: %v, quiero ok=true antes del reinicio", results[0])
  389. }
  390. if ok, _ := results[1]["ok"].(bool); ok {
  391. t.Fatalf("segundo resultado: %v, quiero ok=false", results[1])
  392. }
  393. if msg, _ := results[1]["error"].(string); !strings.Contains(msg, "reinicio falló") {
  394. t.Fatalf("error reportado = %q", msg)
  395. }
  396. }