push_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. "crypto/aes"
  8. "crypto/cipher"
  9. "crypto/elliptic"
  10. "crypto/rand"
  11. "crypto/sha256"
  12. "encoding/base64"
  13. "encoding/binary"
  14. "encoding/json"
  15. "io"
  16. "net/http"
  17. "net/http/httptest"
  18. "strings"
  19. "sync"
  20. "testing"
  21. "time"
  22. "github.com/gnacho/netpulse/server-go/internal/alerts"
  23. "github.com/gnacho/netpulse/server-go/internal/db"
  24. "github.com/gnacho/netpulse/server-go/internal/push"
  25. "golang.org/x/crypto/hkdf"
  26. )
  27. func openDB(t *testing.T) (*db.DB, string) {
  28. t.Helper()
  29. dir := t.TempDir()
  30. d, err := db.Open(dir)
  31. if err != nil {
  32. t.Fatalf("db.Open: %v", err)
  33. }
  34. t.Cleanup(func() { d.Close() })
  35. return d, dir
  36. }
  37. func TestVAPIDStable(t *testing.T) {
  38. d, dir := openDB(t)
  39. pub1, priv1, err := push.EnsureVAPIDKeys(d)
  40. if err != nil {
  41. t.Fatalf("EnsureVAPIDKeys: %v", err)
  42. }
  43. if pub1 == "" || priv1 == "" || pub1 == priv1 {
  44. t.Fatalf("par VAPID inválido: pub=%q priv=%q", pub1, priv1)
  45. }
  46. // Segunda llamada: mismo par (no regenera).
  47. pub2, priv2, _ := push.EnsureVAPIDKeys(d)
  48. if pub1 != pub2 || priv1 != priv2 {
  49. t.Fatal("VAPID no estable entre llamadas")
  50. }
  51. // Reinicio (reabrir la misma DB): mismo par (persistido en kv).
  52. d.Close()
  53. d2, err := db.Open(dir)
  54. if err != nil {
  55. t.Fatalf("reabrir db: %v", err)
  56. }
  57. defer d2.Close()
  58. pub3, priv3, _ := push.EnsureVAPIDKeys(d2)
  59. if pub1 != pub3 || priv1 != priv3 {
  60. t.Fatal("VAPID no estable entre reinicios")
  61. }
  62. }
  63. func TestStoreRoundtrip(t *testing.T) {
  64. d, _ := openDB(t)
  65. sub := push.Subscription{Endpoint: "https://push.example/abc", Auth: "a", P256dh: "p", UserAgent: "test-ua"}
  66. created, err := push.UpsertSubscription(d, sub)
  67. if err != nil || !created {
  68. t.Fatalf("upsert nuevo: created=%v err=%v", created, err)
  69. }
  70. // Upsert del mismo endpoint: actualiza, no duplica.
  71. sub.Auth = "a2"
  72. created, err = push.UpsertSubscription(d, sub)
  73. if err != nil || created {
  74. t.Fatalf("upsert existente: created=%v err=%v", created, err)
  75. }
  76. subs, err := push.ListSubscriptions(d)
  77. if err != nil || len(subs) != 1 {
  78. t.Fatalf("list: %v %v", subs, err)
  79. }
  80. if subs[0].Auth != "a2" || subs[0].P256dh != "p" || subs[0].UserAgent != "test-ua" || subs[0].CreatedAt <= 0 {
  81. t.Fatalf("fila: %+v", subs[0])
  82. }
  83. if err := push.DeleteSubscription(d, sub.Endpoint); err != nil {
  84. t.Fatalf("delete: %v", err)
  85. }
  86. // Idempotente: borrar de nuevo no es error.
  87. if err := push.DeleteSubscription(d, sub.Endpoint); err != nil {
  88. t.Fatalf("delete idempotente: %v", err)
  89. }
  90. subs, _ = push.ListSubscriptions(d)
  91. if len(subs) != 0 {
  92. t.Fatalf("tras delete: %d suscripciones", len(subs))
  93. }
  94. }
  95. // browserSub simula una PushSubscription del navegador: par ECDH P-256 y
  96. // auth secret (16 B), devueltos para poder descifrar en el test.
  97. type browserSub struct {
  98. auth []byte
  99. priv []byte
  100. pub []byte // uncompressed point (65 B)
  101. authB string
  102. pubB string
  103. }
  104. func newBrowserSub(t *testing.T) browserSub {
  105. t.Helper()
  106. priv, x, y, err := elliptic.GenerateKey(elliptic.P256(), rand.Reader)
  107. if err != nil {
  108. t.Fatalf("keypair navegador: %v", err)
  109. }
  110. pub := elliptic.Marshal(elliptic.P256(), x, y)
  111. auth := make([]byte, 16)
  112. if _, err := rand.Read(auth); err != nil {
  113. t.Fatalf("auth secret: %v", err)
  114. }
  115. return browserSub{
  116. auth: auth,
  117. priv: priv,
  118. pub: pub,
  119. authB: base64.RawURLEncoding.EncodeToString(auth),
  120. pubB: base64.RawURLEncoding.EncodeToString(pub),
  121. }
  122. }
  123. type capturedPush struct {
  124. method string
  125. header http.Header
  126. body []byte
  127. }
  128. // decryptAES128GCM descifra el cuerpo tal y como lo haría el navegador
  129. // (RFC 8291 §3.4 + RFC 8188 §2: header salt|rs|idlen|keyid en el cuerpo,
  130. // registro único con delimitador 0x02 y padding de ceros al final).
  131. func decryptAES128GCM(t *testing.T, ua browserSub, body []byte) []byte {
  132. t.Helper()
  133. if len(body) < 16+4+1+65+17 {
  134. t.Fatalf("cuerpo cifrado demasiado corto: %d B", len(body))
  135. }
  136. salt := body[:16]
  137. rs := binary.BigEndian.Uint32(body[16:20])
  138. idlen := int(body[20])
  139. asPub := body[21 : 21+idlen]
  140. ciphertext := body[21+idlen:]
  141. if rs < uint32(len(ciphertext)) {
  142. t.Fatalf("record size incoherente: rs=%d ct=%d", rs, len(ciphertext))
  143. }
  144. curve := elliptic.P256()
  145. x, y := elliptic.Unmarshal(curve, asPub)
  146. if x == nil {
  147. t.Fatal("clave efímera del servidor no es un punto válido")
  148. }
  149. sx, _ := curve.ScalarMult(x, y, ua.priv)
  150. secret := make([]byte, 32)
  151. sx.FillBytes(secret)
  152. read := func(prkSecret, hkdfSalt, info []byte, n int) []byte {
  153. out := make([]byte, n)
  154. if _, err := io.ReadFull(hkdf.New(sha256.New, prkSecret, hkdfSalt, info), out); err != nil {
  155. t.Fatalf("hkdf: %v", err)
  156. }
  157. return out
  158. }
  159. info := append(append([]byte("WebPush: info\x00"), ua.pub...), asPub...)
  160. ikm := read(secret, ua.auth, info, 32)
  161. cek := read(ikm, salt, []byte("Content-Encoding: aes128gcm\x00"), 16)
  162. nonce := read(ikm, salt, []byte("Content-Encoding: nonce\x00"), 12)
  163. block, err := aes.NewCipher(cek)
  164. if err != nil {
  165. t.Fatalf("aes: %v", err)
  166. }
  167. gcm, err := cipher.NewGCM(block)
  168. if err != nil {
  169. t.Fatalf("gcm: %v", err)
  170. }
  171. plain, err := gcm.Open(nil, nonce, ciphertext, nil)
  172. if err != nil {
  173. t.Fatalf("descifrado GCM (¿claves mal derivadas?): %v", err)
  174. }
  175. // Quitar padding: ceros finales + delimitador 0x02 (registro final).
  176. i := len(plain) - 1
  177. for i >= 0 && plain[i] == 0 {
  178. i--
  179. }
  180. if i < 0 || plain[i] != 0x02 {
  181. t.Fatalf("delimitador 0x02 no encontrado (plain=%d B)", len(plain))
  182. }
  183. return plain[:i]
  184. }
  185. func testEvent() alerts.AlertEvent {
  186. return alerts.AlertEvent{
  187. ID: "alert-test-1",
  188. Category: alerts.CatRouter,
  189. Urgent: true,
  190. Severity: "critical",
  191. Title: "Router sin respuesta",
  192. Description: "Sin respuesta de 192.168.8.1",
  193. Hint: "Revisa la alimentación del router",
  194. Type: "router-down",
  195. Vars: map[string]string{"router": "192.168.8.1"},
  196. }
  197. }
  198. func newNotifier(t *testing.T, d *db.DB) *push.Notifier {
  199. t.Helper()
  200. pub, priv, err := push.EnsureVAPIDKeys(d)
  201. if err != nil {
  202. t.Fatalf("vapid: %v", err)
  203. }
  204. n := push.NewNotifier(d, pub, priv)
  205. t.Cleanup(n.Close)
  206. return n
  207. }
  208. // El Notifier envía un POST cifrado aes128gcm con cabecera VAPID al endpoint
  209. // suscrito, y el payload descifrado cumple el contrato del SW.
  210. func TestNotifierSendsEncryptedPayload(t *testing.T) {
  211. d, _ := openDB(t)
  212. pub, _, _ := push.EnsureVAPIDKeys(d)
  213. ua := newBrowserSub(t)
  214. got := make(chan capturedPush, 1)
  215. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  216. body, _ := io.ReadAll(r.Body)
  217. got <- capturedPush{method: r.Method, header: r.Header.Clone(), body: body}
  218. w.WriteHeader(http.StatusCreated)
  219. }))
  220. defer srv.Close()
  221. if _, err := push.UpsertSubscription(d, push.Subscription{
  222. Endpoint: srv.URL, Auth: ua.authB, P256dh: ua.pubB,
  223. }); err != nil {
  224. t.Fatalf("upsert: %v", err)
  225. }
  226. n := newNotifier(t, d)
  227. n.Notify(testEvent())
  228. var req capturedPush
  229. select {
  230. case req = <-got:
  231. case <-time.After(15 * time.Second):
  232. t.Fatal("el push service simulado no recibió nada en 15 s")
  233. }
  234. if req.method != http.MethodPost {
  235. t.Fatalf("método: %s, esperaba POST", req.method)
  236. }
  237. if enc := req.header.Get("Content-Encoding"); enc != "aes128gcm" {
  238. t.Fatalf("Content-Encoding: %q", enc)
  239. }
  240. if ttl := req.header.Get("TTL"); ttl != "3600" {
  241. t.Fatalf("TTL: %q", ttl)
  242. }
  243. authz := req.header.Get("Authorization")
  244. if !strings.HasPrefix(authz, "vapid t=") || !strings.Contains(authz, ", k=") {
  245. t.Fatalf("Authorization VAPID: %q", authz)
  246. }
  247. if !strings.Contains(authz, ", k="+pub) {
  248. t.Fatal("la cabecera VAPID no lleva la clave pública servida en /api/push/vapid-key")
  249. }
  250. plain := decryptAES128GCM(t, ua, req.body)
  251. var p struct {
  252. Title string `json:"title"`
  253. Body string `json:"body"`
  254. Type string `json:"type"`
  255. Vars map[string]string `json:"vars"`
  256. Category string `json:"category"`
  257. Severity string `json:"severity"`
  258. URL string `json:"url"`
  259. Tag string `json:"tag"`
  260. Hint string `json:"hint"`
  261. }
  262. if err := json.Unmarshal(plain, &p); err != nil {
  263. t.Fatalf("payload no es JSON: %v (%q)", err, plain)
  264. }
  265. if p.Title != "Router sin respuesta" || p.Body != "Sin respuesta de 192.168.8.1" ||
  266. p.Category != "router" || p.Severity != "critical" || p.URL != "/alerts" || p.Tag != "alert-test-1" {
  267. t.Fatalf("payload: %+v", p)
  268. }
  269. if p.Hint != "Revisa la alimentación del router" {
  270. t.Fatalf("payload hint: %q", p.Hint)
  271. }
  272. // #689: el slug y las vars viajan para que el SW pueda traducir el push.
  273. if p.Type != "router-down" || p.Vars["router"] != "192.168.8.1" {
  274. t.Fatalf("payload type/vars: type=%q vars=%v", p.Type, p.Vars)
  275. }
  276. }
  277. // Un push service que responde 410 (suscripción expirada) provoca la purga
  278. // de la fila; el resto de suscripciones se conserva.
  279. func TestNotifierPurgesGoneSubscription(t *testing.T) {
  280. d, _ := openDB(t)
  281. ua := newBrowserSub(t)
  282. got := make(chan struct{}, 2)
  283. dead := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  284. got <- struct{}{}
  285. w.WriteHeader(http.StatusGone)
  286. }))
  287. defer dead.Close()
  288. alive := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  289. got <- struct{}{}
  290. w.WriteHeader(http.StatusCreated)
  291. }))
  292. defer alive.Close()
  293. for _, ep := range []string{dead.URL, alive.URL} {
  294. if _, err := push.UpsertSubscription(d, push.Subscription{Endpoint: ep, Auth: ua.authB, P256dh: ua.pubB}); err != nil {
  295. t.Fatalf("upsert: %v", err)
  296. }
  297. }
  298. n := newNotifier(t, d)
  299. n.Notify(testEvent())
  300. for i := 0; i < 2; i++ {
  301. select {
  302. case <-got:
  303. case <-time.After(15 * time.Second):
  304. t.Fatalf("solo %d/2 envíos recibidos", i)
  305. }
  306. }
  307. n.Close() // drena el worker: la purga ya ocurrió
  308. subs, err := push.ListSubscriptions(d)
  309. if err != nil {
  310. t.Fatalf("list: %v", err)
  311. }
  312. if len(subs) != 1 || subs[0].Endpoint != alive.URL {
  313. t.Fatalf("tras purga: %+v", subs)
  314. }
  315. }
  316. // TestNotifierCloseConNotifyConcurrentesNoPanic reproduce el bug #202:
  317. // Close() cerraba el canal de la cola y un Notify concurrente podía elegir
  318. // la rama de envío tras el close → panic "send on closed channel".
  319. func TestNotifierCloseConNotifyConcurrentesNoPanic(t *testing.T) {
  320. d, _ := openDB(t)
  321. pub, _, _ := push.EnsureVAPIDKeys(d)
  322. n := newNotifier(t, d)
  323. _ = pub
  324. done := make(chan struct{})
  325. var wg sync.WaitGroup
  326. for i := 0; i < 8; i++ {
  327. wg.Add(1)
  328. go func() {
  329. defer wg.Done()
  330. for {
  331. select {
  332. case <-done:
  333. return
  334. default:
  335. n.Notify(testEvent())
  336. }
  337. }
  338. }()
  339. }
  340. time.Sleep(5 * time.Millisecond)
  341. n.Close()
  342. close(done)
  343. wg.Wait()
  344. }