webhook_test.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. // webhook_test.go — notificador saliente (Fase 8.7b): firma HMAC, decisión de
  2. // reintento (4xx no / 429-5xx sí) y DLQ.
  3. package webhook
  4. import (
  5. "crypto/hmac"
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "io"
  9. "net/http"
  10. "net/http/httptest"
  11. "os"
  12. "path/filepath"
  13. "sync/atomic"
  14. "testing"
  15. "time"
  16. "github.com/gnacho/netpulse/server-go/internal/alerts"
  17. "github.com/gnacho/netpulse/server-go/internal/config"
  18. "github.com/gnacho/netpulse/server-go/internal/db"
  19. )
  20. func testAlert() alerts.AlertEvent {
  21. return alerts.AlertEvent{
  22. ID: "evt-test-001", Category: "router", Urgent: true,
  23. Severity: "warn", Title: "Router caído", Description: "gateway no responde",
  24. Ts: time.Now().Unix(), RouterID: "gateway",
  25. }
  26. }
  27. func testConfig() config.Webhook {
  28. return config.Webhook{
  29. URL: "", Secret: "test-secret-32-bytes-minimum!!", Timeout: 3 * time.Second,
  30. Retries: 2, RetryDelay: 10 * time.Millisecond, Enabled: true,
  31. }
  32. }
  33. func openWebhookDB(t *testing.T) *db.DB {
  34. t.Helper()
  35. dataDir := t.TempDir()
  36. path := filepath.Join(dataDir, "netpulse.db")
  37. os.Remove(path)
  38. d, err := db.Open(dataDir)
  39. if err != nil {
  40. t.Fatalf("db.Open: %v", err)
  41. }
  42. t.Cleanup(func() { d.Close() })
  43. return d
  44. }
  45. // TestFirmaValida: el receptor debe poder verificar la firma con el secreto.
  46. func TestFirmaValida(t *testing.T) {
  47. var gotSig atomic.Value
  48. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  49. body, _ := io.ReadAll(r.Body)
  50. gotSig.Store(r.Header.Get("X-Webhook-Signature"))
  51. // Verificar con el secreto compartido (como haría el receptor)
  52. mac := hmac.New(sha256.New, []byte("test-secret-32-bytes-minimum!!"))
  53. mac.Write(body)
  54. expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
  55. if r.Header.Get("X-Webhook-Signature") != expected {
  56. t.Errorf("firma incorrecta: %q != %q", r.Header.Get("X-Webhook-Signature"), expected)
  57. }
  58. w.WriteHeader(http.StatusOK)
  59. }))
  60. defer srv.Close()
  61. cfg := testConfig()
  62. cfg.URL = srv.URL
  63. n := NewNotifier(cfg, nil)
  64. defer n.Close()
  65. n.Notify(testAlert())
  66. // El worker es asíncrono: dar margen a que se envíe
  67. time.Sleep(300 * time.Millisecond)
  68. if gotSig.Load() == nil {
  69. t.Fatal("no se recibió ninguna petición")
  70. }
  71. }
  72. // TestRetry4xxNoReintenta: 400 no se reintenta (1 solo request).
  73. func TestRetry4xxNoReintenta(t *testing.T) {
  74. var calls atomic.Int32
  75. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  76. calls.Add(1)
  77. w.WriteHeader(http.StatusBadRequest)
  78. }))
  79. defer srv.Close()
  80. cfg := testConfig()
  81. cfg.URL = srv.URL
  82. n := NewNotifier(cfg, openWebhookDB(t))
  83. defer n.Close()
  84. n.Notify(testAlert())
  85. time.Sleep(300 * time.Millisecond)
  86. if c := calls.Load(); c != 1 {
  87. t.Fatalf("400 debería recibir 1 request, recibió %d", c)
  88. }
  89. }
  90. // TestRetry5xxReintentaYVaADLQ: 500 se reintenta (Retries+1 requests) y al
  91. // agotar se guarda en DLQ.
  92. func TestRetry5xxReintentaYVaADLQ(t *testing.T) {
  93. var calls atomic.Int32
  94. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  95. calls.Add(1)
  96. w.WriteHeader(http.StatusInternalServerError)
  97. }))
  98. defer srv.Close()
  99. d := openWebhookDB(t)
  100. cfg := testConfig()
  101. cfg.URL = srv.URL
  102. n := NewNotifier(cfg, d)
  103. defer n.Close()
  104. n.Notify(testAlert())
  105. time.Sleep(500 * time.Millisecond)
  106. // Retries=2 → 1 envío inicial + 2 reintentos = 3 requests
  107. if c := calls.Load(); c != 3 {
  108. t.Fatalf("500 con retries=2 debería recibir 3 requests, recibió %d", c)
  109. }
  110. var cnt int
  111. if err := d.QueryRow("SELECT COUNT(*) FROM webhook_events").Scan(&cnt); err != nil {
  112. t.Fatalf("query DLQ: %v", err)
  113. }
  114. if cnt != 1 {
  115. t.Fatalf("DLQ debería tener 1 evento, tiene %d", cnt)
  116. }
  117. }
  118. // TestOKNoVaADLQ: 2xx → éxito, sin DLQ.
  119. func TestOKNoVaADLQ(t *testing.T) {
  120. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  121. w.WriteHeader(http.StatusAccepted)
  122. }))
  123. defer srv.Close()
  124. d := openWebhookDB(t)
  125. cfg := testConfig()
  126. cfg.URL = srv.URL
  127. n := NewNotifier(cfg, d)
  128. defer n.Close()
  129. n.Notify(testAlert())
  130. time.Sleep(300 * time.Millisecond)
  131. var cnt int
  132. if err := d.QueryRow("SELECT COUNT(*) FROM webhook_events").Scan(&cnt); err != nil {
  133. t.Fatalf("query DLQ: %v", err)
  134. }
  135. if cnt != 0 {
  136. t.Fatalf("2xx no debería ir a DLQ, tiene %d", cnt)
  137. }
  138. }