upgrade_api_test.go 16 KB

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