4
0

agent_binary_test.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. // agent_binary_test.go — #1367: el endpoint de binario del agente no debe
  2. // defaultear a arm64 en silencio cuando falta ?arch=, y el one-liner de
  3. // instalación no debe pre-descargar el binario (la detección de arquitectura
  4. // la hace install-agent.sh contra el router, que es quien la sabe).
  5. package httpapi_test
  6. import (
  7. "io"
  8. "net/http"
  9. "strings"
  10. "testing"
  11. "github.com/gnacho/netpulse/agent/probe"
  12. "github.com/gnacho/netpulse/server-go/internal/agentbin"
  13. )
  14. // getBinary hace GET /api/agents/<slug>/binary autenticado con el token del
  15. // agente; query se añade tal cual ("" o "?arch=mipsle").
  16. func getBinary(t *testing.T, ts *agentTestServer, slug, token, query string) *http.Response {
  17. t.Helper()
  18. url := ts.URL + "/api/agents/" + slug + "/binary" + query
  19. req, _ := http.NewRequest("GET", url, nil)
  20. req.Header.Set("Authorization", "Bearer "+token)
  21. res, err := http.DefaultClient.Do(req)
  22. if err != nil {
  23. t.Fatalf("GET %s: %v", url, err)
  24. }
  25. return res
  26. }
  27. func createTokenFor(t *testing.T, ts *agentTestServer, slug string) string {
  28. t.Helper()
  29. status, token, _ := createAgentToken(t, ts, slug)
  30. if status != 201 {
  31. t.Fatalf("create token %s: %d", slug, status)
  32. }
  33. return token
  34. }
  35. // #1367: sin ?arch= el server servía arm64 en silencio; un router MIPS que
  36. // instalara con el one-liner recibía un binario aarch64 (exec format error).
  37. // El default silencioso es la causa del reporte: ahora se exige la arch.
  38. func TestAgentBinaryRequiresArch(t *testing.T) {
  39. ts := makeAgentTestServer(t)
  40. token := createTokenFor(t, ts, "mipsbox")
  41. res := getBinary(t, ts, "mipsbox", token, "")
  42. defer res.Body.Close()
  43. if res.StatusCode != http.StatusBadRequest {
  44. body, _ := io.ReadAll(res.Body)
  45. t.Fatalf("sin ?arch= quiero 400 pidiendo la arch, tengo %d: %s", res.StatusCode, body)
  46. }
  47. }
  48. // Con ?arch= explícita el binario servido debe ser el de ESA arquitectura
  49. // (Content-Disposition y sha256 presentes), no el default.
  50. func TestAgentBinaryServesRequestedArch(t *testing.T) {
  51. if !agentbin.HasBinaries() {
  52. t.Skip("sin binarios embebidos (árbol dev sin agentbin/agents)")
  53. }
  54. ts := makeAgentTestServer(t)
  55. token := createTokenFor(t, ts, "mipsbox")
  56. res := getBinary(t, ts, "mipsbox", token, "?arch=mipsle")
  57. defer res.Body.Close()
  58. if res.StatusCode != http.StatusOK {
  59. body, _ := io.ReadAll(res.Body)
  60. t.Fatalf("?arch=mipsle quiero 200, tengo %d: %s", res.StatusCode, body)
  61. }
  62. if cd := res.Header.Get("Content-Disposition"); !strings.Contains(cd, "mipsle") {
  63. t.Fatalf("Content-Disposition = %q, quiero mipsle", cd)
  64. }
  65. if res.Header.Get("X-Checksum-Sha256") == "" {
  66. t.Fatal("falta la cabecera X-Checksum-Sha256")
  67. }
  68. head := make([]byte, 4)
  69. if _, err := io.ReadFull(res.Body, head); err != nil {
  70. t.Fatalf("leer body: %v", err)
  71. }
  72. if string(head) != "\x7fELF" {
  73. t.Fatalf("el body no es un ELF: %x", head)
  74. }
  75. }
  76. // Arch desconocida: 404 (comportamiento preexistente, se fija como contrato).
  77. func TestAgentBinaryUnknownArch(t *testing.T) {
  78. ts := makeAgentTestServer(t)
  79. token := createTokenFor(t, ts, "mipsbox")
  80. res := getBinary(t, ts, "mipsbox", token, "?arch=sparc")
  81. defer res.Body.Close()
  82. if res.StatusCode != http.StatusNotFound {
  83. t.Fatalf("?arch=sparc quiero 404, tengo %d", res.StatusCode)
  84. }
  85. }
  86. // #1840: el servidor no debe servir su binario embebido a un agente que ya
  87. // corre una versión más nueva: sería un downgrade silencioso que revierte
  88. // fixes. El operador puede forzarlo con ?force=1.
  89. func TestAgentBinaryRefusesDowngrade(t *testing.T) {
  90. prev := agentbin.EmbeddedAgentVersion
  91. agentbin.EmbeddedAgentVersion = "3.0.31"
  92. t.Cleanup(func() { agentbin.EmbeddedAgentVersion = prev })
  93. ts := makeAgentTestServer(t)
  94. token := createTokenFor(t, ts, "rt1")
  95. ts.agents.Ingest(&probe.Payload{Router: "rt1", Kind: "native", Version: "3.0.32"})
  96. res := getBinary(t, ts, "rt1", token, "?arch=arm64")
  97. defer res.Body.Close()
  98. if res.StatusCode != http.StatusConflict {
  99. body, _ := io.ReadAll(res.Body)
  100. t.Fatalf("agente más nuevo: quiero 409, tengo %d: %s", res.StatusCode, body)
  101. }
  102. body, _ := io.ReadAll(res.Body)
  103. if !strings.Contains(string(body), "3.0.32") {
  104. t.Fatalf("el error debe decir la versión reportada: %s", body)
  105. }
  106. }
  107. // ?force=1 es la confirmación explícita: sirve el binario aunque el router
  108. // reporte una versión más nueva (reinstall de un agente roto).
  109. func TestAgentBinaryForceSkipsDowngradeGuard(t *testing.T) {
  110. prev := agentbin.EmbeddedAgentVersion
  111. agentbin.EmbeddedAgentVersion = "3.0.31"
  112. t.Cleanup(func() { agentbin.EmbeddedAgentVersion = prev })
  113. ts := makeAgentTestServer(t)
  114. token := createTokenFor(t, ts, "rt1")
  115. ts.agents.Ingest(&probe.Payload{Router: "rt1", Kind: "native", Version: "3.0.32"})
  116. res := getBinary(t, ts, "rt1", token, "?arch=arm64&force=1")
  117. defer res.Body.Close()
  118. // 404 si el árbol no tiene binarios embebidos: el guard ya no bloquea.
  119. if res.StatusCode == http.StatusConflict {
  120. t.Fatal("?force=1 no debe devolver 409")
  121. }
  122. }
  123. // Sin estado del agente (recién instalado o caído) no se bloquea: hay que
  124. // poder curarlo. Un agente más viejo que el embebido tampoco se bloquea.
  125. func TestAgentBinaryDowngradeGuardOnlyForNewerAgents(t *testing.T) {
  126. prev := agentbin.EmbeddedAgentVersion
  127. agentbin.EmbeddedAgentVersion = "3.0.31"
  128. t.Cleanup(func() { agentbin.EmbeddedAgentVersion = prev })
  129. ts := makeAgentTestServer(t)
  130. token := createTokenFor(t, ts, "rt1")
  131. res := getBinary(t, ts, "rt1", token, "?arch=arm64")
  132. res.Body.Close()
  133. if res.StatusCode == http.StatusConflict {
  134. t.Fatal("sin estado del agente no debe bloquear")
  135. }
  136. ts.agents.Ingest(&probe.Payload{Router: "rt1", Kind: "native", Version: "3.0.30"})
  137. res = getBinary(t, ts, "rt1", token, "?arch=arm64")
  138. res.Body.Close()
  139. if res.StatusCode == http.StatusConflict {
  140. t.Fatal("un agente más viejo no debe bloquearse")
  141. }
  142. }
  143. // #1367: el one-liner NO debe pre-descargar el binario (sin arch no puede
  144. // acertar en MIPS); debe delegar en install-agent.sh, que detecta la arch
  145. // del router por SSH y descarga del propio server con ?arch=.
  146. func TestInstallLineDelegatesBinaryToInstaller(t *testing.T) {
  147. ts := makeAgentTestServer(t)
  148. _, _, install := createAgentToken(t, ts, "rt1")
  149. if strings.Contains(install, "/binary") {
  150. t.Fatalf("el one-liner no debe descargar el binario: %s", install)
  151. }
  152. // #1751: el instalador se sirve desde el propio servidor, no de GitHub.
  153. if !strings.Contains(install, "/api/agents/install-agent.sh") {
  154. t.Fatalf("el one-liner debe bajar el instalador del server: %s", install)
  155. }
  156. if strings.Contains(install, "raw.githubusercontent.com") {
  157. t.Fatalf("el one-liner no debe depender de GitHub: %s", install)
  158. }
  159. if !strings.Contains(install, "install-agent.sh") {
  160. t.Fatalf("el one-liner debe invocar install-agent.sh: %s", install)
  161. }
  162. for _, want := range []string{"--slug=rt1", "--token=", "--server="} {
  163. if !strings.Contains(install, want) {
  164. t.Fatalf("falta %s en el one-liner: %s", want, install)
  165. }
  166. }
  167. }