server_webpush_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. //go:build !nowebpush
  2. package server
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "github.com/stretchr/testify/require"
  7. "heckel.io/ntfy/v2/user"
  8. "heckel.io/ntfy/v2/util"
  9. "io"
  10. "net/http"
  11. "net/http/httptest"
  12. "net/netip"
  13. "strings"
  14. "sync/atomic"
  15. "testing"
  16. "time"
  17. )
  18. const (
  19. testWebPushEndpoint = "https://updates.push.services.mozilla.com/wpush/v1/AAABBCCCDDEEEFFF"
  20. )
  21. func TestServer_WebPush_Disabled(t *testing.T) {
  22. s := newTestServer(t, newTestConfig(t))
  23. response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, testWebPushEndpoint), nil)
  24. require.Equal(t, 404, response.Code)
  25. }
  26. func TestServer_WebPush_TopicAdd(t *testing.T) {
  27. s := newTestServer(t, newTestConfigWithWebPush(t))
  28. response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, testWebPushEndpoint), nil)
  29. require.Equal(t, 200, response.Code)
  30. require.Equal(t, `{"success":true}`+"\n", response.Body.String())
  31. subs, err := s.webPush.SubscriptionsForTopic("test-topic")
  32. require.Nil(t, err)
  33. require.Len(t, subs, 1)
  34. require.Equal(t, subs[0].Endpoint, testWebPushEndpoint)
  35. require.Equal(t, subs[0].P256dh, "p256dh-key")
  36. require.Equal(t, subs[0].Auth, "auth-key")
  37. require.Equal(t, subs[0].UserID, "")
  38. }
  39. func TestServer_WebPush_TopicAdd_InvalidEndpoint(t *testing.T) {
  40. s := newTestServer(t, newTestConfigWithWebPush(t))
  41. response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, "https://ddos-target.example.com/webpush"), nil)
  42. require.Equal(t, 400, response.Code)
  43. require.Equal(t, `{"code":40039,"http":400,"error":"invalid request: web push endpoint unknown"}`+"\n", response.Body.String())
  44. }
  45. func TestServer_WebPush_TopicAdd_TooManyTopics(t *testing.T) {
  46. s := newTestServer(t, newTestConfigWithWebPush(t))
  47. topicList := make([]string, 51)
  48. for i := range topicList {
  49. topicList[i] = util.RandomString(5)
  50. }
  51. response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, topicList, testWebPushEndpoint), nil)
  52. require.Equal(t, 400, response.Code)
  53. require.Equal(t, `{"code":40040,"http":400,"error":"invalid request: too many web push topic subscriptions"}`+"\n", response.Body.String())
  54. }
  55. func TestServer_WebPush_TopicUnsubscribe(t *testing.T) {
  56. s := newTestServer(t, newTestConfigWithWebPush(t))
  57. addSubscription(t, s, testWebPushEndpoint, "test-topic")
  58. requireSubscriptionCount(t, s, "test-topic", 1)
  59. response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{}, testWebPushEndpoint), nil)
  60. require.Equal(t, 200, response.Code)
  61. require.Equal(t, `{"success":true}`+"\n", response.Body.String())
  62. requireSubscriptionCount(t, s, "test-topic", 0)
  63. }
  64. func TestServer_WebPush_Delete(t *testing.T) {
  65. s := newTestServer(t, newTestConfigWithWebPush(t))
  66. addSubscription(t, s, testWebPushEndpoint, "test-topic")
  67. requireSubscriptionCount(t, s, "test-topic", 1)
  68. response := request(t, s, "DELETE", "/v1/webpush", fmt.Sprintf(`{"endpoint":"%s"}`, testWebPushEndpoint), nil)
  69. require.Equal(t, 200, response.Code)
  70. require.Equal(t, `{"success":true}`+"\n", response.Body.String())
  71. requireSubscriptionCount(t, s, "test-topic", 0)
  72. }
  73. func TestServer_WebPush_TopicSubscribeProtected_Allowed(t *testing.T) {
  74. config := configureAuth(t, newTestConfigWithWebPush(t))
  75. config.AuthDefault = user.PermissionDenyAll
  76. s := newTestServer(t, config)
  77. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser, false))
  78. require.Nil(t, s.userManager.AllowAccess("ben", "test-topic", user.PermissionReadWrite))
  79. response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, testWebPushEndpoint), map[string]string{
  80. "Authorization": util.BasicAuth("ben", "ben"),
  81. })
  82. require.Equal(t, 200, response.Code)
  83. require.Equal(t, `{"success":true}`+"\n", response.Body.String())
  84. subs, err := s.webPush.SubscriptionsForTopic("test-topic")
  85. require.Nil(t, err)
  86. require.Len(t, subs, 1)
  87. require.True(t, strings.HasPrefix(subs[0].UserID, "u_"))
  88. }
  89. func TestServer_WebPush_TopicSubscribeProtected_Denied(t *testing.T) {
  90. config := configureAuth(t, newTestConfigWithWebPush(t))
  91. config.AuthDefault = user.PermissionDenyAll
  92. s := newTestServer(t, config)
  93. response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, testWebPushEndpoint), nil)
  94. require.Equal(t, 403, response.Code)
  95. requireSubscriptionCount(t, s, "test-topic", 0)
  96. }
  97. func TestServer_WebPush_DeleteAccountUnsubscribe(t *testing.T) {
  98. config := configureAuth(t, newTestConfigWithWebPush(t))
  99. s := newTestServer(t, config)
  100. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser, false))
  101. require.Nil(t, s.userManager.AllowAccess("ben", "test-topic", user.PermissionReadWrite))
  102. response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, testWebPushEndpoint), map[string]string{
  103. "Authorization": util.BasicAuth("ben", "ben"),
  104. })
  105. require.Equal(t, 200, response.Code)
  106. require.Equal(t, `{"success":true}`+"\n", response.Body.String())
  107. requireSubscriptionCount(t, s, "test-topic", 1)
  108. request(t, s, "DELETE", "/v1/account", `{"password":"ben"}`, map[string]string{
  109. "Authorization": util.BasicAuth("ben", "ben"),
  110. })
  111. // should've been deleted with the account
  112. requireSubscriptionCount(t, s, "test-topic", 0)
  113. }
  114. func TestServer_WebPush_Publish(t *testing.T) {
  115. s := newTestServer(t, newTestConfigWithWebPush(t))
  116. var received atomic.Bool
  117. pushService := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  118. _, err := io.ReadAll(r.Body)
  119. require.Nil(t, err)
  120. require.Equal(t, "/push-receive", r.URL.Path)
  121. require.Equal(t, "high", r.Header.Get("Urgency"))
  122. require.Equal(t, "", r.Header.Get("Topic"))
  123. received.Store(true)
  124. }))
  125. defer pushService.Close()
  126. addSubscription(t, s, pushService.URL+"/push-receive", "test-topic")
  127. request(t, s, "POST", "/test-topic", "web push test", nil)
  128. waitFor(t, func() bool {
  129. return received.Load()
  130. })
  131. }
  132. func TestServer_WebPush_Publish_RemoveOnError(t *testing.T) {
  133. s := newTestServer(t, newTestConfigWithWebPush(t))
  134. var received atomic.Bool
  135. pushService := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  136. _, err := io.ReadAll(r.Body)
  137. require.Nil(t, err)
  138. w.WriteHeader(http.StatusGone)
  139. received.Store(true)
  140. }))
  141. defer pushService.Close()
  142. addSubscription(t, s, pushService.URL+"/push-receive", "test-topic", "test-topic-abc")
  143. requireSubscriptionCount(t, s, "test-topic", 1)
  144. requireSubscriptionCount(t, s, "test-topic-abc", 1)
  145. request(t, s, "POST", "/test-topic", "web push test", nil)
  146. waitFor(t, func() bool {
  147. return received.Load()
  148. })
  149. // Receiving the 410 should've caused the publisher to expire all subscriptions on the endpoint
  150. requireSubscriptionCount(t, s, "test-topic", 0)
  151. requireSubscriptionCount(t, s, "test-topic-abc", 0)
  152. }
  153. func TestServer_WebPush_Expiry(t *testing.T) {
  154. s := newTestServer(t, newTestConfigWithWebPush(t))
  155. var received atomic.Bool
  156. pushService := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  157. _, err := io.ReadAll(r.Body)
  158. require.Nil(t, err)
  159. w.WriteHeader(200)
  160. w.Write([]byte(``))
  161. received.Store(true)
  162. }))
  163. defer pushService.Close()
  164. addSubscription(t, s, pushService.URL+"/push-receive", "test-topic")
  165. requireSubscriptionCount(t, s, "test-topic", 1)
  166. _, err := s.webPush.db.Exec("UPDATE subscription SET updated_at = ?", time.Now().Add(-55*24*time.Hour).Unix())
  167. require.Nil(t, err)
  168. s.pruneAndNotifyWebPushSubscriptions()
  169. requireSubscriptionCount(t, s, "test-topic", 1)
  170. waitFor(t, func() bool {
  171. return received.Load()
  172. })
  173. _, err = s.webPush.db.Exec("UPDATE subscription SET updated_at = ?", time.Now().Add(-60*24*time.Hour).Unix())
  174. require.Nil(t, err)
  175. s.pruneAndNotifyWebPushSubscriptions()
  176. waitFor(t, func() bool {
  177. subs, err := s.webPush.SubscriptionsForTopic("test-topic")
  178. require.Nil(t, err)
  179. return len(subs) == 0
  180. })
  181. }
  182. func payloadForTopics(t *testing.T, topics []string, endpoint string) string {
  183. topicsJSON, err := json.Marshal(topics)
  184. require.Nil(t, err)
  185. return fmt.Sprintf(`{
  186. "topics": %s,
  187. "endpoint": "%s",
  188. "p256dh": "p256dh-key",
  189. "auth": "auth-key"
  190. }`, topicsJSON, endpoint)
  191. }
  192. func addSubscription(t *testing.T, s *Server, endpoint string, topics ...string) {
  193. require.Nil(t, s.webPush.UpsertSubscription(endpoint, "kSC3T8aN1JCQxxPdrFLrZg", "BMKKbxdUU_xLS7G1Wh5AN8PvWOjCzkCuKZYb8apcqYrDxjOF_2piggBnoJLQYx9IeSD70fNuwawI3e9Y8m3S3PE", "u_123", netip.MustParseAddr("1.2.3.4"), topics)) // Test auth and p256dh
  194. }
  195. func requireSubscriptionCount(t *testing.T, s *Server, topic string, expectedLength int) {
  196. subs, err := s.webPush.SubscriptionsForTopic(topic)
  197. require.Nil(t, err)
  198. require.Len(t, subs, expectedLength)
  199. }