webhook.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // Package webhook — notificador SALIENTE de alertas (Fase 8.7b).
  2. //
  3. // Implementa alerts.Notifier con entrega a una URL externa: firma
  4. // HMAC-SHA256 del body, reintentos con backoff exponencial + jitter
  5. // (4xx no se reintenta salvo 429; 5xx sí), DLQ en tabla webhook_events si
  6. // se agotan los reintentos. Patrón del skill email-webhook-notifications
  7. // (references/webhook-patterns.md) aplicado a NetPulse.
  8. //
  9. // Notify NUNCA bloquea al llamador: encola el evento y un worker único lo
  10. // drena. Si la cola está llena se descarta (la alerta ya está en /api/alerts).
  11. package webhook
  12. import (
  13. "bytes"
  14. "context"
  15. "crypto/hmac"
  16. "crypto/sha256"
  17. "encoding/hex"
  18. "encoding/json"
  19. "fmt"
  20. "io"
  21. "log/slog"
  22. "math/rand"
  23. "net/http"
  24. "sync"
  25. "time"
  26. "github.com/gnacho/netpulse/server-go/internal/alerts"
  27. "github.com/gnacho/netpulse/server-go/internal/config"
  28. "github.com/gnacho/netpulse/server-go/internal/db"
  29. )
  30. const (
  31. queueCap = 64
  32. maxBodyCap = 64 << 10 // 64 KB (recomendación de seguridad del skill)
  33. )
  34. // payload es el contrato del webhook (firmado): event_id para idempotencia
  35. // del receptor y datos de la alerta.
  36. type payload struct {
  37. EventID string `json:"event_id"`
  38. Timestamp string `json:"timestamp"` // RFC3339
  39. Type string `json:"type"`
  40. Severity string `json:"severity"`
  41. Title string `json:"title"`
  42. Description string `json:"description"`
  43. Category string `json:"category"`
  44. RouterID string `json:"routerId,omitempty"`
  45. App string `json:"app"`
  46. }
  47. // Notifier implementa alerts.Notifier con entrega asíncrona y DLQ.
  48. type Notifier struct {
  49. cfg config.Webhook
  50. db *db.DB
  51. client *http.Client
  52. ch chan alerts.AlertEvent
  53. done chan struct{}
  54. once sync.Once
  55. wg sync.WaitGroup
  56. }
  57. // NewNotifier crea el Notifier y arranca su worker.
  58. func NewNotifier(cfg config.Webhook, d *db.DB) *Notifier {
  59. n := &Notifier{
  60. cfg: cfg,
  61. db: d,
  62. client: &http.Client{Timeout: cfg.Timeout},
  63. ch: make(chan alerts.AlertEvent, queueCap),
  64. done: make(chan struct{}),
  65. }
  66. n.wg.Add(1)
  67. go n.worker()
  68. return n
  69. }
  70. // Notify encola el evento y vuelve inmediatamente.
  71. func (n *Notifier) Notify(ev alerts.AlertEvent) {
  72. select {
  73. case <-n.done:
  74. return
  75. case n.ch <- ev:
  76. default:
  77. slog.Warn("webhook: cola llena, evento descartado", "alertId", ev.ID, "title", ev.Title)
  78. }
  79. }
  80. // Close para el worker y espera al envío en curso.
  81. func (n *Notifier) Close() {
  82. n.once.Do(func() {
  83. close(n.done)
  84. close(n.ch)
  85. n.wg.Wait()
  86. })
  87. }
  88. func (n *Notifier) worker() {
  89. defer n.wg.Done()
  90. for ev := range n.ch {
  91. n.sendWithRetry(ev)
  92. }
  93. }
  94. // payloadJSON construye el body firmable de un evento.
  95. func payloadJSON(ev alerts.AlertEvent) ([]byte, error) {
  96. return json.Marshal(payload{
  97. EventID: ev.ID,
  98. Timestamp: time.Unix(ev.Ts, 0).UTC().Format(time.RFC3339),
  99. Type: "alert." + ev.Category,
  100. Severity: ev.Severity,
  101. Title: ev.Title,
  102. Description: ev.Description,
  103. Category: ev.Category,
  104. RouterID: ev.RouterID,
  105. App: "netpulse",
  106. })
  107. }
  108. // sign calcula la firma HMAC-SHA256 del body crudo.
  109. func sign(body []byte, secret string) string {
  110. mac := hmac.New(sha256.New, []byte(secret))
  111. mac.Write(body)
  112. return "sha256=" + hex.EncodeToString(mac.Sum(nil))
  113. }
  114. // sendWithRetry envía con backoff exponencial + jitter. 4xx (salvo 429) no se
  115. // reintenta; 429/5xx sí. Al agotar reintentos guarda en DLQ.
  116. func (n *Notifier) sendWithRetry(ev alerts.AlertEvent) {
  117. body, err := payloadJSON(ev)
  118. if err != nil {
  119. slog.Error("webhook: payload no serializable", "alertId", ev.ID, "error", err)
  120. return
  121. }
  122. var lastErr error
  123. for attempt := 0; attempt <= n.cfg.Retries; attempt++ {
  124. ctx, cancel := context.WithTimeout(context.Background(), n.cfg.Timeout)
  125. err = n.sendOnce(ctx, ev.ID, body)
  126. cancel()
  127. if err == nil {
  128. return
  129. }
  130. lastErr = err
  131. var retryable bool
  132. if httpErr, ok := err.(*httpStatusError); ok {
  133. // 4xx (salvo 429): error del emisor, no reintentar jamás.
  134. if httpErr.status >= 400 && httpErr.status < 500 && httpErr.status != http.StatusTooManyRequests {
  135. slog.Warn("webhook: 4xx permanente, no se reintenta", "alertId", ev.ID, "status", httpErr.status)
  136. n.saveDLQ(ev, body, lastErr.Error())
  137. return
  138. }
  139. retryable = true
  140. }
  141. if attempt < n.cfg.Retries && retryable {
  142. jitter := time.Duration(rand.Int63n(int64(n.cfg.RetryDelay)))
  143. backoff := n.cfg.RetryDelay * time.Duration(1<<attempt)
  144. time.Sleep(backoff + jitter)
  145. }
  146. }
  147. n.saveDLQ(ev, body, lastErr.Error())
  148. }
  149. // httpStatusError marca la respuesta HTTP para la decisión de reintento.
  150. type httpStatusError struct {
  151. status int
  152. body string
  153. }
  154. func (e *httpStatusError) Error() string {
  155. return fmt.Sprintf("webhook status %d: %s", e.status, e.body)
  156. }
  157. func (n *Notifier) sendOnce(ctx context.Context, eventID string, body []byte) error {
  158. req, err := http.NewRequestWithContext(ctx, http.MethodPost, n.cfg.URL, bytes.NewReader(body))
  159. if err != nil {
  160. return err
  161. }
  162. req.Header.Set("Content-Type", "application/json")
  163. req.Header.Set("User-Agent", "NetPulse-Webhook/2.0")
  164. req.Header.Set("X-Webhook-Signature", sign(body, n.cfg.Secret))
  165. resp, err := n.client.Do(req)
  166. if err != nil {
  167. return err
  168. }
  169. defer resp.Body.Close()
  170. respBody, _ := io.ReadAll(io.LimitReader(resp.Body, maxBodyCap))
  171. if resp.StatusCode >= 200 && resp.StatusCode < 300 {
  172. return nil
  173. }
  174. return &httpStatusError{status: resp.StatusCode, body: string(respBody)}
  175. }
  176. // saveDLQ persiste el evento no entregado para diagnóstico posterior.
  177. func (n *Notifier) saveDLQ(ev alerts.AlertEvent, body []byte, reason string) {
  178. if n.db == nil {
  179. return
  180. }
  181. if _, err := n.db.Exec(
  182. "INSERT OR REPLACE INTO webhook_events (event_id, payload, sent_at, error) VALUES (?, ?, ?, ?)",
  183. ev.ID, string(body), time.Now().Unix(), reason,
  184. ); err != nil {
  185. slog.Error("webhook: no se pudo guardar en DLQ", "alertId", ev.ID, "error", err)
  186. return
  187. }
  188. slog.Warn("webhook: evento a DLQ", "alertId", ev.ID, "error", reason)
  189. }