4
0

integrations_catalog_test.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. // integrations_catalog_test.go - #1697: GET /api/integrations/vendors sirve el
  2. // catálogo por descubrimiento (con lastRefreshedAt) y degrada a la semilla sin
  3. // red; POST /api/integrations/vendors/refresh (admin) fuerza el fetch y
  4. // devuelve el catálogo actualizado. Sin red: fetch inyectado.
  5. package httpapi_test
  6. import (
  7. "errors"
  8. "net/http"
  9. "strings"
  10. "sync/atomic"
  11. "testing"
  12. "github.com/gnacho/netpulse/server-go/internal/db"
  13. "github.com/gnacho/netpulse/server-go/internal/rintegration"
  14. )
  15. // seedVendor devuelve un vendor de la semilla embebida (helper de tests).
  16. func seedVendor(t *testing.T, id string) rintegration.Vendor {
  17. t.Helper()
  18. v, ok := rintegration.NewCatalog(nil).Lookup(id)
  19. if !ok {
  20. t.Fatalf("vendor %q missing from the embedded seed", id)
  21. }
  22. return v
  23. }
  24. func post(t *testing.T, base, path, cookie, body string) *http.Response {
  25. t.Helper()
  26. req, _ := http.NewRequest("POST", base+path, strings.NewReader(body))
  27. if cookie != "" {
  28. req.Header.Set("Cookie", "session="+cookie)
  29. }
  30. res, err := http.DefaultClient.Do(req)
  31. if err != nil {
  32. t.Fatalf("POST %s: %v", path, err)
  33. }
  34. return res
  35. }
  36. const labVendorCatalog = `{"vendors":[{"id":"labvendor","mode":"local","arches":["amd64"],"tagPrefix":"lab/v","binary":"lab-pusher","target":"lab/cmd/lab-pusher","description":"Lab vendor"}]}`
  37. // TestVendorsEndpointServesSeedAndDegradesOffline: con el fetch roto, el GET
  38. // sirve la semilla embebida (nunca una lista vacía), lastRefreshedAt se
  39. // mantiene a cero y el intento fallido no tira la respuesta.
  40. func TestVendorsEndpointServesSeedAndDegradesOffline(t *testing.T) {
  41. var calls atomic.Int32
  42. ts, _ := makeIntegrationsTestServerFull(t, nil, func(d *db.DB) *rintegration.Catalog {
  43. c := rintegration.NewCatalog(d.DB)
  44. c.FetchOverride = func(string) ([]byte, error) {
  45. calls.Add(1)
  46. return nil, errors.New("dial tcp: connection refused")
  47. }
  48. return c
  49. })
  50. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  51. res := get(t, ts.URL, "/api/integrations/vendors", cookie)
  52. if res.StatusCode != http.StatusOK {
  53. t.Fatalf("GET vendors: status %d", res.StatusCode)
  54. }
  55. body := readJSON(t, res)
  56. rawVendors, ok := body["vendors"].([]any)
  57. if !ok {
  58. t.Fatalf("vendors missing: %v", body)
  59. }
  60. if len(rawVendors) != 4 {
  61. t.Fatalf("seed must be served when offline: %d vendors (%v)", len(rawVendors), rawVendors)
  62. }
  63. if got := body["lastRefreshedAt"].(float64); got != 0 {
  64. t.Fatalf("lastRefreshedAt = %v, want 0 without a successful fetch", got)
  65. }
  66. if calls.Load() != 1 {
  67. t.Fatalf("the endpoint must attempt the discovery once (calls %d)", calls.Load())
  68. }
  69. }
  70. // TestVendorsRefreshEndpointUpdatesCatalog: el refresco admin fuerza el fetch
  71. // y devuelve el catálogo nuevo con lastRefreshedAt actualizado.
  72. func TestVendorsRefreshEndpointUpdatesCatalog(t *testing.T) {
  73. var calls atomic.Int32
  74. ts, _ := makeIntegrationsTestServerFull(t, nil, func(d *db.DB) *rintegration.Catalog {
  75. c := rintegration.NewCatalog(d.DB)
  76. c.FetchOverride = func(string) ([]byte, error) {
  77. if calls.Add(1) == 1 {
  78. // Primer intento (GET): roto, se sirve la semilla.
  79. return nil, errors.New("connection refused")
  80. }
  81. return []byte(labVendorCatalog), nil
  82. }
  83. return c
  84. })
  85. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  86. // Estado inicial: el GET de arranque falla y sirve la semilla.
  87. res0 := get(t, ts.URL, "/api/integrations/vendors", cookie)
  88. body0 := readJSON(t, res0)
  89. if rawVendors0, ok := body0["vendors"].([]any); !ok || len(rawVendors0) != 4 {
  90. t.Fatalf("seed must be served while the fetch fails: %v", body0)
  91. }
  92. res := post(t, ts.URL, "/api/integrations/vendors/refresh", cookie, "")
  93. if res.StatusCode != http.StatusOK {
  94. t.Fatalf("POST refresh: status %d", res.StatusCode)
  95. }
  96. body := readJSON(t, res)
  97. rawVendors, ok := body["vendors"].([]any)
  98. if !ok || len(rawVendors) != 1 {
  99. t.Fatalf("refreshed catalog = %v", body)
  100. }
  101. first, _ := rawVendors[0].(map[string]any)
  102. if first["id"] != "labvendor" || first["tagPrefix"] != "lab/v" {
  103. t.Fatalf("refreshed vendor = %v", first)
  104. }
  105. if got := body["lastRefreshedAt"].(float64); got <= 0 {
  106. t.Fatalf("lastRefreshedAt = %v, want > 0 after a successful refresh", got)
  107. }
  108. // El GET posterior sirve el catálogo refrescado desde la caché.
  109. res2 := get(t, ts.URL, "/api/integrations/vendors", cookie)
  110. body2 := readJSON(t, res2)
  111. if rawVendors2, ok := body2["vendors"].([]any); !ok || len(rawVendors2) != 1 {
  112. t.Fatalf("GET after refresh must serve the cached catalog: %v", body2)
  113. }
  114. }
  115. // TestVendorsRefreshRequiresSession: el refresco del catálogo es admin-only.
  116. func TestVendorsRefreshRequiresSession(t *testing.T) {
  117. ts, _ := makeIntegrationsTestServerFull(t, nil, func(d *db.DB) *rintegration.Catalog {
  118. return rintegration.NewCatalog(d.DB)
  119. })
  120. res := post(t, ts.URL, "/api/integrations/vendors/refresh", "", "")
  121. defer res.Body.Close()
  122. if res.StatusCode != http.StatusUnauthorized {
  123. t.Fatalf("unauthenticated refresh: status %d, want 401", res.StatusCode)
  124. }
  125. }
  126. // TestVendorsFallbackCatalogHasNoNetwork: el catálogo por defecto de
  127. // NewHandler (sin Deps.VendorCatalog) sirve la semilla sin intentar fetch
  128. // alguno: los tests y el demo no tocan la red.
  129. func TestVendorsFallbackCatalogHasNoNetwork(t *testing.T) {
  130. ts, _ := makeIntegrationsTestServer(t)
  131. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  132. res := get(t, ts.URL, "/api/integrations/vendors", cookie)
  133. if res.StatusCode != http.StatusOK {
  134. t.Fatalf("GET vendors: status %d", res.StatusCode)
  135. }
  136. body := readJSON(t, res)
  137. rawVendors, ok := body["vendors"].([]any)
  138. if !ok || len(rawVendors) != 4 {
  139. t.Fatalf("fallback catalog must serve the seed: %v", body)
  140. }
  141. if got := body["lastRefreshedAt"].(float64); got != 0 {
  142. t.Fatalf("fallback catalog must never fetch: lastRefreshedAt = %v", got)
  143. }
  144. }