| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369 |
- // alerts_api_test.go — contrato de los endpoints de alertas (SPEC-ALERTAS §4):
- // GET /api/alerts (+category, +unread=1), GET/PUT /api/alerts/config,
- // POST /api/alerts/read y /api/alerts/read-all (server truth en overview).
- package httpapi_test
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "strings"
- "testing"
- "time"
- )
- func doJSON(t *testing.T, method, base, path, cookie string, body string) *http.Response {
- t.Helper()
- var rd io.Reader
- if body != "" {
- rd = bytes.NewBufferString(body)
- }
- req, _ := http.NewRequest(method, base+path, rd)
- if body != "" {
- req.Header.Set("Content-Type", "application/json")
- }
- if cookie != "" {
- req.Header.Set("Cookie", "session="+cookie)
- }
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatalf("%s %s: %v", method, path, err)
- }
- return res
- }
- func alertItems(t *testing.T, res *http.Response) []map[string]any {
- t.Helper()
- defer res.Body.Close()
- var body struct {
- Items []map[string]any `json:"items"`
- }
- if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
- t.Fatalf("json: %v", err)
- }
- return body.Items
- }
- func TestAlertsContractFields(t *testing.T) {
- ts := makeTestServer(t)
- _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
- res := get(t, ts.URL, "/api/alerts", cookie)
- items := alertItems(t, res)
- if len(items) != 5 {
- t.Fatalf("alertas demo: %d, esperaba 5", len(items))
- }
- for _, a := range items {
- if a["category"] == nil || a["category"] == "" {
- t.Fatalf("alerta sin category: %v", a["id"])
- }
- if _, ok := a["urgent"].(bool); !ok {
- t.Fatalf("alerta sin urgent bool: %v", a["id"])
- }
- if ts64, ok := a["ts"].(float64); !ok || ts64 <= 0 {
- t.Fatalf("alerta sin ts: %v", a["id"])
- }
- }
- // Filtro por categoría: vpn → solo el handshake
- items = alertItems(t, get(t, ts.URL, "/api/alerts?category=vpn", cookie))
- if len(items) != 1 || items[0]["id"] != "alert-handshake-wg" {
- t.Fatalf("category=vpn: %v", items)
- }
- // Categoría inválida → 400
- res = get(t, ts.URL, "/api/alerts?category=wifi", cookie)
- if res.StatusCode != 400 {
- t.Fatalf("category inválida: %d, esperaba 400", res.StatusCode)
- }
- res.Body.Close()
- // unread=1 → las 2 no leídas del canon
- items = alertItems(t, get(t, ts.URL, "/api/alerts?unread=1", cookie))
- if len(items) != 2 {
- t.Fatalf("unread=1: %d, esperaba 2", len(items))
- }
- for _, a := range items {
- if a["read"] == true {
- t.Fatalf("unread=1 devolvió leída: %v", a["id"])
- }
- }
- // Combinado: category + unread
- items = alertItems(t, get(t, ts.URL, "/api/alerts?category=clients&unread=1", cookie))
- if len(items) != 0 {
- t.Fatalf("clients&unread: %d, esperaba 0 (la canon clients está leída)", len(items))
- }
- }
- func TestAlertsConfigEndpoints(t *testing.T) {
- ts := makeTestServer(t)
- _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
- res := get(t, ts.URL, "/api/alerts/config", cookie)
- cfg := readJSON(t, res)
- if len(cfg) != 6 {
- t.Fatalf("config: %d claves, esperaba 6", len(cfg))
- }
- want := map[string]string{"router": "urgent", "internet": "urgent", "clients": "all",
- "signal": "none", "vpn": "none", "system": "all"}
- for k, v := range want {
- if cfg[k] != v {
- t.Fatalf("default %s: %v, esperaba %s", k, cfg[k], v)
- }
- }
- // PUT parcial → 200 y devuelve la config efectiva completa
- res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `{"vpn":"all"}`)
- if res.StatusCode != 200 {
- t.Fatalf("PUT config: %d", res.StatusCode)
- }
- cfg = readJSON(t, res)
- if cfg["vpn"] != "all" || cfg["router"] != "urgent" {
- t.Fatalf("PUT parcial: %v", cfg)
- }
- // Roundtrip: GET refleja el cambio (persistido en kv)
- cfg = readJSON(t, get(t, ts.URL, "/api/alerts/config", cookie))
- if cfg["vpn"] != "all" {
- t.Fatalf("roundtrip: %v", cfg)
- }
- // Nivel inválido → 400
- res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `{"vpn":"todo"}`)
- if res.StatusCode != 400 {
- t.Fatalf("nivel inválido: %d, esperaba 400", res.StatusCode)
- }
- res.Body.Close()
- // Categoría desconocida → 400
- res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `{"wifi":"all"}`)
- if res.StatusCode != 400 {
- t.Fatalf("categoría desconocida: %d, esperaba 400", res.StatusCode)
- }
- res.Body.Close()
- // Body no-JSON → 400
- res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `nope`)
- if res.StatusCode != 400 {
- t.Fatalf("body inválido: %d, esperaba 400", res.StatusCode)
- }
- res.Body.Close()
- }
- func TestAlertsReadEndpoints(t *testing.T) {
- ts := makeTestServer(t)
- _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
- unreadOf := func() float64 {
- res := get(t, ts.URL, "/api/overview", cookie)
- body := readJSON(t, res)
- return body["unreadAlerts"].(float64)
- }
- if got := unreadOf(); got != 2 {
- t.Fatalf("unreadAlerts inicial: %v, esperaba 2", got)
- }
- // POST read {ids}: marca una
- res := doJSON(t, "POST", ts.URL, "/api/alerts/read", cookie, `{"ids":["alert-temp-patio"]}`)
- if res.StatusCode != 200 {
- t.Fatalf("read: %d", res.StatusCode)
- }
- res.Body.Close()
- if got := unreadOf(); got != 1 {
- t.Fatalf("unreadAlerts tras read: %v, esperaba 1", got)
- }
- items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
- for _, a := range items {
- if a["id"] == "alert-temp-patio" && a["read"] != true {
- t.Fatal("read no aplicado en GET /api/alerts")
- }
- }
- // POST read-all → 0 en overview (server truth)
- res = doJSON(t, "POST", ts.URL, "/api/alerts/read-all", cookie, "")
- if res.StatusCode != 200 {
- t.Fatalf("read-all: %d", res.StatusCode)
- }
- res.Body.Close()
- if got := unreadOf(); got != 0 {
- t.Fatalf("unreadAlerts tras read-all: %v, esperaba 0", got)
- }
- items = alertItems(t, get(t, ts.URL, "/api/alerts?unread=1", cookie))
- if len(items) != 0 {
- t.Fatalf("unread=1 tras read-all: %d", len(items))
- }
- }
- // POST /api/alerts/dismiss (issue #833): limpia alertas del feed.
- func TestAlertsDismissEndpoint(t *testing.T) {
- ts := makeTestServer(t)
- _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
- // ids vacío → 400
- res := doJSON(t, "POST", ts.URL, "/api/alerts/dismiss", cookie, `{"ids":[]}`)
- if res.StatusCode != 400 {
- t.Fatalf("dismiss ids vacío: %d, esperaba 400", res.StatusCode)
- }
- res.Body.Close()
- res = doJSON(t, "POST", ts.URL, "/api/alerts/dismiss", cookie, `{"ids":["alert-temp-patio"]}`)
- if res.StatusCode != 200 {
- t.Fatalf("dismiss: %d", res.StatusCode)
- }
- res.Body.Close()
- items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
- for _, a := range items {
- if a["id"] == "alert-temp-patio" {
- t.Fatal("alert-temp-patio debía haber desaparecido del feed")
- }
- }
- // unread baja: la alerta limpiada cuenta como leída y se elimina.
- unread := 0
- for _, a := range items {
- if a["read"] != true {
- unread++
- }
- }
- if unread != 1 {
- t.Fatalf("unread tras dismiss: %d, esperaba 1", unread)
- }
- }
- // POST /api/alerts/clear (issue #971): "Marcar todo como leído" VACÍA el
- // feed - las alertas se descartan, no solo se marcan - y el badge queda a 0.
- func TestAlertsClearAllEndpoint(t *testing.T) {
- ts := makeTestServer(t)
- _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
- res := doJSON(t, "POST", ts.URL, "/api/alerts/clear", cookie, "")
- if res.StatusCode != 200 {
- t.Fatalf("clear: %d", res.StatusCode)
- }
- res.Body.Close()
- items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
- if len(items) != 0 {
- t.Fatalf("feed tras clear: %d, esperaba 0", len(items))
- }
- body := readJSON(t, get(t, ts.URL, "/api/overview", cookie))
- if got := body["unreadAlerts"].(float64); got != 0 {
- t.Fatalf("unreadAlerts tras clear: %v, esperaba 0", got)
- }
- }
- // writeJSON sin '\n' final (paridad D5, SPEC-ALERTAS §4).
- func TestAlertsNoTrailingNewline(t *testing.T) {
- ts := makeTestServer(t)
- _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
- res := get(t, ts.URL, "/api/alerts/config", cookie)
- defer res.Body.Close()
- raw, _ := io.ReadAll(res.Body)
- if strings.HasSuffix(string(raw), "\n") {
- t.Fatal("writeJSON no debe terminar en \\n")
- }
- }
- // POST /api/alerts/silence (#2185): posponer deja la alerta en el feed con
- // snoozed/snoozedUntil, acepta 1h/2h/8h/7d/forever y una fecha absoluta, y
- // POST /api/alerts/unsilence {id} quita la posposicion.
- func TestAlertsSnoozeEndpoint(t *testing.T) {
- ts := makeTestServer(t)
- _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
- res := doJSON(t, "POST", ts.URL, "/api/alerts/silence", cookie, `{"id":"alert-handshake-wg","duration":"2h"}`)
- if res.StatusCode != 200 {
- t.Fatalf("snooze: %d", res.StatusCode)
- }
- var snoozed struct {
- OK bool `json:"ok"`
- Key string `json:"key"`
- }
- if err := json.NewDecoder(res.Body).Decode(&snoozed); err != nil || !snoozed.OK || snoozed.Key == "" {
- t.Fatalf("snooze body: %+v err=%v", snoozed, err)
- }
- res.Body.Close()
- items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
- var row map[string]any
- for _, a := range items {
- if a["id"] == "alert-handshake-wg" {
- row = a
- }
- }
- if row == nil {
- t.Fatal("la alerta pospuesta debe seguir en el feed")
- }
- if got, _ := row["snoozed"].(bool); !got {
- t.Fatalf("snoozed ausente: %v", row)
- }
- until, _ := row["snoozedUntil"].(float64)
- if until <= float64(time.Now().Unix()) {
- t.Fatalf("snoozedUntil no está en el futuro: %v", row["snoozedUntil"])
- }
- // Quitar la posposicion por ID y ver que la marca desaparece.
- res = doJSON(t, "POST", ts.URL, "/api/alerts/unsilence", cookie, `{"id":"alert-handshake-wg"}`)
- if res.StatusCode != 200 {
- t.Fatalf("unsnooze por id: %d", res.StatusCode)
- }
- res.Body.Close()
- for _, a := range alertItems(t, get(t, ts.URL, "/api/alerts", cookie)) {
- if a["id"] == "alert-handshake-wg" {
- if got, _ := a["snoozed"].(bool); got {
- t.Fatalf("snoozed debería haberse quitado: %v", a)
- }
- }
- }
- // Duraciones válidas y fecha absoluta.
- future := time.Now().Add(3 * time.Hour).Unix()
- for _, body := range []string{
- `{"id":"alert-handshake-wg","duration":"1h"}`,
- `{"id":"alert-handshake-wg","duration":"8h"}`,
- `{"id":"alert-handshake-wg","duration":"7d"}`,
- `{"id":"alert-handshake-wg","duration":"forever"}`,
- fmt.Sprintf(`{"id":"alert-handshake-wg","until":%d}`, future),
- } {
- res = doJSON(t, "POST", ts.URL, "/api/alerts/silence", cookie, body)
- if res.StatusCode != 200 {
- t.Fatalf("snooze %s: %d", body, res.StatusCode)
- }
- res.Body.Close()
- }
- for _, body := range []string{
- `{"id":"alert-handshake-wg","duration":"5m"}`,
- `{"id":"alert-handshake-wg","until":1}`,
- `{"id":"no-existe","duration":"1h"}`,
- } {
- res = doJSON(t, "POST", ts.URL, "/api/alerts/silence", cookie, body)
- if body == `{"id":"no-existe","duration":"1h"}` {
- if res.StatusCode != 404 {
- t.Fatalf("snooze inexistente: %d, esperaba 404", res.StatusCode)
- }
- } else if res.StatusCode != 400 {
- t.Fatalf("snooze %s: %d, esperaba 400", body, res.StatusCode)
- }
- res.Body.Close()
- }
- }
- // #2223: un cuerpo sin duration ni until no puede posponer para siempre.
- // forever sigue disponible, pero solo cuando se pide por su nombre.
- func TestAlertsSilenceRequiresExpiry(t *testing.T) {
- ts := makeTestServer(t)
- _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
- res := doJSON(t, "POST", ts.URL, "/api/alerts/silence", cookie, `{"id":"alert-handshake-wg"}`)
- if res.StatusCode != 400 {
- t.Fatalf("silence sin duración: %d, esperaba 400", res.StatusCode)
- }
- res.Body.Close()
- for _, a := range alertItems(t, get(t, ts.URL, "/api/alerts", cookie)) {
- if a["id"] == "alert-handshake-wg" {
- if snoozed, _ := a["snoozed"].(bool); snoozed {
- t.Fatalf("se pospuso una alerta sin duración: %v", a)
- }
- }
- }
- res = doJSON(t, "POST", ts.URL, "/api/alerts/silence", cookie, `{"id":"alert-handshake-wg","duration":"forever"}`)
- if res.StatusCode != 200 {
- t.Fatalf("forever explícito: %d", res.StatusCode)
- }
- res.Body.Close()
- }
|