push_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. }
  195. }
  196. func newNotifier(t *testing.T, d *db.DB) *push.Notifier {
  197. t.Helper()
  198. pub, priv, err := push.EnsureVAPIDKeys(d)
  199. if err != nil {
  200. t.Fatalf("vapid: %v", err)
  201. }
  202. n := push.NewNotifier(d, pub, priv)
  203. t.Cleanup(n.Close)
  204. return n
  205. }
  206. // El Notifier envía un POST cifrado aes128gcm con cabecera VAPID al endpoint
  207. // suscrito, y el payload descifrado cumple el contrato del SW.
  208. func TestNotifierSendsEncryptedPayload(t *testing.T) {
  209. d, _ := openDB(t)
  210. pub, _, _ := push.EnsureVAPIDKeys(d)
  211. ua := newBrowserSub(t)
  212. got := make(chan capturedPush, 1)
  213. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  214. body, _ := io.ReadAll(r.Body)
  215. got <- capturedPush{method: r.Method, header: r.Header.Clone(), body: body}
  216. w.WriteHeader(http.StatusCreated)
  217. }))
  218. defer srv.Close()
  219. if _, err := push.UpsertSubscription(d, push.Subscription{
  220. Endpoint: srv.URL, Auth: ua.authB, P256dh: ua.pubB,
  221. }); err != nil {
  222. t.Fatalf("upsert: %v", err)
  223. }
  224. n := newNotifier(t, d)
  225. n.Notify(testEvent())
  226. var req capturedPush
  227. select {
  228. case req = <-got:
  229. case <-time.After(15 * time.Second):
  230. t.Fatal("el push service simulado no recibió nada en 15 s")
  231. }
  232. if req.method != http.MethodPost {
  233. t.Fatalf("método: %s, esperaba POST", req.method)
  234. }
  235. if enc := req.header.Get("Content-Encoding"); enc != "aes128gcm" {
  236. t.Fatalf("Content-Encoding: %q", enc)
  237. }
  238. if ttl := req.header.Get("TTL"); ttl != "3600" {
  239. t.Fatalf("TTL: %q", ttl)
  240. }
  241. authz := req.header.Get("Authorization")
  242. if !strings.HasPrefix(authz, "vapid t=") || !strings.Contains(authz, ", k=") {
  243. t.Fatalf("Authorization VAPID: %q", authz)
  244. }
  245. if !strings.Contains(authz, ", k="+pub) {
  246. t.Fatal("la cabecera VAPID no lleva la clave pública servida en /api/push/vapid-key")
  247. }
  248. plain := decryptAES128GCM(t, ua, req.body)
  249. var p struct {
  250. Title string `json:"title"`
  251. Body string `json:"body"`
  252. Category string `json:"category"`
  253. Severity string `json:"severity"`
  254. URL string `json:"url"`
  255. Tag string `json:"tag"`
  256. Hint string `json:"hint"`
  257. }
  258. if err := json.Unmarshal(plain, &p); err != nil {
  259. t.Fatalf("payload no es JSON: %v (%q)", err, plain)
  260. }
  261. if p.Title != "Router sin respuesta" || p.Body != "Sin respuesta de 192.168.8.1" ||
  262. p.Category != "router" || p.Severity != "critical" || p.URL != "/alerts" || p.Tag != "alert-test-1" {
  263. t.Fatalf("payload: %+v", p)
  264. }
  265. if p.Hint != "Revisa la alimentación del router" {
  266. t.Fatalf("payload hint: %q", p.Hint)
  267. }
  268. }
  269. // Un push service que responde 410 (suscripción expirada) provoca la purga
  270. // de la fila; el resto de suscripciones se conserva.
  271. func TestNotifierPurgesGoneSubscription(t *testing.T) {
  272. d, _ := openDB(t)
  273. ua := newBrowserSub(t)
  274. got := make(chan struct{}, 2)
  275. dead := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  276. got <- struct{}{}
  277. w.WriteHeader(http.StatusGone)
  278. }))
  279. defer dead.Close()
  280. alive := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  281. got <- struct{}{}
  282. w.WriteHeader(http.StatusCreated)
  283. }))
  284. defer alive.Close()
  285. for _, ep := range []string{dead.URL, alive.URL} {
  286. if _, err := push.UpsertSubscription(d, push.Subscription{Endpoint: ep, Auth: ua.authB, P256dh: ua.pubB}); err != nil {
  287. t.Fatalf("upsert: %v", err)
  288. }
  289. }
  290. n := newNotifier(t, d)
  291. n.Notify(testEvent())
  292. for i := 0; i < 2; i++ {
  293. select {
  294. case <-got:
  295. case <-time.After(15 * time.Second):
  296. t.Fatalf("solo %d/2 envíos recibidos", i)
  297. }
  298. }
  299. n.Close() // drena el worker: la purga ya ocurrió
  300. subs, err := push.ListSubscriptions(d)
  301. if err != nil {
  302. t.Fatalf("list: %v", err)
  303. }
  304. if len(subs) != 1 || subs[0].Endpoint != alive.URL {
  305. t.Fatalf("tras purga: %+v", subs)
  306. }
  307. }
  308. // TestNotifierCloseConNotifyConcurrentesNoPanic reproduce el bug #202:
  309. // Close() cerraba el canal de la cola y un Notify concurrente podía elegir
  310. // la rama de envío tras el close → panic "send on closed channel".
  311. func TestNotifierCloseConNotifyConcurrentesNoPanic(t *testing.T) {
  312. d, _ := openDB(t)
  313. pub, _, _ := push.EnsureVAPIDKeys(d)
  314. n := newNotifier(t, d)
  315. _ = pub
  316. done := make(chan struct{})
  317. var wg sync.WaitGroup
  318. for i := 0; i < 8; i++ {
  319. wg.Add(1)
  320. go func() {
  321. defer wg.Done()
  322. for {
  323. select {
  324. case <-done:
  325. return
  326. default:
  327. n.Notify(testEvent())
  328. }
  329. }
  330. }()
  331. }
  332. time.Sleep(5 * time.Millisecond)
  333. n.Close()
  334. close(done)
  335. wg.Wait()
  336. }