ntfy_test.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // ntfy_test.go - tests del canal ntfy (#766): publicacion, reintentos,
  2. // no-retry en 4xx, formato y config (topic/server/token write-only).
  3. package ntfy
  4. import (
  5. "context"
  6. "errors"
  7. "net/http"
  8. "net/http/httptest"
  9. "net/url"
  10. "strings"
  11. "syscall"
  12. "testing"
  13. "time"
  14. "unicode/utf8"
  15. "github.com/gnacho/netpulse/server-go/internal/alerts"
  16. )
  17. type fakeKV struct{ m map[string]string }
  18. func (f *fakeKV) Get(key string) (string, bool) {
  19. v, ok := f.m[key]
  20. return v, ok
  21. }
  22. func (f *fakeKV) Set(key, value string) error {
  23. if f.m == nil {
  24. f.m = map[string]string{}
  25. }
  26. f.m[key] = value
  27. return nil
  28. }
  29. func TestPublishPostsTitleAndPriority(t *testing.T) {
  30. var gotPath, gotTitle, gotPrio, gotBody, gotAuth string
  31. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  32. gotPath = r.URL.Path
  33. gotTitle = r.Header.Get("Title")
  34. gotPrio = r.Header.Get("Priority")
  35. gotAuth = r.Header.Get("Authorization")
  36. buf := make([]byte, 512)
  37. n, _ := r.Body.Read(buf)
  38. gotBody = string(buf[:n])
  39. w.WriteHeader(200)
  40. }))
  41. defer srv.Close()
  42. n := &Notifier{client: srv.Client(), done: make(chan struct{})}
  43. cfg := Config{Server: srv.URL, Topic: "mi-topic-secreto", Token: "tk123"}
  44. if err := n.publish(cfg, "Router caído", "🔴 descripción", "urgent"); err != nil {
  45. t.Fatalf("publish: %v", err)
  46. }
  47. if gotPath != "/mi-topic-secreto" {
  48. t.Fatalf("path: %s", gotPath)
  49. }
  50. if gotTitle != "Router caído" || gotPrio != "urgent" {
  51. t.Fatalf("headers: %q %q", gotTitle, gotPrio)
  52. }
  53. if gotAuth != "Bearer tk123" {
  54. t.Fatalf("auth: %q", gotAuth)
  55. }
  56. if gotBody == "" {
  57. t.Fatalf("body vacío")
  58. }
  59. }
  60. func TestPublishNoRetryOn4xx(t *testing.T) {
  61. calls := 0
  62. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  63. calls++
  64. w.WriteHeader(403)
  65. _, _ = w.Write([]byte("forbidden"))
  66. }))
  67. defer srv.Close()
  68. n := &Notifier{client: srv.Client(), done: make(chan struct{})}
  69. err := n.sendWithRetry(Config{Server: srv.URL, Topic: "x"}, alerts.AlertEvent{Title: "t", Urgent: true})
  70. if err == nil {
  71. t.Fatalf("403 debe fallar")
  72. }
  73. if calls != 1 {
  74. t.Fatalf("4xx no reintenta: %d llamadas", calls)
  75. }
  76. }
  77. func TestPublishRetriesOn5xxThenOK(t *testing.T) {
  78. calls := 0
  79. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  80. calls++
  81. if calls == 1 {
  82. w.WriteHeader(502)
  83. return
  84. }
  85. w.WriteHeader(200)
  86. }))
  87. defer srv.Close()
  88. n := &Notifier{client: srv.Client(), done: make(chan struct{})}
  89. // Retry inmediato no existe: baseRetry 2s haría el test lento; aceptamos
  90. // la espera del primer reintento con un timeout holgado.
  91. done := make(chan error, 1)
  92. go func() {
  93. done <- n.sendWithRetry(Config{Server: srv.URL, Topic: "x"}, alerts.AlertEvent{Title: "t"})
  94. }()
  95. <-done
  96. if calls != 2 {
  97. t.Fatalf("esperaba 2 llamadas (1 fallo + reintento OK): %d", calls)
  98. }
  99. }
  100. func TestNotifyQueueNoConfigNoop(t *testing.T) {
  101. kv := &fakeKV{}
  102. n := NewNotifier(kv)
  103. n.Notify(alerts.AlertEvent{Title: "x", Urgent: true})
  104. n.Close() // sin config no debe intentar enviar ni bloquear
  105. }
  106. func TestConfigValidation(t *testing.T) {
  107. kv := &fakeKV{}
  108. if err := SaveConfig(kv, Config{Topic: "tema con espacios"}); err == nil {
  109. t.Fatalf("topic inválido debe fallar")
  110. }
  111. if err := SaveConfig(kv, Config{Server: "ftp://x", Topic: "ok"}); err == nil {
  112. t.Fatalf("server no-http debe fallar")
  113. }
  114. if err := SaveConfig(kv, Config{Topic: "netpulse_abc-123", Enabled: true}); err != nil {
  115. t.Fatalf("valida: %v", err)
  116. }
  117. got := LoadConfig(kv)
  118. if got.Server != DefaultServer || got.Topic != "netpulse_abc-123" || !got.Enabled {
  119. t.Fatalf("roundtrip: %+v", got)
  120. }
  121. // Topic vacío permitido (limpiar canal): LoadConfig devuelve default.
  122. if err := SaveConfig(kv, Config{}); err != nil {
  123. t.Fatalf("limpiar: %v", err)
  124. }
  125. if got := LoadConfig(kv); got.Topic != "" || got.Enabled {
  126. t.Fatalf("tras limpiar: %+v", got)
  127. }
  128. }
  129. func TestFormatMessage(t *testing.T) {
  130. msg := formatMessage(alerts.AlertEvent{Title: "Firmware actualizado", Description: "rt: 25.12.5 -> 25.12.7", RouterID: "gateway", Urgent: true, Ts: 1700000000})
  131. if msg == "" || !contains(msg, "Firmware actualizado") || !contains(msg, "gateway") {
  132. t.Fatalf("formato: %q", msg)
  133. }
  134. }
  135. // B1: el topic (secreto del canal) nunca se registra en claro.
  136. func TestMaskTopic(t *testing.T) {
  137. got := MaskTopic("top-secreto-123")
  138. if contains(got, "top-secreto-123") || !contains(got, "***") {
  139. t.Fatalf("el topic debe quedar enmascarado: %q", got)
  140. }
  141. if got := MaskTopic(""); got != "" {
  142. t.Fatalf("topic vacío: %q", got)
  143. }
  144. }
  145. // B2: el error de red no debe filtrar el topic (URL saneada).
  146. func TestPublishErrorRedactsTopic(t *testing.T) {
  147. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
  148. base := srv.URL
  149. srv.Close()
  150. n := &Notifier{client: &http.Client{Timeout: 2 * time.Second}, done: make(chan struct{})}
  151. err := n.publish(Config{Server: base, Topic: "top-secreto-abc"}, "t", "b", "default")
  152. if err == nil {
  153. t.Fatalf("esperaba error con el server cerrado")
  154. }
  155. if contains(err.Error(), "top-secreto-abc") {
  156. t.Fatalf("el topic no debe aparecer en el error: %q", err.Error())
  157. }
  158. if !contains(err.Error(), "***") {
  159. t.Fatalf("esperaba el topic enmascarado: %q", err.Error())
  160. }
  161. }
  162. // B3: solo se reintenta 5xx, 429 y errores de red transitorios.
  163. func TestIsRetryable(t *testing.T) {
  164. cases := []struct {
  165. name string
  166. err error
  167. want bool
  168. }{
  169. {"nil", nil, false},
  170. {"status 500", errors.New("status 500: boom"), true},
  171. {"status 503", errors.New("status 503: boom"), true},
  172. {"status 429", errors.New("status 429: slow down"), true},
  173. {"status 400", errors.New("status 400: bad"), false},
  174. {"status 401", errors.New("status 401: bad"), false},
  175. {"status 403", errors.New("status 403: bad"), false},
  176. {"status 404", errors.New("status 404: bad"), false},
  177. {"url inválida", &url.Error{Op: "parse", URL: "http://x/y", Err: errors.New("invalid")}, false},
  178. {"contexto cancelado", &url.Error{Op: "Post", URL: "http://x/y", Err: context.Canceled}, false},
  179. {"timeout", &url.Error{Op: "Post", URL: "http://x/y", Err: context.DeadlineExceeded}, true},
  180. {"conexión rechazada", &url.Error{Op: "Post", URL: "http://x/y", Err: syscall.ECONNREFUSED}, true},
  181. }
  182. for _, tc := range cases {
  183. if got := isRetryable(tc.err); got != tc.want {
  184. t.Errorf("%s: got %v want %v", tc.name, got, tc.want)
  185. }
  186. }
  187. }
  188. // B4: el truncado no debe partir runas multibyte.
  189. func TestFormatMessageTruncatesOnRuneBoundary(t *testing.T) {
  190. desc := strings.Repeat("é", 600) // 1200 bytes, >500
  191. msg := formatMessage(alerts.AlertEvent{Title: "t", Description: desc, Ts: 1700000000})
  192. if !utf8.ValidString(msg) {
  193. t.Fatalf("mensaje con UTF-8 inválido")
  194. }
  195. if !contains(msg, "...") {
  196. t.Fatalf("esperaba recorte de la descripción: %q", msg)
  197. }
  198. big := strings.Repeat("日", 3000) // 9000 bytes, supera maxMsgLen
  199. msg = formatMessage(alerts.AlertEvent{Title: big, Ts: 1700000000})
  200. if !utf8.ValidString(msg) {
  201. t.Fatalf("mensaje largo con UTF-8 inválido")
  202. }
  203. if len(msg) > maxMsgLen {
  204. t.Fatalf("mensaje por encima del límite: %d bytes", len(msg))
  205. }
  206. }
  207. // B7: el test no publica si el canal está desactivado.
  208. func TestSendTestRequiresEnabled(t *testing.T) {
  209. calls := 0
  210. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  211. calls++
  212. w.WriteHeader(200)
  213. }))
  214. defer srv.Close()
  215. kv := &fakeKV{m: map[string]string{
  216. "ntfy.server": srv.URL,
  217. "ntfy.topic": "x",
  218. "ntfy.enabled": "false",
  219. }}
  220. if err := SendTest(kv); err == nil {
  221. t.Fatalf("test debe fallar con el canal desactivado")
  222. }
  223. if calls != 0 {
  224. t.Fatalf("no debe publicar desactivado: %d", calls)
  225. }
  226. kv.m["ntfy.enabled"] = "true"
  227. if err := SendTest(kv); err != nil {
  228. t.Fatalf("test con canal activo: %v", err)
  229. }
  230. if calls != 1 {
  231. t.Fatalf("debe publicar una vez activo: %d", calls)
  232. }
  233. }
  234. // B8: Close cancela la petición en curso.
  235. func TestCloseCancelsInFlightPublish(t *testing.T) {
  236. started := make(chan struct{})
  237. release := make(chan struct{})
  238. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  239. close(started)
  240. <-release
  241. w.WriteHeader(200)
  242. }))
  243. defer srv.Close()
  244. defer close(release)
  245. kv := &fakeKV{m: map[string]string{
  246. "ntfy.server": srv.URL,
  247. "ntfy.topic": "x",
  248. "ntfy.enabled": "true",
  249. }}
  250. n := NewNotifier(kv)
  251. n.Notify(alerts.AlertEvent{Title: "t", Urgent: true})
  252. select {
  253. case <-started:
  254. case <-time.After(3 * time.Second):
  255. t.Fatalf("la petición no llegó al server")
  256. }
  257. done := make(chan struct{})
  258. go func() {
  259. n.Close()
  260. close(done)
  261. }()
  262. select {
  263. case <-done:
  264. case <-time.After(3 * time.Second):
  265. t.Fatalf("Close no canceló la petición en curso")
  266. }
  267. }
  268. // B9: Close es idempotente.
  269. func TestCloseIsIdempotent(t *testing.T) {
  270. n := NewNotifier(&fakeKV{})
  271. n.Close()
  272. n.Close() // no debe paniquear
  273. }
  274. func contains(s, sub string) bool {
  275. for i := 0; i+len(sub) <= len(s); i++ {
  276. if s[i:i+len(sub)] == sub {
  277. return true
  278. }
  279. }
  280. return false
  281. }