orchestr_apply_result_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. // orchestr_apply_result_test.go — ciclo completo de un plan real:
  2. // POST /api/plans -> apply (marca applying ANTES de enviar) -> el agente
  3. // reporta por POST /api/agents/{slug}/apply-result -> applied / rolled_back,
  4. // y los caminos honestos cuando el plan no existe o el envío SSE falla.
  5. package httpapi_test
  6. import (
  7. "bytes"
  8. "encoding/json"
  9. "io"
  10. "net/http"
  11. "sync"
  12. "testing"
  13. "time"
  14. "github.com/gnacho/netpulse/agent/executor"
  15. )
  16. // planRow es el estado persistido de un plan.
  17. type planRow struct {
  18. Status string
  19. Resource string
  20. CreatedBy string
  21. Desired string
  22. Diff string
  23. AppliedAt *int64
  24. Result *string
  25. }
  26. func readPlan(t *testing.T, ts *testServer, id string) planRow {
  27. t.Helper()
  28. var p planRow
  29. if err := ts.db.QueryRow(
  30. `SELECT status, resource, created_by, desired, diff, applied_at, result
  31. FROM orchestr_plans WHERE id = ?`, id).Scan(
  32. &p.Status, &p.Resource, &p.CreatedBy, &p.Desired, &p.Diff, &p.AppliedAt, &p.Result); err != nil {
  33. t.Fatalf("select plan %s: %v", id, err)
  34. }
  35. return p
  36. }
  37. // createPlanViaAPI crea un plan real con diff explícito (sin probe SSH).
  38. func createPlanViaAPI(t *testing.T, base, cookie, routerID, resource string, ops []executor.Op) string {
  39. t.Helper()
  40. body, _ := json.Marshal(map[string]any{
  41. "routerId": routerID,
  42. "resource": resource,
  43. "diff": ops,
  44. })
  45. req, _ := http.NewRequest("POST", base+"/api/plans", bytes.NewReader(body))
  46. req.Header.Set("Cookie", "session="+cookie)
  47. req.Header.Set("Content-Type", "application/json")
  48. res, err := http.DefaultClient.Do(req)
  49. if err != nil {
  50. t.Fatalf("create plan: %v", err)
  51. }
  52. defer res.Body.Close()
  53. raw, _ := io.ReadAll(res.Body)
  54. if res.StatusCode != http.StatusCreated {
  55. t.Fatalf("create plan: esperaba 201, got %d: %s", res.StatusCode, raw)
  56. }
  57. var plan struct {
  58. ID string `json:"id"`
  59. }
  60. if err := json.Unmarshal(raw, &plan); err != nil {
  61. t.Fatalf("plan JSON: %v (%s)", err, raw)
  62. }
  63. if plan.ID == "" {
  64. t.Fatalf("el plan creado llegó sin id: %s", raw)
  65. }
  66. return plan.ID
  67. }
  68. // createPlanFromDesired crea un plan real dejando que el módulo calcule el
  69. // diff (el probe SSH es fakeProbeSSH, sin red), de modo que desired y diff
  70. // quedan persistidos y el rollback puede invertirse.
  71. func createPlanFromDesired(t *testing.T, base, cookie, routerID, resource string, desired any) string {
  72. t.Helper()
  73. body, _ := json.Marshal(map[string]any{
  74. "routerId": routerID,
  75. "resource": resource,
  76. "desired": desired,
  77. })
  78. req, _ := http.NewRequest("POST", base+"/api/plans", bytes.NewReader(body))
  79. req.Header.Set("Cookie", "session="+cookie)
  80. req.Header.Set("Content-Type", "application/json")
  81. res, err := http.DefaultClient.Do(req)
  82. if err != nil {
  83. t.Fatalf("create plan: %v", err)
  84. }
  85. defer res.Body.Close()
  86. raw, _ := io.ReadAll(res.Body)
  87. if res.StatusCode != http.StatusCreated {
  88. t.Fatalf("create plan: esperaba 201, got %d: %s", res.StatusCode, raw)
  89. }
  90. var plan struct {
  91. ID string `json:"id"`
  92. }
  93. if err := json.Unmarshal(raw, &plan); err != nil {
  94. t.Fatalf("plan JSON: %v (%s)", err, raw)
  95. }
  96. if plan.ID == "" {
  97. t.Fatalf("el plan creado llegó sin id: %s", raw)
  98. }
  99. return plan.ID
  100. }
  101. func postApply(t *testing.T, base, cookie, planID string) (int, []byte) {
  102. t.Helper()
  103. req, _ := http.NewRequest("POST", base+"/api/plans/"+planID+"/apply", nil)
  104. req.Header.Set("Cookie", "session="+cookie)
  105. res, err := http.DefaultClient.Do(req)
  106. if err != nil {
  107. t.Fatalf("apply: %v", err)
  108. }
  109. defer res.Body.Close()
  110. raw, _ := io.ReadAll(res.Body)
  111. return res.StatusCode, raw
  112. }
  113. func postRollback(t *testing.T, base, cookie, planID string) (int, []byte) {
  114. t.Helper()
  115. req, _ := http.NewRequest("POST", base+"/api/plans/"+planID+"/rollback", nil)
  116. req.Header.Set("Cookie", "session="+cookie)
  117. res, err := http.DefaultClient.Do(req)
  118. if err != nil {
  119. t.Fatalf("rollback: %v", err)
  120. }
  121. defer res.Body.Close()
  122. raw, _ := io.ReadAll(res.Body)
  123. return res.StatusCode, raw
  124. }
  125. // tryPostApplyResult hace el POST sin tocar *testing.T (se usa desde la
  126. // goroutine del hook del stream).
  127. func tryPostApplyResult(base, slug, token, planID string, result executor.ApplyResult) (int, []byte, error) {
  128. body, err := json.Marshal(map[string]any{"planId": planID, "result": result})
  129. if err != nil {
  130. return 0, nil, err
  131. }
  132. req, err := http.NewRequest("POST", base+"/api/agents/"+slug+"/apply-result", bytes.NewReader(body))
  133. if err != nil {
  134. return 0, nil, err
  135. }
  136. req.Header.Set("Authorization", "Bearer "+token)
  137. req.Header.Set("Content-Type", "application/json")
  138. res, err := http.DefaultClient.Do(req)
  139. if err != nil {
  140. return 0, nil, err
  141. }
  142. defer res.Body.Close()
  143. raw, err := io.ReadAll(res.Body)
  144. if err != nil {
  145. return res.StatusCode, nil, err
  146. }
  147. return res.StatusCode, raw, nil
  148. }
  149. // postApplyResult es lo que hace el agente al terminar de aplicar las ops.
  150. func postApplyResult(t *testing.T, base, slug, token, planID string, result executor.ApplyResult) (int, []byte) {
  151. t.Helper()
  152. code, raw, err := tryPostApplyResult(base, slug, token, planID, result)
  153. if err != nil {
  154. t.Fatalf("apply-result: %v", err)
  155. }
  156. return code, raw
  157. }
  158. // waitPlanStatus espera (con deadline) a que el plan llegue a un estado.
  159. func waitPlanStatus(t *testing.T, ts *testServer, id, want string) {
  160. t.Helper()
  161. deadline := time.Now().Add(5 * time.Second)
  162. for {
  163. got := planStatus(t, ts, id)
  164. if got == want {
  165. return
  166. }
  167. if time.Now().After(deadline) {
  168. t.Fatalf("plan %s: esperaba %q, sigue en %q", id, want, got)
  169. }
  170. time.Sleep(20 * time.Millisecond)
  171. }
  172. }
  173. func auditActionsOf(t *testing.T, ts *testServer, planID string) []string {
  174. t.Helper()
  175. rows, err := ts.db.Query(`SELECT action FROM orchestr_audit WHERE plan_id = ? ORDER BY id`, planID)
  176. if err != nil {
  177. t.Fatalf("audit: %v", err)
  178. }
  179. defer rows.Close()
  180. var out []string
  181. for rows.Next() {
  182. var a string
  183. if err := rows.Scan(&a); err != nil {
  184. t.Fatalf("scan audit: %v", err)
  185. }
  186. out = append(out, a)
  187. }
  188. return out
  189. }
  190. func containsAction(actions []string, want string) bool {
  191. for _, a := range actions {
  192. if a == want {
  193. return true
  194. }
  195. }
  196. return false
  197. }
  198. // TestApplyResultMarksPlanApplied: el agente reporta el resultado y el plan
  199. // queda applied con applied_at y el resultado persistidos.
  200. func TestApplyResultMarksPlanApplied(t *testing.T) {
  201. ts, _ := newSSEPlanServer(t, nil)
  202. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  203. setAgentToken(t, ts, "flint2", "agent-token")
  204. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  205. planID := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
  206. {Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
  207. })
  208. code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planID, executor.ApplyResult{
  209. Status: "applied", DurationMs: 12,
  210. })
  211. if code != http.StatusOK {
  212. t.Fatalf("apply-result: esperaba 200, got %d: %s", code, raw)
  213. }
  214. p := readPlan(t, ts, planID)
  215. if p.Status != "applied" {
  216. t.Fatalf("estado del plan: got %q, want applied", p.Status)
  217. }
  218. if p.AppliedAt == nil {
  219. t.Error("el plan aplicado debe llevar applied_at")
  220. }
  221. if p.Result == nil || !bytes.Contains([]byte(*p.Result), []byte(`"applied"`)) {
  222. t.Errorf("el resultado del agente debe persistirse, got %v", p.Result)
  223. }
  224. if acts := auditActionsOf(t, ts, planID); !containsAction(acts, "applied") {
  225. t.Errorf("se esperaba auditoría \"applied\", got %v", acts)
  226. }
  227. }
  228. // TestApplyResultUnknownPlanIsNotFound: un plan inexistente es un error del
  229. // cliente (404), no un 500 de "update_error" que el agente reintenta diez veces.
  230. func TestApplyResultUnknownPlanIsNotFound(t *testing.T) {
  231. ts, _ := newSSEPlanServer(t, nil)
  232. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  233. setAgentToken(t, ts, "flint2", "agent-token")
  234. code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", "plan-que-no-existe",
  235. executor.ApplyResult{Status: "applied"})
  236. if code != http.StatusNotFound {
  237. t.Fatalf("apply-result con plan inexistente: esperaba 404, got %d: %s", code, raw)
  238. }
  239. var body struct {
  240. Error string `json:"error"`
  241. }
  242. if err := json.Unmarshal(raw, &body); err != nil {
  243. t.Fatalf("cuerpo de error: %v (%s)", err, raw)
  244. }
  245. if body.Error != "not_found" {
  246. t.Errorf("código de error: got %q, want not_found", body.Error)
  247. }
  248. }
  249. // TestApplyResultRejectsBadAgentToken: el token del agente se sigue exigiendo.
  250. func TestApplyResultRejectsBadAgentToken(t *testing.T) {
  251. ts, _ := newSSEPlanServer(t, nil)
  252. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  253. setAgentToken(t, ts, "flint2", "agent-token")
  254. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  255. planID := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
  256. {Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
  257. })
  258. code, raw := postApplyResult(t, ts.URL, "flint2", "token-equivocado", planID,
  259. executor.ApplyResult{Status: "applied"})
  260. if code != http.StatusUnauthorized {
  261. t.Fatalf("apply-result con token inválido: esperaba 401, got %d: %s", code, raw)
  262. }
  263. if got := planStatus(t, ts, planID); got != "pending" {
  264. t.Fatalf("un token inválido no puede tocar el plan, got %s", got)
  265. }
  266. }
  267. // TestPlanLifecycleApplyAndRollbackReportedByAgent recorre el ciclo completo
  268. // con un plan real creado por la API: apply-result lo deja applied, el
  269. // rollback manda las ops inversas por SSE y el nuevo apply-result lo cierra
  270. // como rolled_back (no se queda en rolling_back).
  271. func TestPlanLifecycleApplyAndRollbackReportedByAgent(t *testing.T) {
  272. ts, _ := newSSEPlanServer(t, nil)
  273. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  274. setAgentToken(t, ts, "flint2", "agent-token")
  275. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  276. events := connectAgentStream(t, ts.URL, "flint2")
  277. planID := createPlanFromDesired(t, ts.URL, cookie, "flint2", "guestwifi", map[string]any{
  278. "enabled": true, "ssid": "NetPulse-Guest", "allowNonGateway": false,
  279. })
  280. if code, raw := postApply(t, ts.URL, cookie, planID); code != http.StatusAccepted {
  281. t.Fatalf("apply: esperaba 202, got %d: %s", code, raw)
  282. }
  283. ev := waitAgentEvent(t, events, "apply")
  284. if !bytes.Contains([]byte(ev.data), []byte(planID)) {
  285. t.Fatalf("el evento SSE no lleva el plan real: %s", ev.data)
  286. }
  287. if code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planID,
  288. executor.ApplyResult{Status: "applied"}); code != http.StatusOK {
  289. t.Fatalf("apply-result: esperaba 200, got %d: %s", code, raw)
  290. }
  291. if got := planStatus(t, ts, planID); got != "applied" {
  292. t.Fatalf("tras el apply-result: esperaba applied, got %s", got)
  293. }
  294. if code, raw := postRollback(t, ts.URL, cookie, planID); code != http.StatusAccepted {
  295. t.Fatalf("rollback: esperaba 202, got %d: %s", code, raw)
  296. }
  297. ev = waitAgentEvent(t, events, "apply")
  298. var payload struct {
  299. PlanID string `json:"plan_id"`
  300. Ops []executor.Op `json:"ops"`
  301. }
  302. if err := json.Unmarshal([]byte(ev.data), &payload); err != nil {
  303. t.Fatalf("payload SSE del rollback: %v (%s)", err, ev.data)
  304. }
  305. if payload.PlanID != planID {
  306. t.Errorf("plan_id del rollback: got %q, want %q", payload.PlanID, planID)
  307. }
  308. if got := planStatus(t, ts, planID); got != "rolling_back" {
  309. t.Fatalf("el rollback en curso debe quedar rolling_back, got %s", got)
  310. }
  311. // El agente termina el rollback y reporta: el plan NO se queda colgado.
  312. if code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planID,
  313. executor.ApplyResult{Status: "applied"}); code != http.StatusOK {
  314. t.Fatalf("apply-result del rollback: esperaba 200, got %d: %s", code, raw)
  315. }
  316. if got := planStatus(t, ts, planID); got != "rolled_back" {
  317. t.Fatalf("tras el rollback: esperaba rolled_back, got %s", got)
  318. }
  319. acts := auditActionsOf(t, ts, planID)
  320. if !containsAction(acts, "rollback") || !containsAction(acts, "rolled_back") {
  321. t.Errorf("la auditoría debe registrar rollback y rolled_back, got %v", acts)
  322. }
  323. }
  324. // TestApplyMarksApplyingBeforeAgentSeesEvent: con un agente que responde al
  325. // instante (el apply-result entra mientras el servidor aún está escribiendo el
  326. // evento), el plan no se queda en applying: el estado applying se fija ANTES
  327. // de enviar, así que SetResult no pisa un resultado que ya llegó.
  328. func TestApplyMarksApplyingBeforeAgentSeesEvent(t *testing.T) {
  329. var (
  330. mu sync.Mutex
  331. planID string
  332. base string
  333. hookCode int
  334. hookBody []byte
  335. hookErr error
  336. hooks int
  337. )
  338. onApply := func() {
  339. mu.Lock()
  340. id, url := planID, base
  341. hooks++
  342. mu.Unlock()
  343. if id == "" || url == "" {
  344. return
  345. }
  346. code, raw, err := tryPostApplyResult(url, "flint2", "agent-token", id,
  347. executor.ApplyResult{Status: "applied", DurationMs: 3})
  348. mu.Lock()
  349. hookCode, hookBody, hookErr = code, raw, err
  350. mu.Unlock()
  351. }
  352. ts, _ := newSSEPlanServer(t, nil, withHandlerWrap(withStreamHook(streamHookFastAgent, onApply)))
  353. base = ts.URL
  354. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  355. setAgentToken(t, ts, "flint2", "agent-token")
  356. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  357. connectAgentStream(t, ts.URL, "flint2")
  358. created := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
  359. {Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
  360. })
  361. mu.Lock()
  362. planID = created
  363. mu.Unlock()
  364. if code, raw := postApply(t, ts.URL, cookie, planID); code != http.StatusAccepted {
  365. t.Fatalf("apply: esperaba 202, got %d: %s", code, raw)
  366. }
  367. mu.Lock()
  368. got := hooks
  369. code, body, err := hookCode, hookBody, hookErr
  370. mu.Unlock()
  371. if got == 0 {
  372. t.Fatal("el agente rápido no llegó a responder dentro del envío")
  373. }
  374. if err != nil {
  375. t.Fatalf("apply-result del agente rápido: %v", err)
  376. }
  377. if code != http.StatusOK {
  378. t.Fatalf("apply-result del agente rápido: esperaba 200, got %d: %s", code, body)
  379. }
  380. // El resultado del agente es el último estado; nunca se queda en applying.
  381. waitPlanStatus(t, ts, planID, "applied")
  382. }
  383. // TestApplyRestoresPendingWhenSSEDeliveryFails: si la escritura del evento
  384. // falla, el plan vuelve a pending (estado honesto), se audita la
  385. // restauración y la respuesta es un 503, nunca un 202 de éxito.
  386. func TestApplyRestoresPendingWhenSSEDeliveryFails(t *testing.T) {
  387. ts, _ := newSSEPlanServer(t, nil, withHandlerWrap(withStreamHook(streamHookFailOnApply, nil)))
  388. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  389. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  390. connectAgentStream(t, ts.URL, "flint2")
  391. planID := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
  392. {Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
  393. })
  394. code, raw := postApply(t, ts.URL, cookie, planID)
  395. if code != http.StatusServiceUnavailable {
  396. t.Fatalf("apply con el stream roto: esperaba 503, got %d: %s", code, raw)
  397. }
  398. if got := planStatus(t, ts, planID); got != "pending" {
  399. t.Fatalf("tras fallar el envío el plan debe volver a pending, got %s", got)
  400. }
  401. if acts := auditActionsOf(t, ts, planID); !containsAction(acts, "restore") {
  402. t.Errorf("la restauración debe quedar auditada, got %v", acts)
  403. }
  404. }
  405. // TestApplyKeepsPlanPendingWithoutAgent: sin agente conectado no hay plan en
  406. // curso ni 202: el plan sigue pendiente y se puede reintentar.
  407. func TestApplyKeepsPlanPendingWithoutAgent(t *testing.T) {
  408. ts, _ := newSSEPlanServer(t, nil)
  409. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  410. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  411. planID := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
  412. {Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
  413. })
  414. code, raw := postApply(t, ts.URL, cookie, planID)
  415. if code != http.StatusServiceUnavailable {
  416. t.Fatalf("apply sin agente: esperaba 503, got %d: %s", code, raw)
  417. }
  418. if got := planStatus(t, ts, planID); got != "pending" {
  419. t.Fatalf("sin agente el plan debe seguir pending, got %s", got)
  420. }
  421. }
  422. // TestRollbackRestoresAppliedWhenSSEDeliveryFails: si el envío del rollback
  423. // falla, el plan vuelve a applied (no se queda rolling_back para siempre).
  424. func TestRollbackRestoresAppliedWhenSSEDeliveryFails(t *testing.T) {
  425. // La primera entrega (apply) va bien; la segunda (rollback) se rompe.
  426. ts, _ := newSSEPlanServer(t, nil, withHandlerWrap(withStreamHookFailAt(streamHookFailOnApply, nil, 2)))
  427. addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
  428. setAgentToken(t, ts, "flint2", "agent-token")
  429. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  430. events := connectAgentStream(t, ts.URL, "flint2")
  431. planID := createPlanFromDesired(t, ts.URL, cookie, "flint2", "guestwifi", map[string]any{
  432. "enabled": true, "ssid": "NetPulse-Guest", "allowNonGateway": false,
  433. })
  434. if code, raw := postApply(t, ts.URL, cookie, planID); code != http.StatusAccepted {
  435. t.Fatalf("apply: esperaba 202, got %d: %s", code, raw)
  436. }
  437. waitAgentEvent(t, events, "apply")
  438. if code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planID,
  439. executor.ApplyResult{Status: "applied"}); code != http.StatusOK {
  440. t.Fatalf("apply-result: got %d: %s", code, raw)
  441. }
  442. if got := planStatus(t, ts, planID); got != "applied" {
  443. t.Fatalf("tras el apply: esperaba applied, got %s", got)
  444. }
  445. code, raw := postRollback(t, ts.URL, cookie, planID)
  446. if code != http.StatusServiceUnavailable {
  447. t.Fatalf("rollback con el stream roto: esperaba 503, got %d: %s", code, raw)
  448. }
  449. if got := planStatus(t, ts, planID); got != "applied" {
  450. t.Fatalf("tras fallar el envío el plan debe volver a applied, got %s", got)
  451. }
  452. if acts := auditActionsOf(t, ts, planID); !containsAction(acts, "restore") {
  453. t.Errorf("la restauración debe quedar auditada, got %v", acts)
  454. }
  455. }