upgrade_api_test.go 13 KB

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