orchestr_apply_test.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. // orchestr_apply_test.go — tests del endpoint /api/orchestr/apply (#451).
  2. package httpapi_test
  3. import (
  4. "bytes"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "encoding/json"
  8. "io"
  9. "net/http"
  10. "net/http/httptest"
  11. "testing"
  12. "github.com/gnacho/netpulse/agent/executor"
  13. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  14. )
  15. func TestOrchestrApplyCreatesAndAppliesPlan(t *testing.T) {
  16. ts := makeTestServer(t)
  17. var receivedOps []executor.Op
  18. netgripMock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  19. if r.URL.Path != "/api/executor/apply" {
  20. http.NotFound(w, r)
  21. return
  22. }
  23. if auth := r.Header.Get("Authorization"); auth != "Bearer netgrip-secret" {
  24. http.Error(w, "unauthorized", http.StatusUnauthorized)
  25. return
  26. }
  27. var body struct {
  28. Ops []executor.Op `json:"ops"`
  29. }
  30. if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body); err != nil {
  31. http.Error(w, err.Error(), http.StatusBadRequest)
  32. return
  33. }
  34. receivedOps = body.Ops
  35. w.Header().Set("Content-Type", "application/json")
  36. w.WriteHeader(http.StatusOK)
  37. _ = json.NewEncoder(w).Encode(map[string]bool{"ok": true})
  38. }))
  39. defer netgripMock.Close()
  40. host := netgripMock.Listener.Addr().String()
  41. _, err := routerstore.AddRouter(ts.db.DB, routerstore.AddInput{
  42. Name: "Flint 2",
  43. Host: host,
  44. Type: "openwrt",
  45. IsGateway: true,
  46. })
  47. if err != nil {
  48. t.Fatalf("add router: %v", err)
  49. }
  50. _, err = ts.db.Exec("UPDATE routers SET id = ? WHERE host = ?", "flint2", host)
  51. if err != nil {
  52. t.Fatalf("update router id: %v", err)
  53. }
  54. sum := sha256.Sum256([]byte("agent-token"))
  55. _, err = ts.db.Exec("INSERT INTO kv (key, value) VALUES (?, ?)", "agent.token.flint2", hex.EncodeToString(sum[:]))
  56. if err != nil {
  57. t.Fatalf("insert agent token: %v", err)
  58. }
  59. _, err = ts.db.Exec(
  60. "INSERT INTO kv (key, value) VALUES (?, ?)",
  61. "netgrip.executor_token.flint2", "netgrip-secret")
  62. if err != nil {
  63. t.Fatalf("insert executor token: %v", err)
  64. }
  65. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  66. ops := []executor.Op{{
  67. Kind: "uci_set",
  68. Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"},
  69. Desc: "set dns",
  70. }}
  71. body, _ := json.Marshal(map[string]any{
  72. "routerId": "flint2",
  73. "resource": "guestwifi",
  74. "diff": ops,
  75. })
  76. req, _ := http.NewRequest("POST", ts.URL+"/api/orchestr/apply", bytes.NewReader(body))
  77. req.Header.Set("Cookie", "session="+cookie)
  78. req.Header.Set("Content-Type", "application/json")
  79. res, err := http.DefaultClient.Do(req)
  80. if err != nil {
  81. t.Fatalf("apply: %v", err)
  82. }
  83. defer res.Body.Close()
  84. if res.StatusCode != http.StatusAccepted {
  85. b, _ := io.ReadAll(res.Body)
  86. t.Fatalf("apply: esperaba 202, got %d: %s", res.StatusCode, string(b))
  87. }
  88. // Verificar que el plan se creó y que NetGrip recibió ownership.
  89. if len(receivedOps) < 3 {
  90. t.Fatalf("NetGrip debería recibir al menos 3 ops, got %d", len(receivedOps))
  91. }
  92. if receivedOps[0].Kind != "ownership_mode" || receivedOps[0].Args["enforce"] != "true" {
  93. t.Errorf("op[0] debería ser ownership_mode enforce=true, got %+v", receivedOps[0])
  94. }
  95. if receivedOps[1].Kind != "uci_set_managed" {
  96. t.Errorf("op[1] debería ser uci_set_managed, got %+v", receivedOps[1])
  97. }
  98. var planID string
  99. if err := ts.db.QueryRow("SELECT id FROM orchestr_plans ORDER BY created_at DESC LIMIT 1").Scan(&planID); err != nil {
  100. t.Fatalf("select plan: %v", err)
  101. }
  102. var status string
  103. if err := ts.db.QueryRow("SELECT status FROM orchestr_plans WHERE id = ?", planID).Scan(&status); err != nil {
  104. t.Fatalf("select status: %v", err)
  105. }
  106. if status != "applied" {
  107. t.Fatalf("plan status: esperaba applied, got %s", status)
  108. }
  109. }