4
0

mqtt_propagate_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. // mqtt_propagate_test.go — regresión F-06: POST /api/settings/mqtt/propagate
  2. // entrega la op mqtt.configure a cada router NetGrip por SSE, sin hablar HTTP
  3. // con sus executors. Cada router recibe un plan REAL (fila en orchestr_plans,
  4. // marcado applying antes del envío) y la respuesta dice "encolado", nunca
  5. // "aplicado".
  6. package httpapi_test
  7. import (
  8. "bytes"
  9. "encoding/json"
  10. "io"
  11. "net/http"
  12. "strings"
  13. "sync/atomic"
  14. "testing"
  15. "github.com/gnacho/netpulse/agent/executor"
  16. "github.com/gnacho/netpulse/agent/probe"
  17. "github.com/gnacho/netpulse/server-go/internal/adapters"
  18. )
  19. type propagateResult struct {
  20. ID string `json:"id"`
  21. Name string `json:"name"`
  22. PlanID string `json:"planId"`
  23. Queued bool `json:"queued"`
  24. Delegated bool `json:"delegated"`
  25. Status string `json:"status"`
  26. Error string `json:"error"`
  27. }
  28. // propagateMQTT llama al endpoint y devuelve los resultados por id más el
  29. // cuerpo crudo (para comprobar que no se afirma que el plan se aplicó).
  30. func propagateMQTT(t *testing.T, ts *testServer, cookie string) (map[string]propagateResult, string) {
  31. t.Helper()
  32. req, _ := http.NewRequest("POST", ts.URL+"/api/settings/mqtt/propagate", nil)
  33. req.Header.Set("Cookie", "session="+cookie)
  34. res, err := http.DefaultClient.Do(req)
  35. if err != nil {
  36. t.Fatalf("propagate: %v", err)
  37. }
  38. defer res.Body.Close()
  39. if res.StatusCode != http.StatusOK {
  40. t.Fatalf("propagate: esperaba 200, got %d", res.StatusCode)
  41. }
  42. raw, err := io.ReadAll(res.Body)
  43. if err != nil {
  44. t.Fatalf("leer respuesta propagate: %v", err)
  45. }
  46. var body struct {
  47. Results []propagateResult `json:"results"`
  48. }
  49. if err := json.Unmarshal(raw, &body); err != nil {
  50. t.Fatalf("respuesta propagate: %v (%s)", err, raw)
  51. }
  52. out := map[string]propagateResult{}
  53. for _, r := range body.Results {
  54. if _, dup := out[r.ID]; dup {
  55. t.Fatalf("router duplicado en la respuesta: %s", r.ID)
  56. }
  57. out[r.ID] = r
  58. }
  59. return out, string(raw)
  60. }
  61. func TestMQTTPropagateSendsOpsOverSSE(t *testing.T) {
  62. ov := &adapters.Overview{Routers: []adapters.Router{
  63. {ID: "flint2", Name: "Flint 2"},
  64. {ID: "rt2", Name: "RT2"},
  65. {ID: "rt1", Name: "RT1"}, // agente nativo: no participa
  66. }}
  67. ts, reg := newSSEPlanServer(t, ov)
  68. netgripMock, hits := countingNetGripMock(t)
  69. host := netgripMock.Listener.Addr().String()
  70. addPlanRouter(t, ts, "flint2", host, true, "netgrip-secret")
  71. addPlanRouter(t, ts, "rt2", host, false, "netgrip-secret")
  72. addPlanRouter(t, ts, "rt1", host, false, "netgrip-secret")
  73. // flint2 y rt2 con agente conectado; rt1 es nativo y queda fuera.
  74. setAgentToken(t, ts, "flint2", "agent-token")
  75. setAgentToken(t, ts, "rt2", "agent-token")
  76. reg.Ingest(&probe.Payload{Router: "flint2", Kind: "netgrip", Version: "0.77.3"})
  77. reg.Ingest(&probe.Payload{Router: "rt2", Kind: "netgrip", Version: "0.77.3"})
  78. reg.Ingest(&probe.Payload{Router: "rt1", Kind: "native", Version: "3.0.26"})
  79. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  80. flintEvents := connectAgentStream(t, ts.URL, "flint2")
  81. rt2Events := connectAgentStream(t, ts.URL, "rt2")
  82. results, raw := propagateMQTT(t, ts, cookie)
  83. if strings.Contains(raw, `"applied"`) {
  84. t.Errorf("la propagación solo encola: la respuesta no puede afirmar que se aplicó: %s", raw)
  85. }
  86. if got := atomic.LoadInt32(hits); got != 0 {
  87. t.Fatalf("NetGrip recibió %d peticiones HTTP; la propagación debe ir por SSE", got)
  88. }
  89. if len(results) != 2 {
  90. t.Fatalf("esperaba 2 routers NetGrip en el resultado, got %+v", results)
  91. }
  92. if _, ok := results["rt1"]; ok {
  93. t.Error("rt1 es agente nativo: no debe aparecer en la propagación")
  94. }
  95. // El agente conectado recibe la op mqtt.configure con el broker del server.
  96. streams := map[string]<-chan agentEvent{"flint2": flintEvents, "rt2": rt2Events}
  97. planIDs := map[string]string{}
  98. for id, r := range results {
  99. if r.Error != "" {
  100. t.Errorf("%s: error inesperado %q", id, r.Error)
  101. }
  102. if !r.Queued || !r.Delegated {
  103. t.Errorf("%s: se entregó al agente, esperaba queued/delegated true, got %+v", id, r)
  104. }
  105. // La respuesta habla de encolado, no de aplicación.
  106. if r.Status != "queued" {
  107. t.Errorf("%s: estado esperado queued, got %+v", id, r)
  108. }
  109. if r.PlanID == "" {
  110. t.Fatalf("%s: la respuesta debe llevar el planId real", id)
  111. }
  112. planIDs[id] = r.PlanID
  113. // El plan existe de verdad y está en curso (applying), no inventado.
  114. p := readPlan(t, ts, r.PlanID)
  115. if p.Status != "applying" {
  116. t.Errorf("%s: el plan debe quedar applying, got %s", id, p.Status)
  117. }
  118. if p.Resource != "mqtt" {
  119. t.Errorf("%s: recurso del plan: got %q, want mqtt", id, p.Resource)
  120. }
  121. if p.CreatedBy != "admin" {
  122. t.Errorf("%s: createdBy del plan: got %q, want admin", id, p.CreatedBy)
  123. }
  124. if !bytes.Contains([]byte(p.Diff), []byte("mqtt.configure")) {
  125. t.Errorf("%s: el diff persistido no lleva la op mqtt.configure: %s", id, p.Diff)
  126. }
  127. if !bytes.Contains([]byte(p.Desired), []byte("broker.test")) {
  128. t.Errorf("%s: el desired persistido no lleva el broker: %s", id, p.Desired)
  129. }
  130. // La contraseña del broker no se duplica en la tabla de planes.
  131. if bytes.Contains([]byte(p.Diff), []byte("broker-pass")) ||
  132. bytes.Contains([]byte(p.Desired), []byte("broker-pass")) {
  133. t.Errorf("%s: la contraseña del broker no debe persistirse en el plan", id)
  134. }
  135. ev := waitAgentEvent(t, streams[id], "apply")
  136. var payload struct {
  137. PlanID string `json:"plan_id"`
  138. Ops []executor.Op `json:"ops"`
  139. }
  140. if err := json.Unmarshal([]byte(ev.data), &payload); err != nil {
  141. t.Fatalf("%s: payload SSE apply inválido (%q): %v", id, ev.data, err)
  142. }
  143. if payload.PlanID != r.PlanID {
  144. t.Errorf("%s: plan_id SSE got %q, want %q", id, payload.PlanID, r.PlanID)
  145. }
  146. if len(payload.Ops) != 1 || payload.Ops[0].Kind != "mqtt.configure" {
  147. t.Fatalf("%s: ops SSE: %+v", id, payload.Ops)
  148. }
  149. if got := payload.Ops[0].Args["host"]; got != "broker.test" {
  150. t.Errorf("%s: broker en la op: got %q, want broker.test", id, got)
  151. }
  152. // El secreto viaja al agente (por el canal autenticado), aunque no se
  153. // guarde en el plan.
  154. if got := payload.Ops[0].Args["pass"]; got != "broker-pass" {
  155. t.Errorf("%s: la op enviada debe llevar la contraseña real, got %q", id, got)
  156. }
  157. }
  158. if planIDs["flint2"] == planIDs["rt2"] {
  159. t.Fatalf("cada router necesita su propio plan, ambos comparten %q", planIDs["flint2"])
  160. }
  161. // El agente confirma: el plan de ese router pasa a applied.
  162. if code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planIDs["flint2"],
  163. executor.ApplyResult{Status: "applied"}); code != http.StatusOK {
  164. t.Fatalf("apply-result: esperaba 200, got %d: %s", code, raw)
  165. }
  166. if got := planStatus(t, ts, planIDs["flint2"]); got != "applied" {
  167. t.Fatalf("el plan confirmado por el agente debe quedar applied, got %s", got)
  168. }
  169. }
  170. // TestMQTTPropagateWithoutAgentIsHonest: sin agente conectado no se simula
  171. // éxito: la respuesta lo dice y el plan no queda en curso.
  172. func TestMQTTPropagateWithoutAgentIsHonest(t *testing.T) {
  173. ov := &adapters.Overview{Routers: []adapters.Router{{ID: "flint2", Name: "Flint 2"}}}
  174. ts, reg := newSSEPlanServer(t, ov)
  175. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  176. reg.Ingest(&probe.Payload{Router: "flint2", Kind: "netgrip", Version: "0.77.3"})
  177. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  178. results, _ := propagateMQTT(t, ts, cookie)
  179. r, ok := results["flint2"]
  180. if !ok {
  181. t.Fatalf("falta flint2 en la respuesta: %+v", results)
  182. }
  183. if r.Queued || r.Delegated || r.Status == "queued" {
  184. t.Errorf("sin agente conectado no se puede afirmar que se encoló: %+v", r)
  185. }
  186. if r.Error != "agent_not_connected" {
  187. t.Errorf("error esperado agent_not_connected, got %+v", r)
  188. }
  189. if r.PlanID == "" {
  190. t.Fatal("la respuesta debe identificar el plan creado para el intento")
  191. }
  192. if got := planStatus(t, ts, r.PlanID); got != "pending" {
  193. t.Errorf("un envío fallido no puede dejar el plan en curso, got %s", got)
  194. }
  195. }
  196. // TestMQTTPropagateTLSRequiresUpdatedNetGrip: con TLS activo, un agente que
  197. // solo entiende los siete argumentos originales no puede recibir la op (la
  198. // decodificaría sin TLS y el router publicaría en claro sin avisar). La
  199. // respuesta lo dice por router y los agentes nuevos reciben los dos args.
  200. func TestMQTTPropagateTLSRequiresUpdatedNetGrip(t *testing.T) {
  201. ov := &adapters.Overview{Routers: []adapters.Router{
  202. {ID: "flint2", Name: "Flint 2"},
  203. {ID: "rt2", Name: "RT2"},
  204. }}
  205. ts, reg := newSSEPlanServer(t, ov)
  206. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  207. addPlanRouter(t, ts, "rt2", "192.0.2.11", true, "")
  208. setAgentToken(t, ts, "flint2", "agent-token")
  209. setAgentToken(t, ts, "rt2", "agent-token")
  210. reg.Ingest(&probe.Payload{Router: "flint2", Kind: "netgrip", Version: "0.77.3"})
  211. reg.Ingest(&probe.Payload{Router: "rt2", Kind: "netgrip", Version: "0.78.0"})
  212. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  213. if res, body := wanSpeedRequest(t, "PUT", ts.URL, "/api/settings/mqtt", cookie,
  214. `{"tls":true,"tlsInsecure":true,"port":8883}`); res.StatusCode != http.StatusOK {
  215. t.Fatalf("PUT mqtt TLS: status %d (%v)", res.StatusCode, body)
  216. }
  217. _ = connectAgentStream(t, ts.URL, "flint2")
  218. rt2Events := connectAgentStream(t, ts.URL, "rt2")
  219. results, _ := propagateMQTT(t, ts, cookie)
  220. old, ok := results["flint2"]
  221. if !ok {
  222. t.Fatalf("falta flint2 en la respuesta: %+v", results)
  223. }
  224. if old.Error != "netgrip_update_required" {
  225. t.Errorf("flint2 con NetGrip 0.77.3: error esperado netgrip_update_required, got %+v", old)
  226. }
  227. if old.Queued || old.PlanID != "" {
  228. t.Errorf("no se puede encolar TLS a un agente que no lo entiende: %+v", old)
  229. }
  230. r, ok := results["rt2"]
  231. if !ok {
  232. t.Fatalf("falta rt2 en la respuesta: %+v", results)
  233. }
  234. if r.Error != "" || !r.Queued {
  235. t.Fatalf("rt2 con NetGrip 0.78.0 debe recibir la op, got %+v", r)
  236. }
  237. ev := waitAgentEvent(t, rt2Events, "apply")
  238. var payload struct {
  239. Ops []executor.Op `json:"ops"`
  240. }
  241. if err := json.Unmarshal([]byte(ev.data), &payload); err != nil {
  242. t.Fatalf("payload SSE apply inválido (%q): %v", ev.data, err)
  243. }
  244. if len(payload.Ops) != 1 {
  245. t.Fatalf("ops SSE: %+v", payload.Ops)
  246. }
  247. if got := payload.Ops[0].Args["tls"]; got != "1" {
  248. t.Errorf("arg tls: got %q, want 1", got)
  249. }
  250. if got := payload.Ops[0].Args["tlsInsecure"]; got != "true" {
  251. t.Errorf("arg tlsInsecure: got %q, want true", got)
  252. }
  253. }
  254. // TestMQTTPropagateDoesNotPersistBrokerPassword revisa la copia persistida
  255. // del plan: el secreto viaja por SSE, no se guarda en orchestr_plans.
  256. func TestMQTTPropagateDoesNotPersistBrokerPassword(t *testing.T) {
  257. ov := &adapters.Overview{Routers: []adapters.Router{{ID: "flint2", Name: "Flint 2"}}}
  258. ts, reg := newSSEPlanServer(t, ov)
  259. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  260. reg.Ingest(&probe.Payload{Router: "flint2", Kind: "netgrip", Version: "0.77.3"})
  261. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  262. connectAgentStream(t, ts.URL, "flint2")
  263. results, _ := propagateMQTT(t, ts, cookie)
  264. r := results["flint2"]
  265. if r.PlanID == "" {
  266. t.Fatalf("sin planId en la respuesta: %+v", r)
  267. }
  268. // La fila completa, tal cual queda en la base de datos.
  269. var desired, diff, result string
  270. if err := ts.db.QueryRow(
  271. `SELECT desired, diff, COALESCE(result, '') FROM orchestr_plans WHERE id = ?`,
  272. r.PlanID).Scan(&desired, &diff, &result); err != nil {
  273. t.Fatalf("select plan: %v", err)
  274. }
  275. blob := strings.Join([]string{desired, diff, result}, "\n")
  276. if strings.Contains(blob, "broker-pass") {
  277. t.Fatalf("la contraseña del broker quedó persistida en el plan:\n%s", blob)
  278. }
  279. if !strings.Contains(diff, "mqtt.configure") {
  280. t.Errorf("el plan debe registrar la op enviada: %s", diff)
  281. }
  282. }