push_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. // push_test.go — contrato del Bloque C (SPEC-PUSH §1): VAPID estable en kv,
  2. // roundtrip del store de suscripciones, purga de suscripciones muertas
  3. // (404/410) y Notify con payload cifrado verificable contra un push service
  4. // simulado con httptest (descifrado aes128gcm RFC 8291/8188).
  5. package push_test
  6. import (
  7. "context"
  8. "crypto/aes"
  9. "crypto/cipher"
  10. "crypto/elliptic"
  11. "crypto/rand"
  12. "crypto/sha256"
  13. "crypto/tls"
  14. "encoding/base64"
  15. "encoding/binary"
  16. "encoding/json"
  17. "io"
  18. "net"
  19. "net/http"
  20. "net/http/httptest"
  21. "os"
  22. "path/filepath"
  23. "strings"
  24. "sync"
  25. "testing"
  26. "time"
  27. "github.com/gnacho/netpulse/server-go/internal/alertlang"
  28. "github.com/gnacho/netpulse/server-go/internal/alerts"
  29. "github.com/gnacho/netpulse/server-go/internal/db"
  30. "github.com/gnacho/netpulse/server-go/internal/push"
  31. "golang.org/x/crypto/hkdf"
  32. )
  33. func openDB(t *testing.T) (*db.DB, string) {
  34. t.Helper()
  35. dir := t.TempDir()
  36. d, err := db.Open(dir)
  37. if err != nil {
  38. t.Fatalf("db.Open: %v", err)
  39. }
  40. t.Cleanup(func() { d.Close() })
  41. return d, dir
  42. }
  43. func TestVAPIDStable(t *testing.T) {
  44. d, dir := openDB(t)
  45. pub1, priv1, err := push.EnsureVAPIDKeys(d)
  46. if err != nil {
  47. t.Fatalf("EnsureVAPIDKeys: %v", err)
  48. }
  49. if pub1 == "" || priv1 == "" || pub1 == priv1 {
  50. t.Fatalf("par VAPID inválido: pub=%q priv=%q", pub1, priv1)
  51. }
  52. // Segunda llamada: mismo par (no regenera).
  53. pub2, priv2, _ := push.EnsureVAPIDKeys(d)
  54. if pub1 != pub2 || priv1 != priv2 {
  55. t.Fatal("VAPID no estable entre llamadas")
  56. }
  57. // Reinicio (reabrir la misma DB): mismo par (persistido en kv).
  58. d.Close()
  59. d2, err := db.Open(dir)
  60. if err != nil {
  61. t.Fatalf("reabrir db: %v", err)
  62. }
  63. defer d2.Close()
  64. pub3, priv3, _ := push.EnsureVAPIDKeys(d2)
  65. if pub1 != pub3 || priv1 != priv3 {
  66. t.Fatal("VAPID no estable entre reinicios")
  67. }
  68. }
  69. func TestStoreRoundtrip(t *testing.T) {
  70. d, _ := openDB(t)
  71. sub := push.Subscription{Endpoint: "https://push.example/abc", Auth: "a", P256dh: "p", UserAgent: "test-ua"}
  72. created, err := push.UpsertSubscription(d, sub)
  73. if err != nil || !created {
  74. t.Fatalf("upsert nuevo: created=%v err=%v", created, err)
  75. }
  76. // Upsert del mismo endpoint: actualiza, no duplica.
  77. sub.Auth = "a2"
  78. created, err = push.UpsertSubscription(d, sub)
  79. if err != nil || created {
  80. t.Fatalf("upsert existente: created=%v err=%v", created, err)
  81. }
  82. subs, err := push.ListSubscriptions(d)
  83. if err != nil || len(subs) != 1 {
  84. t.Fatalf("list: %v %v", subs, err)
  85. }
  86. if subs[0].Auth != "a2" || subs[0].P256dh != "p" || subs[0].UserAgent != "test-ua" || subs[0].CreatedAt <= 0 {
  87. t.Fatalf("fila: %+v", subs[0])
  88. }
  89. if err := push.DeleteSubscription(d, sub.Endpoint); err != nil {
  90. t.Fatalf("delete: %v", err)
  91. }
  92. // Idempotente: borrar de nuevo no es error.
  93. if err := push.DeleteSubscription(d, sub.Endpoint); err != nil {
  94. t.Fatalf("delete idempotente: %v", err)
  95. }
  96. subs, _ = push.ListSubscriptions(d)
  97. if len(subs) != 0 {
  98. t.Fatalf("tras delete: %d suscripciones", len(subs))
  99. }
  100. }
  101. // browserSub simula una PushSubscription del navegador: par ECDH P-256 y
  102. // auth secret (16 B), devueltos para poder descifrar en el test.
  103. type browserSub struct {
  104. auth []byte
  105. priv []byte
  106. pub []byte // uncompressed point (65 B)
  107. authB string
  108. pubB string
  109. }
  110. func newBrowserSub(t *testing.T) browserSub {
  111. t.Helper()
  112. priv, x, y, err := elliptic.GenerateKey(elliptic.P256(), rand.Reader)
  113. if err != nil {
  114. t.Fatalf("keypair navegador: %v", err)
  115. }
  116. pub := elliptic.Marshal(elliptic.P256(), x, y)
  117. auth := make([]byte, 16)
  118. if _, err := rand.Read(auth); err != nil {
  119. t.Fatalf("auth secret: %v", err)
  120. }
  121. return browserSub{
  122. auth: auth,
  123. priv: priv,
  124. pub: pub,
  125. authB: base64.RawURLEncoding.EncodeToString(auth),
  126. pubB: base64.RawURLEncoding.EncodeToString(pub),
  127. }
  128. }
  129. type capturedPush struct {
  130. method string
  131. header http.Header
  132. body []byte
  133. }
  134. // decryptAES128GCM descifra el cuerpo tal y como lo haría el navegador
  135. // (RFC 8291 §3.4 + RFC 8188 §2: header salt|rs|idlen|keyid en el cuerpo,
  136. // registro único con delimitador 0x02 y padding de ceros al final).
  137. func decryptAES128GCM(t *testing.T, ua browserSub, body []byte) []byte {
  138. t.Helper()
  139. if len(body) < 16+4+1+65+17 {
  140. t.Fatalf("cuerpo cifrado demasiado corto: %d B", len(body))
  141. }
  142. salt := body[:16]
  143. rs := binary.BigEndian.Uint32(body[16:20])
  144. idlen := int(body[20])
  145. asPub := body[21 : 21+idlen]
  146. ciphertext := body[21+idlen:]
  147. if rs < uint32(len(ciphertext)) {
  148. t.Fatalf("record size incoherente: rs=%d ct=%d", rs, len(ciphertext))
  149. }
  150. curve := elliptic.P256()
  151. x, y := elliptic.Unmarshal(curve, asPub)
  152. if x == nil {
  153. t.Fatal("clave efímera del servidor no es un punto válido")
  154. }
  155. sx, _ := curve.ScalarMult(x, y, ua.priv)
  156. secret := make([]byte, 32)
  157. sx.FillBytes(secret)
  158. read := func(prkSecret, hkdfSalt, info []byte, n int) []byte {
  159. out := make([]byte, n)
  160. if _, err := io.ReadFull(hkdf.New(sha256.New, prkSecret, hkdfSalt, info), out); err != nil {
  161. t.Fatalf("hkdf: %v", err)
  162. }
  163. return out
  164. }
  165. info := append(append([]byte("WebPush: info\x00"), ua.pub...), asPub...)
  166. ikm := read(secret, ua.auth, info, 32)
  167. cek := read(ikm, salt, []byte("Content-Encoding: aes128gcm\x00"), 16)
  168. nonce := read(ikm, salt, []byte("Content-Encoding: nonce\x00"), 12)
  169. block, err := aes.NewCipher(cek)
  170. if err != nil {
  171. t.Fatalf("aes: %v", err)
  172. }
  173. gcm, err := cipher.NewGCM(block)
  174. if err != nil {
  175. t.Fatalf("gcm: %v", err)
  176. }
  177. plain, err := gcm.Open(nil, nonce, ciphertext, nil)
  178. if err != nil {
  179. t.Fatalf("descifrado GCM (¿claves mal derivadas?): %v", err)
  180. }
  181. // Quitar padding: ceros finales + delimitador 0x02 (registro final).
  182. i := len(plain) - 1
  183. for i >= 0 && plain[i] == 0 {
  184. i--
  185. }
  186. if i < 0 || plain[i] != 0x02 {
  187. t.Fatalf("delimitador 0x02 no encontrado (plain=%d B)", len(plain))
  188. }
  189. return plain[:i]
  190. }
  191. func testEvent() alerts.AlertEvent {
  192. return alerts.AlertEvent{
  193. ID: "alert-test-1",
  194. Category: alerts.CatRouter,
  195. Urgent: true,
  196. Severity: "critical",
  197. Title: "Router sin respuesta",
  198. Description: "Sin respuesta de 192.168.8.1",
  199. Hint: "Revisa la alimentación del router",
  200. Type: "router-down",
  201. Vars: map[string]string{"router": "192.168.8.1"},
  202. }
  203. }
  204. func newNotifier(t *testing.T, d *db.DB, clients ...*http.Client) *push.Notifier {
  205. t.Helper()
  206. pub, priv, err := push.EnsureVAPIDKeys(d)
  207. if err != nil {
  208. t.Fatalf("vapid: %v", err)
  209. }
  210. var n *push.Notifier
  211. if len(clients) > 0 && clients[0] != nil {
  212. n = push.NewNotifierWithClient(d, pub, priv, clients[0])
  213. } else {
  214. n = push.NewNotifier(d, pub, priv)
  215. }
  216. t.Cleanup(n.Close)
  217. return n
  218. }
  219. // testPushClient routes every request to the given test TLS server, so tests
  220. // can use public-looking endpoints such as https://push.example.
  221. func testPushClient(srv *httptest.Server) *http.Client {
  222. return &http.Client{
  223. Timeout: 15 * time.Second,
  224. Transport: &http.Transport{
  225. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  226. DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
  227. return (&net.Dialer{}).DialContext(ctx, network, srv.Listener.Addr().String())
  228. },
  229. },
  230. }
  231. }
  232. // El Notifier envía un POST cifrado aes128gcm con cabecera VAPID al endpoint
  233. // suscrito, y el payload descifrado cumple el contrato del SW.
  234. func TestNotifierSendsEncryptedPayload(t *testing.T) {
  235. d, _ := openDB(t)
  236. pub, _, _ := push.EnsureVAPIDKeys(d)
  237. ua := newBrowserSub(t)
  238. got := make(chan capturedPush, 1)
  239. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  240. body, _ := io.ReadAll(r.Body)
  241. got <- capturedPush{method: r.Method, header: r.Header.Clone(), body: body}
  242. w.WriteHeader(http.StatusCreated)
  243. }))
  244. defer srv.Close()
  245. if _, err := push.UpsertSubscription(d, push.Subscription{
  246. Endpoint: "https://push.example/send", Auth: ua.authB, P256dh: ua.pubB,
  247. }); err != nil {
  248. t.Fatalf("upsert: %v", err)
  249. }
  250. n := newNotifier(t, d, testPushClient(srv))
  251. n.Notify(testEvent())
  252. var req capturedPush
  253. select {
  254. case req = <-got:
  255. case <-time.After(15 * time.Second):
  256. t.Fatal("el push service simulado no recibió nada en 15 s")
  257. }
  258. if req.method != http.MethodPost {
  259. t.Fatalf("método: %s, esperaba POST", req.method)
  260. }
  261. if enc := req.header.Get("Content-Encoding"); enc != "aes128gcm" {
  262. t.Fatalf("Content-Encoding: %q", enc)
  263. }
  264. if ttl := req.header.Get("TTL"); ttl != "3600" {
  265. t.Fatalf("TTL: %q", ttl)
  266. }
  267. authz := req.header.Get("Authorization")
  268. if !strings.HasPrefix(authz, "vapid t=") || !strings.Contains(authz, ", k=") {
  269. t.Fatalf("Authorization VAPID: %q", authz)
  270. }
  271. if !strings.Contains(authz, ", k="+pub) {
  272. t.Fatal("la cabecera VAPID no lleva la clave pública servida en /api/push/vapid-key")
  273. }
  274. plain := decryptAES128GCM(t, ua, req.body)
  275. var p struct {
  276. Title string `json:"title"`
  277. Body string `json:"body"`
  278. Type string `json:"type"`
  279. Vars map[string]string `json:"vars"`
  280. Category string `json:"category"`
  281. Severity string `json:"severity"`
  282. URL string `json:"url"`
  283. Tag string `json:"tag"`
  284. Hint string `json:"hint"`
  285. }
  286. if err := json.Unmarshal(plain, &p); err != nil {
  287. t.Fatalf("payload no es JSON: %v (%q)", err, plain)
  288. }
  289. if p.Title != "Router sin respuesta" || p.Body != "Sin respuesta de 192.168.8.1" ||
  290. p.Category != "router" || p.Severity != "critical" || p.URL != "/alerts" || p.Tag != "alert-test-1" {
  291. t.Fatalf("payload: %+v", p)
  292. }
  293. if p.Hint != "Revisa la alimentación del router" {
  294. t.Fatalf("payload hint: %q", p.Hint)
  295. }
  296. // #689: el slug y las vars viajan para que el SW pueda traducir el push.
  297. if p.Type != "router-down" || p.Vars["router"] != "192.168.8.1" {
  298. t.Fatalf("payload type/vars: type=%q vars=%v", p.Type, p.Vars)
  299. }
  300. }
  301. // Un push service que responde 410 (suscripción expirada) provoca la purga
  302. // de la fila; el resto de suscripciones se conserva.
  303. func TestNotifierPurgesGoneSubscription(t *testing.T) {
  304. d, _ := openDB(t)
  305. ua := newBrowserSub(t)
  306. got := make(chan struct{}, 2)
  307. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  308. got <- struct{}{}
  309. if r.URL.Path == "/dead" {
  310. w.WriteHeader(http.StatusGone)
  311. return
  312. }
  313. w.WriteHeader(http.StatusCreated)
  314. }))
  315. defer srv.Close()
  316. for _, ep := range []string{"https://push.example/dead", "https://push.example/alive"} {
  317. if _, err := push.UpsertSubscription(d, push.Subscription{Endpoint: ep, Auth: ua.authB, P256dh: ua.pubB}); err != nil {
  318. t.Fatalf("upsert: %v", err)
  319. }
  320. }
  321. n := newNotifier(t, d, testPushClient(srv))
  322. n.Notify(testEvent())
  323. for i := 0; i < 2; i++ {
  324. select {
  325. case <-got:
  326. case <-time.After(15 * time.Second):
  327. t.Fatalf("solo %d/2 envíos recibidos", i)
  328. }
  329. }
  330. n.Close() // drena el worker: la purga ya ocurrió
  331. subs, err := push.ListSubscriptions(d)
  332. if err != nil {
  333. t.Fatalf("list: %v", err)
  334. }
  335. if len(subs) != 1 || subs[0].Endpoint != "https://push.example/alive" {
  336. t.Fatalf("tras purga: %+v", subs)
  337. }
  338. }
  339. // TestNotifierCloseConNotifyConcurrentesNoPanic reproduce el bug #202:
  340. // Close() cerraba el canal de la cola y un Notify concurrente podía elegir
  341. // la rama de envío tras el close → panic "send on closed channel".
  342. func TestNotifierCloseConNotifyConcurrentesNoPanic(t *testing.T) {
  343. d, _ := openDB(t)
  344. pub, _, _ := push.EnsureVAPIDKeys(d)
  345. n := newNotifier(t, d)
  346. _ = pub
  347. done := make(chan struct{})
  348. var wg sync.WaitGroup
  349. for i := 0; i < 8; i++ {
  350. wg.Add(1)
  351. go func() {
  352. defer wg.Done()
  353. for {
  354. select {
  355. case <-done:
  356. return
  357. default:
  358. n.Notify(testEvent())
  359. }
  360. }
  361. }()
  362. }
  363. time.Sleep(5 * time.Millisecond)
  364. n.Close()
  365. close(done)
  366. wg.Wait()
  367. }
  368. // #1334: el payload se compone POR suscripción: la que guardó idioma es/en
  369. // recibe el texto en ese idioma del catálogo, aunque el evento llegue con
  370. // literales en inglés y el ajuste global sea otro.
  371. func TestNotifierLocalizesPerSubscription(t *testing.T) {
  372. d, _ := openDB(t)
  373. root, err := filepath.Abs("../../..")
  374. if err != nil {
  375. t.Fatal(err)
  376. }
  377. alertlang.SetLocalesFS(os.DirFS(filepath.Join(root, "app", "dist", "locales")))
  378. if len(alertlang.Supported()) == 0 {
  379. t.Fatal("sin catálogos (¿falta npm run build en app/?)")
  380. }
  381. uaES := newBrowserSub(t)
  382. uaEN := newBrowserSub(t)
  383. type got struct {
  384. path string
  385. body []byte
  386. }
  387. ch := make(chan got, 2)
  388. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  389. body, _ := io.ReadAll(r.Body)
  390. ch <- got{path: r.URL.Path, body: body}
  391. w.WriteHeader(http.StatusCreated)
  392. }))
  393. defer srv.Close()
  394. for _, s := range []struct {
  395. path, lang string
  396. ua browserSub
  397. }{
  398. {"/es", "es", uaES},
  399. {"/en", "en", uaEN},
  400. } {
  401. if _, err := push.UpsertSubscription(d, push.Subscription{
  402. Endpoint: "https://push.example" + s.path, Auth: s.ua.authB, P256dh: s.ua.pubB, Language: s.lang,
  403. }); err != nil {
  404. t.Fatalf("upsert: %v", err)
  405. }
  406. }
  407. n := newNotifier(t, d, testPushClient(srv))
  408. n.Notify(alerts.AlertEvent{
  409. ID: "alert-agent-down-gateway", Category: alerts.CatRouter, Urgent: true, Severity: "warn",
  410. Type: "agent-down", Title: "CANARY", Description: "CANARY",
  411. Vars: map[string]string{"router": "gateway", "confirm": "5m"},
  412. })
  413. byPath := map[string][]byte{}
  414. for i := 0; i < 2; i++ {
  415. select {
  416. case g := <-ch:
  417. byPath[g.path] = g.body
  418. case <-time.After(15 * time.Second):
  419. t.Fatal("push service simulado no recibió las dos suscripciones")
  420. }
  421. }
  422. decode := func(path string, ua browserSub) (title, body string) {
  423. t.Helper()
  424. raw, ok := byPath[path]
  425. if !ok {
  426. t.Fatalf("sin push en %s", path)
  427. }
  428. var p struct {
  429. Title string `json:"title"`
  430. Body string `json:"body"`
  431. }
  432. if err := json.Unmarshal(decryptAES128GCM(t, ua, raw), &p); err != nil {
  433. t.Fatalf("payload %s no es JSON: %v", path, err)
  434. }
  435. return p.Title, p.Body
  436. }
  437. esTitle, esBody := decode("/es", uaES)
  438. if !strings.Contains(esTitle, "Agente caído") || !strings.Contains(esBody, "gateway") {
  439. t.Fatalf("suscripción ES sin traducir: title=%q body=%q", esTitle, esBody)
  440. }
  441. enTitle, enBody := decode("/en", uaEN)
  442. if !strings.Contains(enTitle, "Agent down") || !strings.Contains(enBody, "gateway") {
  443. t.Fatalf("suscripción EN sin traducir: title=%q body=%q", enTitle, enBody)
  444. }
  445. if esTitle == "CANARY" || enTitle == "CANARY" {
  446. t.Fatal("el canario no debe llegar sin localizar")
  447. }
  448. }