upgrade_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. }