push_test_1973_test.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // push_test_1973_test.go - contrato de POST /api/push/test (#1973): solo la
  2. // suscripcion del propio usuario, una prueba cada ventana, y el resultado del
  3. // push service tal cual (incluida la suscripcion caducada).
  4. package httpapi_test
  5. import (
  6. "net/http"
  7. "testing"
  8. "time"
  9. "github.com/gnacho/netpulse/server-go/internal/auth"
  10. "github.com/gnacho/netpulse/server-go/internal/config"
  11. "github.com/gnacho/netpulse/server-go/internal/db"
  12. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  13. "github.com/gnacho/netpulse/server-go/internal/push"
  14. "github.com/gnacho/netpulse/server-go/internal/sse"
  15. "net/http/httptest"
  16. "github.com/gnacho/netpulse/server-go/internal/adapters"
  17. )
  18. type fakePush struct {
  19. res push.TestResult
  20. calls int
  21. last push.Subscription
  22. }
  23. func (f *fakePush) SendTest(s push.Subscription) push.TestResult {
  24. f.calls++
  25. f.last = s
  26. return f.res
  27. }
  28. // makePushTestServer: handler real con un PushTester falso y dos usuarios con
  29. // una suscripcion cada uno.
  30. func makePushTestServer(t *testing.T, fake *fakePush) *testServer {
  31. t.Helper()
  32. auth.SetTrustProxy(true)
  33. t.Cleanup(func() { auth.SetTrustProxy(false) })
  34. dataDir := t.TempDir()
  35. cfg, err := config.Load(map[string]string{
  36. "AUTH_USER": "admin", "AUTH_PASS": "test123456",
  37. "DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
  38. }, dataDir)
  39. if err != nil {
  40. t.Fatalf("config: %v", err)
  41. }
  42. d, err := db.Open(dataDir)
  43. if err != nil {
  44. t.Fatalf("db: %v", err)
  45. }
  46. secret, err := auth.EnsureSessionSecret(d, cfg)
  47. if err != nil {
  48. t.Fatalf("secret: %v", err)
  49. }
  50. if err := auth.EnsureUsers(d, cfg); err != nil {
  51. t.Fatalf("users: %v", err)
  52. }
  53. hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
  54. var deps httpapi.PushTester
  55. if fake != nil {
  56. deps = fake
  57. }
  58. handler := httpapi.NewHandler(httpapi.Deps{
  59. Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
  60. Started: time.Now(), Push: deps,
  61. })
  62. srv := httptest.NewServer(handler)
  63. ts := &testServer{Server: srv, db: d, secret: secret}
  64. t.Cleanup(func() {
  65. srv.Close()
  66. d.Close()
  67. })
  68. return ts
  69. }
  70. func adminID(t *testing.T, d *db.DB) int64 {
  71. t.Helper()
  72. var id int64
  73. if err := d.QueryRow("SELECT id FROM users WHERE username = 'admin'").Scan(&id); err != nil {
  74. t.Fatalf("admin id: %v", err)
  75. }
  76. return id
  77. }
  78. func seedSubscription(t *testing.T, d *db.DB, endpoint string, userID int64) {
  79. t.Helper()
  80. if _, err := d.Exec(`INSERT INTO push_subscriptions (endpoint, keys_auth, keys_p256dh, user_agent, created_at, user_id, language)
  81. VALUES (?, 'auth', 'p256dh', 'test', ?, ?, 'es')`, endpoint, db.NowMS(), userID); err != nil {
  82. t.Fatalf("seed subscription: %v", err)
  83. }
  84. }
  85. func TestPushTestSendsToOwnSubscription(t *testing.T) {
  86. fake := &fakePush{res: push.TestResult{Status: http.StatusCreated}}
  87. ts := makePushTestServer(t, fake)
  88. cookie := adminCookie(t, ts)
  89. me := adminID(t, ts.db)
  90. seedSubscription(t, ts.db, "https://push.example/own", me)
  91. res := postJSON(t, ts.URL, "/api/push/test", `{"endpoint":"https://push.example/own"}`, cookie)
  92. if res.StatusCode != http.StatusOK {
  93. t.Fatalf("status = %d, esperaba 200", res.StatusCode)
  94. }
  95. body := readJSON(t, res)
  96. if ok, _ := body["ok"].(bool); !ok {
  97. t.Fatalf("body = %+v", body)
  98. }
  99. if fake.calls != 1 || fake.last.Endpoint != "https://push.example/own" {
  100. t.Fatalf("fake: calls=%d endpoint=%q", fake.calls, fake.last.Endpoint)
  101. }
  102. }
  103. func TestPushTestRejectsForeignEndpoint(t *testing.T) {
  104. fake := &fakePush{res: push.TestResult{Status: http.StatusCreated}}
  105. ts := makePushTestServer(t, fake)
  106. cookie := adminCookie(t, ts)
  107. seedSubscription(t, ts.db, "https://push.example/other", 9999)
  108. res := postJSON(t, ts.URL, "/api/push/test", `{"endpoint":"https://push.example/other"}`, cookie)
  109. if res.StatusCode != http.StatusNotFound {
  110. t.Fatalf("status = %d, esperaba 404", res.StatusCode)
  111. }
  112. if fake.calls != 0 {
  113. t.Fatalf("no debia enviarse nada: %d envios", fake.calls)
  114. }
  115. }
  116. func TestPushTestRateLimited(t *testing.T) {
  117. old := httpapi.PushTestCooldownForTests(20 * time.Millisecond)
  118. t.Cleanup(func() { httpapi.PushTestCooldownForTests(old) })
  119. fake := &fakePush{res: push.TestResult{Status: http.StatusCreated}}
  120. ts := makePushTestServer(t, fake)
  121. cookie := adminCookie(t, ts)
  122. me := adminID(t, ts.db)
  123. seedSubscription(t, ts.db, "https://push.example/own", me)
  124. first := postJSON(t, ts.URL, "/api/push/test", `{"endpoint":"https://push.example/own"}`, cookie)
  125. if first.StatusCode != http.StatusOK {
  126. t.Fatalf("primera: %d", first.StatusCode)
  127. }
  128. second := postJSON(t, ts.URL, "/api/push/test", `{"endpoint":"https://push.example/own"}`, cookie)
  129. if second.StatusCode != http.StatusTooManyRequests {
  130. t.Fatalf("segunda: %d, esperaba 429", second.StatusCode)
  131. }
  132. time.Sleep(30 * time.Millisecond)
  133. third := postJSON(t, ts.URL, "/api/push/test", `{"endpoint":"https://push.example/own"}`, cookie)
  134. if third.StatusCode != http.StatusOK {
  135. t.Fatalf("tercera tras la ventana: %d", third.StatusCode)
  136. }
  137. }
  138. func TestPushTestExpiredPurgesSubscription(t *testing.T) {
  139. fake := &fakePush{res: push.TestResult{Status: http.StatusGone, Expired: true, Reason: "gone"}}
  140. ts := makePushTestServer(t, fake)
  141. cookie := adminCookie(t, ts)
  142. me := adminID(t, ts.db)
  143. seedSubscription(t, ts.db, "https://push.example/dead", me)
  144. res := postJSON(t, ts.URL, "/api/push/test", `{"endpoint":"https://push.example/dead"}`, cookie)
  145. body := readJSON(t, res)
  146. if expired, _ := body["expired"].(bool); !expired {
  147. t.Fatalf("body = %+v", body)
  148. }
  149. var n int
  150. if err := ts.db.QueryRow("SELECT COUNT(*) FROM push_subscriptions WHERE endpoint = ?", "https://push.example/dead").Scan(&n); err != nil {
  151. t.Fatalf("query: %v", err)
  152. }
  153. if n != 0 {
  154. t.Fatalf("la suscripcion caducada sigue en la DB (%d filas)", n)
  155. }
  156. }
  157. func TestPushTestWithoutNotifier(t *testing.T) {
  158. ts := makePushTestServer(t, nil)
  159. cookie := adminCookie(t, ts)
  160. res := postJSON(t, ts.URL, "/api/push/test", `{"endpoint":"https://push.example/own"}`, cookie)
  161. if res.StatusCode != http.StatusServiceUnavailable {
  162. t.Fatalf("status = %d, esperaba 503", res.StatusCode)
  163. }
  164. }