upgrade_api_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // upgrade_api_test.go — Fase 6.3 (issue #243): self-update del agente.
  2. // Contrato de POST /api/agents/{slug}/upgrade (admin) y
  3. // POST /api/agents/{slug}/upgrade-result (Bearer del agente), y del campo
  4. // updateAvailable de GET /api/agents.
  5. package httpapi_test
  6. import (
  7. "context"
  8. "crypto/hmac"
  9. "crypto/sha256"
  10. "crypto/subtle"
  11. "encoding/hex"
  12. "encoding/json"
  13. "fmt"
  14. "io"
  15. "net/http"
  16. "net/http/httptest"
  17. "strings"
  18. "testing"
  19. "time"
  20. "github.com/gnacho/netpulse/server-go/internal/adapters"
  21. "github.com/gnacho/netpulse/server-go/internal/agentbin"
  22. "github.com/gnacho/netpulse/server-go/internal/auth"
  23. "github.com/gnacho/netpulse/server-go/internal/config"
  24. "github.com/gnacho/netpulse/server-go/internal/db"
  25. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  26. "github.com/gnacho/netpulse/server-go/internal/sse"
  27. )
  28. type upgradeTestServer struct {
  29. *httptest.Server
  30. db *db.DB
  31. agents *adapters.AgentRegistry
  32. hub *sse.AgentHub
  33. cookie string
  34. }
  35. // makeUpgradeTestServer: app real con registry + AgentHub (checkToken contra
  36. // kv, como producción). El AgentHub habilita stream/refresh/upgrade.
  37. func makeUpgradeTestServer(t *testing.T) *upgradeTestServer {
  38. t.Helper()
  39. return makeUpgradeTestServerWithOptions(t, true)
  40. }
  41. func makeUpgradeTestServerWithOptions(t *testing.T, allowInsecure bool) *upgradeTestServer {
  42. t.Helper()
  43. auth.SetTrustProxy(true)
  44. t.Cleanup(func() { auth.SetTrustProxy(false) })
  45. dataDir := t.TempDir()
  46. cfg, err := config.Load(map[string]string{
  47. "AUTH_USER": "admin", "AUTH_PASS": "test123456",
  48. "DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
  49. }, dataDir)
  50. if err != nil {
  51. t.Fatalf("config: %v", err)
  52. }
  53. d, err := db.Open(dataDir)
  54. if err != nil {
  55. t.Fatalf("db: %v", err)
  56. }
  57. secret, err := auth.EnsureSessionSecret(d, cfg)
  58. if err != nil {
  59. t.Fatalf("secret: %v", err)
  60. }
  61. if err := auth.EnsureUsers(d, cfg); err != nil {
  62. t.Fatalf("users: %v", err)
  63. }
  64. reg := adapters.NewAgentRegistry(90 * time.Second)
  65. hub := sse.NewAgentHub(func(slug, token string) bool {
  66. if token == "" || d == nil {
  67. return false
  68. }
  69. var stored string
  70. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", "agent.token."+slug).Scan(&stored); err != nil {
  71. return false
  72. }
  73. sum := sha256.Sum256([]byte(token))
  74. return subtle.ConstantTimeCompare([]byte(hex.EncodeToString(sum[:])), []byte(stored)) == 1
  75. })
  76. hub.SetAllowInsecureCommands(allowInsecure)
  77. handler := httpapi.NewHandler(httpapi.Deps{
  78. Config: cfg, DB: d, Adapter: adapters.NewDemo(),
  79. Hub: sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
  80. Secret: secret, Agents: reg, AgentHub: hub, Started: time.Now(),
  81. })
  82. srv := httptest.NewServer(handler)
  83. status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  84. if status != 204 {
  85. t.Fatalf("login: %d", status)
  86. }
  87. ts := &upgradeTestServer{Server: srv, db: d, agents: reg, hub: hub, cookie: cookie}
  88. t.Cleanup(func() {
  89. srv.Close()
  90. d.Close()
  91. })
  92. return ts
  93. }
  94. // createUpgradeToken crea el token de un slug vía API (sesión admin).
  95. func createUpgradeToken(t *testing.T, ts *upgradeTestServer, slug string) (int, string) {
  96. t.Helper()
  97. req, _ := http.NewRequest("POST", ts.URL+"/api/agents", strings.NewReader(`{"slug":"`+slug+`"}`))
  98. req.Header.Set("Content-Type", "application/json")
  99. req.Header.Set("Cookie", "session="+ts.cookie)
  100. res, err := http.DefaultClient.Do(req)
  101. if err != nil {
  102. t.Fatalf("POST /api/agents: %v", err)
  103. }
  104. defer res.Body.Close()
  105. var body struct {
  106. Token string `json:"token"`
  107. }
  108. data, _ := io.ReadAll(res.Body)
  109. _ = json.Unmarshal(data, &body)
  110. return res.StatusCode, body.Token
  111. }
  112. // postUpgrade hace POST /api/agents/{slug}/upgrade con la cookie dada.
  113. func postUpgrade(t *testing.T, ts *upgradeTestServer, slug, cookie string) (int, map[string]any) {
  114. t.Helper()
  115. req, _ := http.NewRequest("POST", ts.URL+"/api/agents/"+slug+"/upgrade", nil)
  116. if cookie != "" {
  117. req.Header.Set("Cookie", "session="+cookie)
  118. }
  119. res, err := http.DefaultClient.Do(req)
  120. if err != nil {
  121. t.Fatalf("POST /upgrade: %v", err)
  122. }
  123. defer res.Body.Close()
  124. var body map[string]any
  125. _ = json.NewDecoder(res.Body).Decode(&body)
  126. return res.StatusCode, body
  127. }
  128. // upgradeIngest hace un push de agente (mismo contrato que rearmIngest).
  129. func upgradeIngest(t *testing.T, ts *upgradeTestServer, token, payload string) {
  130. t.Helper()
  131. req, _ := http.NewRequest("POST", ts.URL+"/api/ingest/agent", strings.NewReader(payload))
  132. req.Header.Set("Content-Type", "application/json")
  133. req.Header.Set("X-Forwarded-For", "10.9.9.1")
  134. if token != "" {
  135. req.Header.Set("Authorization", "Bearer "+token)
  136. mac := hmac.New(sha256.New, []byte(token))
  137. mac.Write([]byte(payload))
  138. req.Header.Set("X-Agent-Signature", hex.EncodeToString(mac.Sum(nil)))
  139. }
  140. res, err := http.DefaultClient.Do(req)
  141. if err != nil {
  142. t.Fatalf("ingest: %v", err)
  143. }
  144. res.Body.Close()
  145. if res.StatusCode != 202 {
  146. t.Fatalf("ingest: got %d want 202", res.StatusCode)
  147. }
  148. }
  149. // upgradePayload construye un payload válido con la versión dada (router "patio").
  150. func upgradePayload(version string) string {
  151. return upgradePayloadFor("patio", version)
  152. }
  153. func upgradePayloadAt(version string, ts int64) string {
  154. return upgradePayloadForAt("patio", version, ts)
  155. }
  156. // upgradePayloadFor: igual que upgradePayload pero para un router arbitrario.
  157. func upgradePayloadFor(router, version string) string {
  158. return upgradePayloadForAt(router, version, time.Now().Unix())
  159. }
  160. func upgradePayloadForAt(router, version string, ts int64) string {
  161. return fmt.Sprintf(`{"router":%q,"ts":%d,"version":%q,"data":{"system":{"sysinfo":{"uptime":100,"load":[0,0,0],"memory":{"total":100,"free":50,"buffered":0,"available":50}},"cpu":10,"temp":40},"wireless":{"clients":{}},"dhcp":{"leases":[]},"fdb":{"macs":{}}}}`, router, ts, version)
  162. }
  163. // openStream registra una conexión SSE falsa del agente en el hub usando un
  164. // ResponseRecorder (sin servidor HTTP real, para no disparar la carrera
  165. // finishRequest de net/http). Devuelve cancel + done para detener el handler.
  166. func openStream(t *testing.T, ts *upgradeTestServer, slug, token string) (cancel context.CancelFunc, done chan struct{}) {
  167. t.Helper()
  168. ctx, cancel := context.WithCancel(context.Background())
  169. req := httptest.NewRequest(http.MethodGet, ts.URL+"/api/agents/"+slug+"/stream", nil).WithContext(ctx)
  170. req.SetPathValue("slug", slug)
  171. req.Header.Set("Authorization", "Bearer "+token)
  172. rec := httptest.NewRecorder()
  173. done = make(chan struct{})
  174. go func() {
  175. ts.hub.HandleStream(rec, req)
  176. close(done)
  177. }()
  178. // Margen para que el hub registre la conexión antes del POST.
  179. time.Sleep(200 * time.Millisecond)
  180. return cancel, done
  181. }
  182. func TestUpgradeSinSesion401(t *testing.T) {
  183. ts := makeUpgradeTestServer(t)
  184. status, body := postUpgrade(t, ts, "patio", "")
  185. if status != 401 || body["error"] != "unauthorized" {
  186. t.Fatalf("sin sesión: got %d %v", status, body)
  187. }
  188. }
  189. func TestUpgradeNoAdmin403(t *testing.T) {
  190. ts := makeUpgradeTestServer(t)
  191. // Crear usuario no-admin y loguear con él.
  192. req, _ := http.NewRequest("POST", ts.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"secreto12345"}`))
  193. req.Header.Set("Cookie", "session="+ts.cookie)
  194. res, _ := http.DefaultClient.Do(req)
  195. res.Body.Close()
  196. _, anaCookie, _ := loginCookie(t, ts.URL, "ana", "secreto12345")
  197. status, body := postUpgrade(t, ts, "patio", anaCookie)
  198. if status != 403 || body["error"] != "forbidden" {
  199. t.Fatalf("no-admin: got %d %v", status, body)
  200. }
  201. }
  202. func TestUpgradeSlugDesconocido404(t *testing.T) {
  203. ts := makeUpgradeTestServer(t)
  204. // Sin token registrado → 404 (distinto del 409 de "no conectado").
  205. status, body := postUpgrade(t, ts, "noexiste", ts.cookie)
  206. if status != 404 || body["error"] != "not_found" {
  207. t.Fatalf("slug desconocido: got %d %v", status, body)
  208. }
  209. }
  210. // TestUpgradeNoConectadoEncola — #284: sin stream SSE el upgrade NO da 409;
  211. // se encola (202 status "queued") para el flush on-connect.
  212. func TestUpgradeNoConectadoEncola(t *testing.T) {
  213. ts := makeUpgradeTestServer(t)
  214. st, tok := createUpgradeToken(t, ts, "patio")
  215. if st != 201 || tok == "" {
  216. t.Fatalf("create: %d", st)
  217. }
  218. status, body := postUpgrade(t, ts, "patio", ts.cookie)
  219. if status != 202 || body["status"] != "queued" {
  220. t.Fatalf("no conectado: got %d %v", status, body)
  221. }
  222. // Al conectar el stream, el upgrade encolado se envía (flush on-connect)
  223. // y el estado pasa a "requested" en GET /api/agents.
  224. cancel, done := openStream(t, ts, "patio", tok)
  225. defer func() { cancel(); <-done }()
  226. deadline := time.Now().Add(5 * time.Second)
  227. ok := false
  228. for time.Now().Before(deadline) && !ok {
  229. res := doReq(t, "GET", ts.URL+"/api/agents", ts.cookie, "")
  230. if res.StatusCode == 200 {
  231. for _, a := range readJSON(t, res)["agents"].([]any) {
  232. m, isMap := a.(map[string]any)
  233. if !isMap || m["slug"] != "patio" {
  234. continue
  235. }
  236. if up, has := m["upgrade"].(map[string]any); has && up["step"] == "requested" {
  237. ok = true
  238. }
  239. }
  240. }
  241. if !ok {
  242. time.Sleep(100 * time.Millisecond)
  243. }
  244. }
  245. if !ok {
  246. t.Fatalf("el upgrade encolado no se envió al conectar el stream")
  247. }
  248. }
  249. func TestUpgradeConectado202(t *testing.T) {
  250. ts := makeUpgradeTestServer(t)
  251. st, tok := createUpgradeToken(t, ts, "patio")
  252. if st != 201 || tok == "" {
  253. t.Fatalf("create: %d", st)
  254. }
  255. cancel, done := openStream(t, ts, "patio", tok)
  256. status, body := postUpgrade(t, ts, "patio", ts.cookie)
  257. if status != 202 || body["ok"] != true || body["status"] != "sent" {
  258. t.Fatalf("conectado: got %d %v", status, body)
  259. }
  260. if len(body) != 2 {
  261. t.Fatalf("body con claves extra: %v", body)
  262. }
  263. cancel()
  264. <-done
  265. }
  266. func TestUpgradeRejectsHTTPTransportWithoutOptIn(t *testing.T) {
  267. ts := makeUpgradeTestServerWithOptions(t, false)
  268. st, tok := createUpgradeToken(t, ts, "patio")
  269. if st != 201 || tok == "" {
  270. t.Fatalf("create: %d", st)
  271. }
  272. cancel, done := openStream(t, ts, "patio", tok)
  273. status, body := postUpgrade(t, ts, "patio", ts.cookie)
  274. if status != 409 || body["error"] != "insecure_agent_transport" {
  275. t.Fatalf("http sin opt-in: got %d %v", status, body)
  276. }
  277. cancel()
  278. <-done
  279. }
  280. func TestUpgradeResultBearer(t *testing.T) {
  281. ts := makeUpgradeTestServer(t)
  282. st, tok := createUpgradeToken(t, ts, "patio")
  283. if st != 201 || tok == "" {
  284. t.Fatalf("create: %d", st)
  285. }
  286. post := func(token, body string) int {
  287. req, _ := http.NewRequest("POST", ts.URL+"/api/agents/patio/upgrade-result", strings.NewReader(body))
  288. req.Header.Set("Content-Type", "application/json")
  289. if token != "" {
  290. req.Header.Set("Authorization", "Bearer "+token)
  291. }
  292. res, err := http.DefaultClient.Do(req)
  293. if err != nil {
  294. t.Fatalf("upgrade-result: %v", err)
  295. }
  296. defer res.Body.Close()
  297. return res.StatusCode
  298. }
  299. // Sin token → 401 (bypass de RequireAuth, pero el handler exige Bearer).
  300. if got := post("", `{"ok":true}`); got != 401 {
  301. t.Fatalf("sin token: got %d want 401", got)
  302. }
  303. // Token inválido → 401.
  304. if got := post("deadbeef", `{"ok":true}`); got != 401 {
  305. t.Fatalf("token malo: got %d want 401", got)
  306. }
  307. // Token válido, body ok → 200.
  308. if got := post(tok, `{"ok":true}`); got != 200 {
  309. t.Fatalf("ok válido: got %d want 200", got)
  310. }
  311. // Token válido, body con error → 200 (se loguea).
  312. if got := post(tok, `{"ok":false,"error":"swap failed"}`); got != 200 {
  313. t.Fatalf("error válido: got %d want 200", got)
  314. }
  315. // Body no-JSON → 400.
  316. if got := post(tok, `not-json`); got != 400 {
  317. t.Fatalf("body roto: got %d want 400", got)
  318. }
  319. }
  320. // TestAgentsListUpdateAvailable: el campo updateAvailable refleja si la versión
  321. // reportada por el agente es MÁS VIEJA que la del binario embebido
  322. // (agentbin.EmbeddedAgentVersion), build incluido (#447). Un agente más nuevo
  323. // que el embebido no está desactualizado (el botón ofrecería un downgrade).
  324. func TestAgentsListUpdateAvailable(t *testing.T) {
  325. ts := makeUpgradeTestServer(t)
  326. st, tok := createUpgradeToken(t, ts, "patio")
  327. if st != 201 {
  328. t.Fatalf("create: %d", st)
  329. }
  330. agentItem := func() map[string]any {
  331. res := get(t, ts.URL, "/api/agents", ts.cookie)
  332. body := readJSON(t, res)
  333. for _, a := range body["agents"].([]any) {
  334. if m, _ := a.(map[string]any); m["slug"] == "patio" {
  335. return m
  336. }
  337. }
  338. t.Fatalf("patio ausente: %v", body)
  339. return nil
  340. }
  341. base := time.Now().Unix() + 60
  342. // Push con versión == EmbeddedAgentVersion (0.1.0) → updateAvailable=false.
  343. upgradeIngest(t, ts, tok, upgradePayloadAt("0.1.0", base))
  344. if patio := agentItem(); patio["updateAvailable"] != false {
  345. t.Fatalf("versión 0.1.0 debe dar updateAvailable=false: %v", patio)
  346. }
  347. // Push con versión más vieja → updateAvailable=true.
  348. upgradeIngest(t, ts, tok, upgradePayloadAt("0.0.9", base+1))
  349. if patio := agentItem(); patio["updateAvailable"] != true {
  350. t.Fatalf("versión 0.0.9 debe dar updateAvailable=true: %v", patio)
  351. }
  352. // Push con versión MÁS NUEVA que la embebida → false (no se ofrece
  353. // downgrade; antes cualquier versión distinta marcaba novedad, #447).
  354. upgradeIngest(t, ts, tok, upgradePayloadAt("9.9.9", base+2))
  355. if patio := agentItem(); patio["updateAvailable"] != false {
  356. t.Fatalf("versión 9.9.9 (más nueva) debe dar updateAvailable=false: %v", patio)
  357. }
  358. // #447: builds del mismo x.y.z: -437 < -443 marca novedad; -443 no.
  359. saved := agentbin.EmbeddedAgentVersion
  360. t.Cleanup(func() { agentbin.EmbeddedAgentVersion = saved })
  361. agentbin.EmbeddedAgentVersion = "2.25.0-443"
  362. upgradeIngest(t, ts, tok, upgradePayloadAt("2.25.0-437", base+3))
  363. if patio := agentItem(); patio["updateAvailable"] != true {
  364. t.Fatalf("2.25.0-437 contra embebido 2.25.0-443 debe dar updateAvailable=true: %v", patio)
  365. }
  366. upgradeIngest(t, ts, tok, upgradePayloadAt("2.25.0-443", base+4))
  367. if patio := agentItem(); patio["updateAvailable"] != false {
  368. t.Fatalf("2.25.0-443 contra embebido 2.25.0-443 debe dar updateAvailable=false: %v", patio)
  369. }
  370. }
  371. // TestAgentsListUpdateAvailableStale — #1382: un agente SIN pulso reciente
  372. // (equipo apagado o retirado de la red) no se ofrece como actualizable aunque
  373. // su última versión conocida sea vieja: no hay forma de aplicarle un upgrade
  374. // y el aviso sería ruido permanente en la tabla de flota.
  375. func TestAgentsListUpdateAvailableStale(t *testing.T) {
  376. ts := makeUpgradeTestServer(t)
  377. st, tok := createUpgradeToken(t, ts, "patio")
  378. if st != 201 {
  379. t.Fatalf("create: %d", st)
  380. }
  381. agentItem := func() map[string]any {
  382. res := get(t, ts.URL, "/api/agents", ts.cookie)
  383. body := readJSON(t, res)
  384. for _, a := range body["agents"].([]any) {
  385. if m, _ := a.(map[string]any); m["slug"] == "patio" {
  386. return m
  387. }
  388. }
  389. t.Fatalf("patio ausente: %v", body)
  390. return nil
  391. }
  392. // Fresco con versión vieja: pendiente de actualizar.
  393. upgradeIngest(t, ts, tok, upgradePayload("0.0.9"))
  394. if patio := agentItem(); patio["updateAvailable"] != true {
  395. t.Fatalf("fresco con 0.0.9 debe dar updateAvailable=true: %v", patio)
  396. }
  397. // El reloj avanza más allá del TTL del registry: la última versión
  398. // conocida sigue siendo vieja, pero sin pulso no hay aviso.
  399. now := time.Now()
  400. ts.agents.SetClock(func() time.Time { return now.Add(2 * time.Hour) })
  401. if patio := agentItem(); patio["fresh"] != false {
  402. t.Fatalf("tras 2h sin push debe dar fresh=false: %v", patio)
  403. }
  404. if patio := agentItem(); patio["updateAvailable"] != false {
  405. t.Fatalf("stale con 0.0.9 debe dar updateAvailable=false: %v", patio)
  406. }
  407. }
  408. // TestAgentsUpgradeAll — #251: POST /api/agents/upgrade-all.
  409. // - 403 sin admin.
  410. // - Con un agente conectado y desactualizado → status "sent".
  411. // - Con un agente desconectado → status "queued" (flush on-connect, #284).
  412. // - Con un agente al día (versión == embebida) → status "up_to_date".
  413. func TestAgentsUpgradeAll(t *testing.T) {
  414. ts := makeUpgradeTestServer(t)
  415. // Sin admin → 403.
  416. res := doReq(t, "POST", ts.URL+"/api/agents/upgrade-all", "", "")
  417. if res.StatusCode != 403 && res.StatusCode != 401 {
  418. t.Fatalf("sin admin: got %d want 403/401", res.StatusCode)
  419. }
  420. // "patio" desactualizado (versión más vieja que la embebida) y conectado → sent.
  421. st, tok := createUpgradeToken(t, ts, "patio")
  422. if st != 201 {
  423. t.Fatalf("create patio: %d", st)
  424. }
  425. upgradeIngest(t, ts, tok, upgradePayload("0.0.9"))
  426. cancel, done := openStream(t, ts, "patio", tok)
  427. defer func() { cancel(); <-done }()
  428. // "otro" desactualizado pero SIN conectar → queued (se envía al conectar).
  429. if st, tokO := createUpgradeToken(t, ts, "otro"); st != 201 {
  430. t.Fatalf("create otro: %d", st)
  431. } else {
  432. upgradeIngest(t, ts, tokO, upgradePayloadFor("otro", "0.0.9"))
  433. }
  434. // "aldia" con versión == embebida → up_to_date.
  435. st2, tok2 := createUpgradeToken(t, ts, "aldia")
  436. if st2 != 201 {
  437. t.Fatalf("create aldia: %d", st2)
  438. }
  439. upgradeIngest(t, ts, tok2, upgradePayloadFor("aldia", "0.1.0"))
  440. res = doReq(t, "POST", ts.URL+"/api/agents/upgrade-all", ts.cookie, "")
  441. if res.StatusCode != 200 {
  442. t.Fatalf("upgrade-all: got %d", res.StatusCode)
  443. }
  444. body := readJSON(t, res)
  445. bySlug := map[string]string{}
  446. for _, a := range body["agents"].([]any) {
  447. m := a.(map[string]any)
  448. bySlug[m["slug"].(string)] = m["status"].(string)
  449. }
  450. if bySlug["patio"] != "sent" {
  451. t.Fatalf("patio debería ser sent: %v", bySlug)
  452. }
  453. if bySlug["otro"] != "queued" {
  454. t.Fatalf("otro debería ser queued: %v", bySlug)
  455. }
  456. if bySlug["aldia"] != "up_to_date" {
  457. t.Fatalf("al_dia debería ser up_to_date: %v", bySlug)
  458. }
  459. }
  460. // TestAgentsUpgradeAllNetgrip — #1436: upgrade-all trata los agentes
  461. // kind=netgrip con su propio criterio (versión vs última release de NetGrip),
  462. // no contra el binario embebido del agente nativo (una versión de NetGrip
  463. // tipo v0.75.0 SIEMPRE es "menor" que 3.0.x y re-dispararía su self-update en
  464. // cada upgrade-all).
  465. func TestAgentsUpgradeAllNetgrip(t *testing.T) {
  466. httpapi.NetgripTestSetFetch(func() string { return "v0.77.1" })
  467. t.Cleanup(func() { httpapi.NetgripTestSetFetch(func() string { return "" }) })
  468. ts := makeUpgradeTestServer(t)
  469. netgripPayload := func(router, version string) string {
  470. return fmt.Sprintf(`{"router":%q,"ts":%d,"version":%q,"kind":"netgrip","data":{"system":{"sysinfo":{"uptime":100,"load":[0,0,0],"memory":{"total":100,"free":50,"buffered":0,"available":50}},"cpu":10,"temp":40},"wireless":{"clients":{}},"dhcp":{"leases":[]},"fdb":{"macs":{}}}}`, router, time.Now().Unix(), version)
  471. }
  472. // "ngold" (netgrip viejo) conectado → su self-update se dispara (sent).
  473. st, tok := createUpgradeToken(t, ts, "ngold")
  474. if st != 201 {
  475. t.Fatalf("create ngold: %d", st)
  476. }
  477. upgradeIngest(t, ts, tok, netgripPayload("ngold", "v0.75.0"))
  478. cancel, done := openStream(t, ts, "ngold", tok)
  479. defer func() { cancel(); <-done }()
  480. // "ngnew" (netgrip al día, sin conectar) → up_to_date, NO queued.
  481. st2, tok2 := createUpgradeToken(t, ts, "ngnew")
  482. if st2 != 201 {
  483. t.Fatalf("create ngnew: %d", st2)
  484. }
  485. upgradeIngest(t, ts, tok2, netgripPayload("ngnew", "v0.77.1"))
  486. res := doReq(t, "POST", ts.URL+"/api/agents/upgrade-all", ts.cookie, "")
  487. if res.StatusCode != 200 {
  488. t.Fatalf("upgrade-all: got %d", res.StatusCode)
  489. }
  490. body := readJSON(t, res)
  491. bySlug := map[string]string{}
  492. for _, a := range body["agents"].([]any) {
  493. m := a.(map[string]any)
  494. bySlug[m["slug"].(string)] = m["status"].(string)
  495. }
  496. if bySlug["ngold"] != "sent" {
  497. t.Fatalf("ngold debería ser sent: %v", bySlug)
  498. }
  499. if bySlug["ngnew"] != "up_to_date" {
  500. t.Fatalf("ngnew debería ser up_to_date (no queued): %v", bySlug)
  501. }
  502. }