main_test.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. // main_test.go — regresión issue #57: notifierChain no debe paniquear con un
  2. // nil-encapsulado (interfaz con tipo pero valor nil) entre sus miembros.
  3. package main
  4. import (
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/gnacho/netpulse/server-go/internal/alerts"
  11. "github.com/gnacho/netpulse/server-go/internal/db"
  12. )
  13. // nilNotifier implementa alerts.Notifier; un puntero nil a este tipo,
  14. // empaquetado en la interfaz, simula el bug (interfaz no-nil, valor nil).
  15. // Notify accede a un campo del receiver (como webhook.Notifier.Notify accede
  16. // a n.done/n.ch): con receiver nil esto paniquea si no se filtra.
  17. type nilNotifier struct {
  18. done chan struct{}
  19. }
  20. func (n *nilNotifier) Notify(alerts.AlertEvent) {
  21. _ = n.done // accede al receiver: con n nil → panic (como webhook.Notify)
  22. }
  23. func TestNotifierChainIgnoraNilEncapsulado(t *testing.T) {
  24. // Cadena con: notifier real + puntero nil a *nilNotifier empaquetado en
  25. // la interfaz. Sin el fix, n.Notify paniquea (receiver nil).
  26. var real alerts.Notifier = &nilNotifier{}
  27. var nilPtr *nilNotifier
  28. chain := notifierChain{real, nilPtr}
  29. ev := alerts.AlertEvent{ID: "test", Title: "x", Urgent: true}
  30. chain.Notify(ev) // no debe paniquear
  31. }
  32. func TestNotifierChainConNilPlano(t *testing.T) {
  33. var real alerts.Notifier = &nilNotifier{}
  34. chain := notifierChain{real, nil}
  35. chain.Notify(alerts.AlertEvent{ID: "test2"}) // no debe paniquear
  36. }
  37. func TestIsSSEStreamPath(t *testing.T) {
  38. cases := map[string]bool{
  39. "/api/stream": true,
  40. "/api/agents/gw/stream": true,
  41. "/api/agents/gateway/stream": true,
  42. "/api/update/stream": true, // FORK
  43. "/api/update/status": false,
  44. "/api/agents/gw/binary": false,
  45. "/api/agents/gw/refresh": false,
  46. "/api/agents/gw/stream/x": false,
  47. "/api/agents": false,
  48. "/api/overview": false,
  49. "/": false,
  50. }
  51. for p, want := range cases {
  52. if got := isSSEStreamPath(p); got != want {
  53. t.Errorf("isSSEStreamPath(%q) = %v, want %v", p, got, want)
  54. }
  55. }
  56. }
  57. // deadlineRecorder envuelve una ResponseWriter registrando si se llama a
  58. // SetWriteDeadline y con qué deadline (para verificar el override de SSE).
  59. type deadlineRecorder struct {
  60. http.ResponseWriter
  61. deadline time.Time
  62. set bool
  63. }
  64. func (d *deadlineRecorder) SetWriteDeadline(t time.Time) error {
  65. d.deadline = t
  66. d.set = true
  67. return nil
  68. }
  69. func TestWithSSEWriteTimeoutExtiendeDeadlineSSE(t *testing.T) {
  70. h := withSSEWriteTimeout(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), 24*time.Hour)
  71. for _, p := range []string{"/api/stream", "/api/agents/gateway/stream"} {
  72. rec := &deadlineRecorder{}
  73. h.ServeHTTP(rec, httptest.NewRequest("GET", p, nil))
  74. if !rec.set {
  75. t.Fatalf("%s: debe extender el write deadline", p)
  76. }
  77. if rec.deadline.Before(time.Now().Add(23 * time.Hour)) {
  78. t.Fatalf("%s: deadline %v no es el esperado (24 h)", p, rec.deadline)
  79. }
  80. }
  81. }
  82. func TestWithSSEWriteTimeoutNoTocaNoSSE(t *testing.T) {
  83. h := withSSEWriteTimeout(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), 24*time.Hour)
  84. rec := &deadlineRecorder{}
  85. h.ServeHTTP(rec, httptest.NewRequest("GET", "/api/overview", nil))
  86. if rec.set {
  87. t.Fatal("/api/overview no debe extender el write deadline")
  88. }
  89. }
  90. func TestWebhookHostForLog(t *testing.T) {
  91. // Issue #217: el log de arranque del webhook debe mostrar solo el host,
  92. // sin userinfo ni path (posibles credenciales embebidas).
  93. cases := map[string]string{
  94. "https://user:pass@hooks.example.com/hook/abc": "hooks.example.com",
  95. "https://hooks.example.com/path": "hooks.example.com",
  96. "http://192.168.1.50:8080/h": "192.168.1.50:8080",
  97. "no-es-una-url": "(sin host)",
  98. }
  99. for raw, want := range cases {
  100. if got := webhookHostForLog(raw); got != want {
  101. t.Errorf("webhookHostForLog(%q) = %q, want %q", raw, got, want)
  102. }
  103. }
  104. if s := webhookHostForLog("https://user:pass@hooks.example.com/x"); strings.Contains(s, "pass") {
  105. t.Fatalf("el host no debe contener credenciales: %q", s)
  106. }
  107. }
  108. // #874: urgencyGate — default (sin kv) = solo urgentes; con
  109. // "<canal>.urgent_only"="false" = pasa también lo no urgente.
  110. func TestUrgencyGateDefaultUrgentOnly(t *testing.T) {
  111. d, err := db.Open(t.TempDir())
  112. if err != nil {
  113. t.Fatal(err)
  114. }
  115. spy := &spyN{}
  116. g := urgencyGate{n: spy, kv: &mainKVAdapter{db: d.DB}, key: "ntfy.urgent_only"}
  117. g.Notify(alerts.AlertEvent{ID: "u1", Urgent: true})
  118. g.Notify(alerts.AlertEvent{ID: "n1", Urgent: false})
  119. if len(spy.got) != 1 || spy.got[0].ID != "u1" {
  120. t.Fatalf("default: %+v", spy.got)
  121. }
  122. if _, err := d.DB.Exec(
  123. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`,
  124. "ntfy.urgent_only", "false"); err != nil {
  125. t.Fatal(err)
  126. }
  127. g.Notify(alerts.AlertEvent{ID: "n2", Urgent: false})
  128. if len(spy.got) != 2 || spy.got[1].ID != "n2" {
  129. t.Fatalf("con urgent_only=false: %+v", spy.got)
  130. }
  131. }
  132. type spyN struct{ got []alerts.AlertEvent }
  133. func (s *spyN) Notify(ev alerts.AlertEvent) { s.got = append(s.got, ev) }