alerts_api_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // alerts_api_test.go — contrato de los endpoints de alertas (SPEC-ALERTAS §4):
  2. // GET /api/alerts (+category, +unread=1), GET/PUT /api/alerts/config,
  3. // POST /api/alerts/read y /api/alerts/read-all (server truth en overview).
  4. package httpapi_test
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "strings"
  12. "testing"
  13. "time"
  14. )
  15. func doJSON(t *testing.T, method, base, path, cookie string, body string) *http.Response {
  16. t.Helper()
  17. var rd io.Reader
  18. if body != "" {
  19. rd = bytes.NewBufferString(body)
  20. }
  21. req, _ := http.NewRequest(method, base+path, rd)
  22. if body != "" {
  23. req.Header.Set("Content-Type", "application/json")
  24. }
  25. if cookie != "" {
  26. req.Header.Set("Cookie", "session="+cookie)
  27. }
  28. res, err := http.DefaultClient.Do(req)
  29. if err != nil {
  30. t.Fatalf("%s %s: %v", method, path, err)
  31. }
  32. return res
  33. }
  34. func alertItems(t *testing.T, res *http.Response) []map[string]any {
  35. t.Helper()
  36. defer res.Body.Close()
  37. var body struct {
  38. Items []map[string]any `json:"items"`
  39. }
  40. if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
  41. t.Fatalf("json: %v", err)
  42. }
  43. return body.Items
  44. }
  45. func TestAlertsContractFields(t *testing.T) {
  46. ts := makeTestServer(t)
  47. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  48. res := get(t, ts.URL, "/api/alerts", cookie)
  49. items := alertItems(t, res)
  50. if len(items) != 5 {
  51. t.Fatalf("alertas demo: %d, esperaba 5", len(items))
  52. }
  53. for _, a := range items {
  54. if a["category"] == nil || a["category"] == "" {
  55. t.Fatalf("alerta sin category: %v", a["id"])
  56. }
  57. if _, ok := a["urgent"].(bool); !ok {
  58. t.Fatalf("alerta sin urgent bool: %v", a["id"])
  59. }
  60. if ts64, ok := a["ts"].(float64); !ok || ts64 <= 0 {
  61. t.Fatalf("alerta sin ts: %v", a["id"])
  62. }
  63. }
  64. // Filtro por categoría: vpn → solo el handshake
  65. items = alertItems(t, get(t, ts.URL, "/api/alerts?category=vpn", cookie))
  66. if len(items) != 1 || items[0]["id"] != "alert-handshake-wg" {
  67. t.Fatalf("category=vpn: %v", items)
  68. }
  69. // Categoría inválida → 400
  70. res = get(t, ts.URL, "/api/alerts?category=wifi", cookie)
  71. if res.StatusCode != 400 {
  72. t.Fatalf("category inválida: %d, esperaba 400", res.StatusCode)
  73. }
  74. res.Body.Close()
  75. // unread=1 → las 2 no leídas del canon
  76. items = alertItems(t, get(t, ts.URL, "/api/alerts?unread=1", cookie))
  77. if len(items) != 2 {
  78. t.Fatalf("unread=1: %d, esperaba 2", len(items))
  79. }
  80. for _, a := range items {
  81. if a["read"] == true {
  82. t.Fatalf("unread=1 devolvió leída: %v", a["id"])
  83. }
  84. }
  85. // Combinado: category + unread
  86. items = alertItems(t, get(t, ts.URL, "/api/alerts?category=clients&unread=1", cookie))
  87. if len(items) != 0 {
  88. t.Fatalf("clients&unread: %d, esperaba 0 (la canon clients está leída)", len(items))
  89. }
  90. }
  91. func TestAlertsConfigEndpoints(t *testing.T) {
  92. ts := makeTestServer(t)
  93. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  94. res := get(t, ts.URL, "/api/alerts/config", cookie)
  95. cfg := readJSON(t, res)
  96. if len(cfg) != 6 {
  97. t.Fatalf("config: %d claves, esperaba 6", len(cfg))
  98. }
  99. want := map[string]string{"router": "urgent", "internet": "urgent", "clients": "all",
  100. "signal": "none", "vpn": "none", "system": "all"}
  101. for k, v := range want {
  102. if cfg[k] != v {
  103. t.Fatalf("default %s: %v, esperaba %s", k, cfg[k], v)
  104. }
  105. }
  106. // PUT parcial → 200 y devuelve la config efectiva completa
  107. res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `{"vpn":"all"}`)
  108. if res.StatusCode != 200 {
  109. t.Fatalf("PUT config: %d", res.StatusCode)
  110. }
  111. cfg = readJSON(t, res)
  112. if cfg["vpn"] != "all" || cfg["router"] != "urgent" {
  113. t.Fatalf("PUT parcial: %v", cfg)
  114. }
  115. // Roundtrip: GET refleja el cambio (persistido en kv)
  116. cfg = readJSON(t, get(t, ts.URL, "/api/alerts/config", cookie))
  117. if cfg["vpn"] != "all" {
  118. t.Fatalf("roundtrip: %v", cfg)
  119. }
  120. // Nivel inválido → 400
  121. res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `{"vpn":"todo"}`)
  122. if res.StatusCode != 400 {
  123. t.Fatalf("nivel inválido: %d, esperaba 400", res.StatusCode)
  124. }
  125. res.Body.Close()
  126. // Categoría desconocida → 400
  127. res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `{"wifi":"all"}`)
  128. if res.StatusCode != 400 {
  129. t.Fatalf("categoría desconocida: %d, esperaba 400", res.StatusCode)
  130. }
  131. res.Body.Close()
  132. // Body no-JSON → 400
  133. res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `nope`)
  134. if res.StatusCode != 400 {
  135. t.Fatalf("body inválido: %d, esperaba 400", res.StatusCode)
  136. }
  137. res.Body.Close()
  138. }
  139. func TestAlertsReadEndpoints(t *testing.T) {
  140. ts := makeTestServer(t)
  141. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  142. unreadOf := func() float64 {
  143. res := get(t, ts.URL, "/api/overview", cookie)
  144. body := readJSON(t, res)
  145. return body["unreadAlerts"].(float64)
  146. }
  147. if got := unreadOf(); got != 2 {
  148. t.Fatalf("unreadAlerts inicial: %v, esperaba 2", got)
  149. }
  150. // POST read {ids}: marca una
  151. res := doJSON(t, "POST", ts.URL, "/api/alerts/read", cookie, `{"ids":["alert-temp-patio"]}`)
  152. if res.StatusCode != 200 {
  153. t.Fatalf("read: %d", res.StatusCode)
  154. }
  155. res.Body.Close()
  156. if got := unreadOf(); got != 1 {
  157. t.Fatalf("unreadAlerts tras read: %v, esperaba 1", got)
  158. }
  159. items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
  160. for _, a := range items {
  161. if a["id"] == "alert-temp-patio" && a["read"] != true {
  162. t.Fatal("read no aplicado en GET /api/alerts")
  163. }
  164. }
  165. // POST read-all → 0 en overview (server truth)
  166. res = doJSON(t, "POST", ts.URL, "/api/alerts/read-all", cookie, "")
  167. if res.StatusCode != 200 {
  168. t.Fatalf("read-all: %d", res.StatusCode)
  169. }
  170. res.Body.Close()
  171. if got := unreadOf(); got != 0 {
  172. t.Fatalf("unreadAlerts tras read-all: %v, esperaba 0", got)
  173. }
  174. items = alertItems(t, get(t, ts.URL, "/api/alerts?unread=1", cookie))
  175. if len(items) != 0 {
  176. t.Fatalf("unread=1 tras read-all: %d", len(items))
  177. }
  178. }
  179. // POST /api/alerts/dismiss (issue #833): limpia alertas del feed.
  180. func TestAlertsDismissEndpoint(t *testing.T) {
  181. ts := makeTestServer(t)
  182. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  183. // ids vacío → 400
  184. res := doJSON(t, "POST", ts.URL, "/api/alerts/dismiss", cookie, `{"ids":[]}`)
  185. if res.StatusCode != 400 {
  186. t.Fatalf("dismiss ids vacío: %d, esperaba 400", res.StatusCode)
  187. }
  188. res.Body.Close()
  189. res = doJSON(t, "POST", ts.URL, "/api/alerts/dismiss", cookie, `{"ids":["alert-temp-patio"]}`)
  190. if res.StatusCode != 200 {
  191. t.Fatalf("dismiss: %d", res.StatusCode)
  192. }
  193. res.Body.Close()
  194. items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
  195. for _, a := range items {
  196. if a["id"] == "alert-temp-patio" {
  197. t.Fatal("alert-temp-patio debía haber desaparecido del feed")
  198. }
  199. }
  200. // unread baja: la alerta limpiada cuenta como leída y se elimina.
  201. unread := 0
  202. for _, a := range items {
  203. if a["read"] != true {
  204. unread++
  205. }
  206. }
  207. if unread != 1 {
  208. t.Fatalf("unread tras dismiss: %d, esperaba 1", unread)
  209. }
  210. }
  211. // POST /api/alerts/clear (issue #971): "Marcar todo como leído" VACÍA el
  212. // feed - las alertas se descartan, no solo se marcan - y el badge queda a 0.
  213. func TestAlertsClearAllEndpoint(t *testing.T) {
  214. ts := makeTestServer(t)
  215. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  216. res := doJSON(t, "POST", ts.URL, "/api/alerts/clear", cookie, "")
  217. if res.StatusCode != 200 {
  218. t.Fatalf("clear: %d", res.StatusCode)
  219. }
  220. res.Body.Close()
  221. items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
  222. if len(items) != 0 {
  223. t.Fatalf("feed tras clear: %d, esperaba 0", len(items))
  224. }
  225. body := readJSON(t, get(t, ts.URL, "/api/overview", cookie))
  226. if got := body["unreadAlerts"].(float64); got != 0 {
  227. t.Fatalf("unreadAlerts tras clear: %v, esperaba 0", got)
  228. }
  229. }
  230. // writeJSON sin '\n' final (paridad D5, SPEC-ALERTAS §4).
  231. func TestAlertsNoTrailingNewline(t *testing.T) {
  232. ts := makeTestServer(t)
  233. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  234. res := get(t, ts.URL, "/api/alerts/config", cookie)
  235. defer res.Body.Close()
  236. raw, _ := io.ReadAll(res.Body)
  237. if strings.HasSuffix(string(raw), "\n") {
  238. t.Fatal("writeJSON no debe terminar en \\n")
  239. }
  240. }
  241. // POST /api/alerts/silence (#2185): posponer deja la alerta en el feed con
  242. // snoozed/snoozedUntil, acepta 1h/2h/8h/7d/forever y una fecha absoluta, y
  243. // POST /api/alerts/unsilence {id} quita la posposicion.
  244. func TestAlertsSnoozeEndpoint(t *testing.T) {
  245. ts := makeTestServer(t)
  246. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  247. res := doJSON(t, "POST", ts.URL, "/api/alerts/silence", cookie, `{"id":"alert-handshake-wg","duration":"2h"}`)
  248. if res.StatusCode != 200 {
  249. t.Fatalf("snooze: %d", res.StatusCode)
  250. }
  251. var snoozed struct {
  252. OK bool `json:"ok"`
  253. Key string `json:"key"`
  254. }
  255. if err := json.NewDecoder(res.Body).Decode(&snoozed); err != nil || !snoozed.OK || snoozed.Key == "" {
  256. t.Fatalf("snooze body: %+v err=%v", snoozed, err)
  257. }
  258. res.Body.Close()
  259. items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
  260. var row map[string]any
  261. for _, a := range items {
  262. if a["id"] == "alert-handshake-wg" {
  263. row = a
  264. }
  265. }
  266. if row == nil {
  267. t.Fatal("la alerta pospuesta debe seguir en el feed")
  268. }
  269. if got, _ := row["snoozed"].(bool); !got {
  270. t.Fatalf("snoozed ausente: %v", row)
  271. }
  272. until, _ := row["snoozedUntil"].(float64)
  273. if until <= float64(time.Now().Unix()) {
  274. t.Fatalf("snoozedUntil no está en el futuro: %v", row["snoozedUntil"])
  275. }
  276. // Quitar la posposicion por ID y ver que la marca desaparece.
  277. res = doJSON(t, "POST", ts.URL, "/api/alerts/unsilence", cookie, `{"id":"alert-handshake-wg"}`)
  278. if res.StatusCode != 200 {
  279. t.Fatalf("unsnooze por id: %d", res.StatusCode)
  280. }
  281. res.Body.Close()
  282. for _, a := range alertItems(t, get(t, ts.URL, "/api/alerts", cookie)) {
  283. if a["id"] == "alert-handshake-wg" {
  284. if got, _ := a["snoozed"].(bool); got {
  285. t.Fatalf("snoozed debería haberse quitado: %v", a)
  286. }
  287. }
  288. }
  289. // Duraciones válidas y fecha absoluta.
  290. future := time.Now().Add(3 * time.Hour).Unix()
  291. for _, body := range []string{
  292. `{"id":"alert-handshake-wg","duration":"1h"}`,
  293. `{"id":"alert-handshake-wg","duration":"8h"}`,
  294. `{"id":"alert-handshake-wg","duration":"7d"}`,
  295. `{"id":"alert-handshake-wg","duration":"forever"}`,
  296. fmt.Sprintf(`{"id":"alert-handshake-wg","until":%d}`, future),
  297. } {
  298. res = doJSON(t, "POST", ts.URL, "/api/alerts/silence", cookie, body)
  299. if res.StatusCode != 200 {
  300. t.Fatalf("snooze %s: %d", body, res.StatusCode)
  301. }
  302. res.Body.Close()
  303. }
  304. for _, body := range []string{
  305. `{"id":"alert-handshake-wg","duration":"5m"}`,
  306. `{"id":"alert-handshake-wg","until":1}`,
  307. `{"id":"no-existe","duration":"1h"}`,
  308. } {
  309. res = doJSON(t, "POST", ts.URL, "/api/alerts/silence", cookie, body)
  310. if body == `{"id":"no-existe","duration":"1h"}` {
  311. if res.StatusCode != 404 {
  312. t.Fatalf("snooze inexistente: %d, esperaba 404", res.StatusCode)
  313. }
  314. } else if res.StatusCode != 400 {
  315. t.Fatalf("snooze %s: %d, esperaba 400", body, res.StatusCode)
  316. }
  317. res.Body.Close()
  318. }
  319. }
  320. // #2223: un cuerpo sin duration ni until no puede posponer para siempre.
  321. // forever sigue disponible, pero solo cuando se pide por su nombre.
  322. func TestAlertsSilenceRequiresExpiry(t *testing.T) {
  323. ts := makeTestServer(t)
  324. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  325. res := doJSON(t, "POST", ts.URL, "/api/alerts/silence", cookie, `{"id":"alert-handshake-wg"}`)
  326. if res.StatusCode != 400 {
  327. t.Fatalf("silence sin duración: %d, esperaba 400", res.StatusCode)
  328. }
  329. res.Body.Close()
  330. for _, a := range alertItems(t, get(t, ts.URL, "/api/alerts", cookie)) {
  331. if a["id"] == "alert-handshake-wg" {
  332. if snoozed, _ := a["snoozed"].(bool); snoozed {
  333. t.Fatalf("se pospuso una alerta sin duración: %v", a)
  334. }
  335. }
  336. }
  337. res = doJSON(t, "POST", ts.URL, "/api/alerts/silence", cookie, `{"id":"alert-handshake-wg","duration":"forever"}`)
  338. if res.StatusCode != 200 {
  339. t.Fatalf("forever explícito: %d", res.StatusCode)
  340. }
  341. res.Body.Close()
  342. }