push_test.go 9.3 KB

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