Debian Codegraph @

server/server_webpush_test.go

raw
1 //go:build !nowebpush
2
3 package server
4
5 import (
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "net/http/httptest"
11 "net/netip"
12 "path/filepath"
13 "strings"
14 "sync/atomic"
15 "testing"
16 "time"
17
18 "github.com/SherClockHolmes/webpush-go"
19 "github.com/stretchr/testify/require"
20 "heckel.io/ntfy/v2/user"
21 "heckel.io/ntfy/v2/util"
22 )
23
24 const (
25 testWebPushEndpoint = "https://updates.push.services.mozilla.com/wpush/v1/AAABBCCCDDEEEFFF"
26 )
27
28 func TestServer_WebPush_Enabled(t *testing.T) {
29 forEachBackend(t, func(t *testing.T, databaseURL string) {
30 conf := newTestConfig(t, databaseURL)
31 conf.WebRoot = "" // Disable web app
32 s := newTestServer(t, conf)
33
34 rr := request(t, s, "GET", "/manifest.webmanifest", "", nil)
35 require.Equal(t, 404, rr.Code)
36
37 conf2 := newTestConfig(t, databaseURL)
38 s2 := newTestServer(t, conf2)
39
40 rr = request(t, s2, "GET", "/manifest.webmanifest", "", nil)
41 require.Equal(t, 404, rr.Code)
42
43 conf3 := newTestConfigWithWebPush(t, databaseURL)
44 s3 := newTestServer(t, conf3)
45
46 rr = request(t, s3, "GET", "/manifest.webmanifest", "", nil)
47 require.Equal(t, 200, rr.Code)
48 require.Equal(t, "application/manifest+json", rr.Header().Get("Content-Type"))
49
50 })
51 }
52 func TestServer_WebPush_Disabled(t *testing.T) {
53 forEachBackend(t, func(t *testing.T, databaseURL string) {
54 s := newTestServer(t, newTestConfig(t, databaseURL))
55
56 response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, testWebPushEndpoint), nil)
57 require.Equal(t, 404, response.Code)
58 })
59 }
60
61 func TestServer_WebPush_TopicAdd(t *testing.T) {
62 forEachBackend(t, func(t *testing.T, databaseURL string) {
63 s := newTestServer(t, newTestConfigWithWebPush(t, databaseURL))
64
65 response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, testWebPushEndpoint), nil)
66 require.Equal(t, 200, response.Code)
67 require.Equal(t, `{"success":true}`+"\n", response.Body.String())
68
69 subs, err := s.webPush.SubscriptionsForTopic("test-topic")
70 require.Nil(t, err)
71
72 require.Len(t, subs, 1)
73 require.Equal(t, subs[0].Endpoint, testWebPushEndpoint)
74 require.Equal(t, subs[0].P256dh, "p256dh-key")
75 require.Equal(t, subs[0].Auth, "auth-key")
76 require.Equal(t, subs[0].UserID, "")
77 })
78 }
79
80 func TestServer_WebPush_TopicAdd_InvalidEndpoint(t *testing.T) {
81 forEachBackend(t, func(t *testing.T, databaseURL string) {
82 s := newTestServer(t, newTestConfigWithWebPush(t, databaseURL))
83
84 response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, "https://ddos-target.example.com/webpush"), nil)
85 require.Equal(t, 400, response.Code)
86 require.Equal(t, `{"code":40039,"http":400,"error":"invalid request: web push endpoint unknown"}`+"\n", response.Body.String())
87 })
88 }
89
90 func TestServer_WebPush_EndpointRegex(t *testing.T) {
91 // Synthetic endpoint samples representing each supported push service host shape.
92 allowed := []string{
93 // Google FCM (legacy send, webpush, preprod webpush)
94 "https://fcm.googleapis.com/fcm/send/FAKETOKEN:APA91b-placeholder-not-a-real-token",
95 "https://fcm.googleapis.com/wp/FAKETOKEN:APA91b-placeholder-not-a-real-token",
96 "https://fcm.googleapis.com/preprod/wp/FAKETOKEN:APA91b-placeholder-not-a-real-token",
97 "https://jmt17.google.com/fcm/send/FAKETOKEN:APA91b-placeholder-not-a-real-token",
98 // Mozilla autopush (v1 legacy, v2 current, plus AWS-hosted infra)
99 "https://updates.push.services.mozilla.com/wpush/v1/placeholder-not-a-real-token",
100 "https://updates.push.services.mozilla.com/wpush/v2/placeholder-not-a-real-token",
101 "https://autopush.mozaws.net/wpush/v1/placeholder-not-a-real-token",
102 // Apple Web Push
103 "https://web.push.apple.com/placeholder-not-a-real-token",
104 // Microsoft WNS: instance-specific "wns2-<region>" prefix is wildcarded
105 "https://wns2-bn3p.notify.windows.com/w/?token=placeholder",
106 "https://wns2-ch1p.notify.windows.com/w/?token=placeholder",
107 "https://wns2-par02p.notify.windows.com/w/?token=placeholder",
108 "https://wns2-pn1p.notify.windows.com/w/?token=placeholder",
109 "https://wns2-am3p.notify.windows.com/w/?token=placeholder",
110 }
111 denied := []string{
112 // HTTP (not HTTPS)
113 "http://fcm.googleapis.com/fcm/send/abc",
114 // Unrelated host
115 "https://attacker.example.com/webpush",
116 // GHSA-w9hq-5jg7-q4j7 bypass: allowed host embedded in path
117 "https://attacker.com/x.google.com/push",
118 "https://attacker.example.com/fcm.googleapis.com/fcm/send/abc",
119 "https://evil.test/web.push.apple.com/3/device/abc",
120 "https://ntfytest.requestcatcher.com/path.google.com/push",
121 "https://ntfytest.requestcatcher.com/a.google.com/toto",
122 "https://ntfytest.requestcatcher.com/bypass.google.com/test",
123 "https://webhook.site/86e94e2e-2af4-4a31-a80b-e2f335cc6495/path.google.com/push",
124 "https://webhook.site/86e94e2e-2af4-4a31-a80b-e2f335cc6495/bypass.google.com/",
125 // Allowed host as a prefix of a different host (no separating slash)
126 "https://fcm.googleapis.com.attacker.com/fcm/send/abc",
127 "https://web.push.apple.com.evil.test/tok",
128 // Allowed host as a suffix of a different host (no separating dot)
129 "https://evilgoogle.com/",
130 "https://notapple.com/",
131 // Credentials/userinfo in the URL pointing at a different host
132 "https://[email protected]/fcm/send/abc",
133 // Previously allowed by the wildcard allowlist but not actually used by Web Push
134 "https://api.push.apple.com/3/device/abc",
135 "https://android.googleapis.com/send/xyz",
136 "https://login.microsoft.com/anything",
137 // Bare notify.windows.com with no subdomain label
138 "https://notify.windows.com/w/?token=abc",
139 }
140 for _, endpoint := range allowed {
141 require.Truef(t, webPushEndpointAllowed(endpoint), "expected endpoint to be allowed: %s", endpoint)
142 }
143 for _, endpoint := range denied {
144 require.Falsef(t, webPushEndpointAllowed(endpoint), "expected endpoint to be denied: %s", endpoint)
145 }
146 }
147
148 func TestServer_WebPush_TopicAdd_BypassAttempt(t *testing.T) {
149 // Regression test for GHSA-w9hq-5jg7-q4j7: the allow-list regex previously had no
150 // end anchor, so a URL like https://attacker.example.com/x.google.com/... passed
151 // validation and caused the server to deliver push payloads to attacker-controlled
152 // endpoints (SSRF + message exfiltration via attacker-supplied p256dh key).
153 forEachBackend(t, func(t *testing.T, databaseURL string) {
154 s := newTestServer(t, newTestConfigWithWebPush(t, databaseURL))
155
156 response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, "https://attacker.example.com/x.google.com/push"), nil)
157 require.Equal(t, 400, response.Code)
158 require.Equal(t, `{"code":40039,"http":400,"error":"invalid request: web push endpoint unknown"}`+"\n", response.Body.String())
159 })
160 }
161
162 func TestServer_WebPush_TopicAdd_TooManyTopics(t *testing.T) {
163 forEachBackend(t, func(t *testing.T, databaseURL string) {
164 s := newTestServer(t, newTestConfigWithWebPush(t, databaseURL))
165
166 topicList := make([]string, 51)
167 for i := range topicList {
168 topicList[i] = util.RandomString(5)
169 }
170
171 response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, topicList, testWebPushEndpoint), nil)
172 require.Equal(t, 400, response.Code)
173 require.Equal(t, `{"code":40040,"http":400,"error":"invalid request: too many web push topic subscriptions"}`+"\n", response.Body.String())
174 })
175 }
176
177 func TestServer_WebPush_TopicUnsubscribe(t *testing.T) {
178 forEachBackend(t, func(t *testing.T, databaseURL string) {
179 s := newTestServer(t, newTestConfigWithWebPush(t, databaseURL))
180
181 addSubscription(t, s, testWebPushEndpoint, "test-topic")
182 requireSubscriptionCount(t, s, "test-topic", 1)
183
184 response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{}, testWebPushEndpoint), nil)
185 require.Equal(t, 200, response.Code)
186 require.Equal(t, `{"success":true}`+"\n", response.Body.String())
187
188 requireSubscriptionCount(t, s, "test-topic", 0)
189 })
190 }
191
192 func TestServer_WebPush_Delete(t *testing.T) {
193 forEachBackend(t, func(t *testing.T, databaseURL string) {
194 s := newTestServer(t, newTestConfigWithWebPush(t, databaseURL))
195
196 addSubscription(t, s, testWebPushEndpoint, "test-topic")
197 requireSubscriptionCount(t, s, "test-topic", 1)
198
199 response := request(t, s, "DELETE", "/v1/webpush", fmt.Sprintf(`{"endpoint":"%s"}`, testWebPushEndpoint), nil)
200 require.Equal(t, 200, response.Code)
201 require.Equal(t, `{"success":true}`+"\n", response.Body.String())
202
203 requireSubscriptionCount(t, s, "test-topic", 0)
204 })
205 }
206
207 func TestServer_WebPush_TopicSubscribeProtected_Allowed(t *testing.T) {
208 forEachBackend(t, func(t *testing.T, databaseURL string) {
209 config := configureAuth(t, newTestConfigWithWebPush(t, databaseURL))
210 config.AuthDefault = user.PermissionDenyAll
211 s := newTestServer(t, config)
212
213 require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser, false))
214 require.Nil(t, s.userManager.AllowAccess("ben", "test-topic", user.PermissionReadWrite))
215
216 response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, testWebPushEndpoint), map[string]string{
217 "Authorization": util.BasicAuth("ben", "ben"),
218 })
219 require.Equal(t, 200, response.Code)
220 require.Equal(t, `{"success":true}`+"\n", response.Body.String())
221
222 subs, err := s.webPush.SubscriptionsForTopic("test-topic")
223 require.Nil(t, err)
224 require.Len(t, subs, 1)
225 require.True(t, strings.HasPrefix(subs[0].UserID, "u_"))
226 })
227 }
228
229 func TestServer_WebPush_TopicSubscribeProtected_Denied(t *testing.T) {
230 forEachBackend(t, func(t *testing.T, databaseURL string) {
231 config := configureAuth(t, newTestConfigWithWebPush(t, databaseURL))
232 config.AuthDefault = user.PermissionDenyAll
233 s := newTestServer(t, config)
234
235 response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, testWebPushEndpoint), nil)
236 require.Equal(t, 403, response.Code)
237
238 requireSubscriptionCount(t, s, "test-topic", 0)
239 })
240 }
241
242 func TestServer_WebPush_DeleteAccountUnsubscribe(t *testing.T) {
243 forEachBackend(t, func(t *testing.T, databaseURL string) {
244 config := configureAuth(t, newTestConfigWithWebPush(t, databaseURL))
245 s := newTestServer(t, config)
246
247 require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser, false))
248 require.Nil(t, s.userManager.AllowAccess("ben", "test-topic", user.PermissionReadWrite))
249
250 response := request(t, s, "POST", "/v1/webpush", payloadForTopics(t, []string{"test-topic"}, testWebPushEndpoint), map[string]string{
251 "Authorization": util.BasicAuth("ben", "ben"),
252 })
253
254 require.Equal(t, 200, response.Code)
255 require.Equal(t, `{"success":true}`+"\n", response.Body.String())
256
257 requireSubscriptionCount(t, s, "test-topic", 1)
258
259 request(t, s, "DELETE", "/v1/account", `{"password":"ben"}`, map[string]string{
260 "Authorization": util.BasicAuth("ben", "ben"),
261 })
262 // should've been deleted with the account
263 requireSubscriptionCount(t, s, "test-topic", 0)
264 })
265 }
266
267 func TestServer_WebPush_Publish(t *testing.T) {
268 forEachBackend(t, func(t *testing.T, databaseURL string) {
269 s := newTestServer(t, newTestConfigWithWebPush(t, databaseURL))
270
271 var received atomic.Bool
272 pushService := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
273 _, err := io.ReadAll(r.Body)
274 require.Nil(t, err)
275 require.Equal(t, "/push-receive", r.URL.Path)
276 require.Equal(t, "high", r.Header.Get("Urgency"))
277 require.Equal(t, "", r.Header.Get("Topic"))
278 received.Store(true)
279 }))
280 defer pushService.Close()
281
282 addSubscription(t, s, pushService.URL+"/push-receive", "test-topic")
283 request(t, s, "POST", "/test-topic", "web push test", nil)
284
285 waitFor(t, func() bool {
286 return received.Load()
287 })
288 })
289 }
290
291 func TestServer_WebPush_Publish_RemoveOnError(t *testing.T) {
292 forEachBackend(t, func(t *testing.T, databaseURL string) {
293 s := newTestServer(t, newTestConfigWithWebPush(t, databaseURL))
294
295 var received atomic.Bool
296 pushService := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
297 _, err := io.ReadAll(r.Body)
298 require.Nil(t, err)
299 w.WriteHeader(http.StatusGone)
300 received.Store(true)
301 }))
302 defer pushService.Close()
303
304 addSubscription(t, s, pushService.URL+"/push-receive", "test-topic", "test-topic-abc")
305 requireSubscriptionCount(t, s, "test-topic", 1)
306 requireSubscriptionCount(t, s, "test-topic-abc", 1)
307
308 request(t, s, "POST", "/test-topic", "web push test", nil)
309
310 // Receiving the 410 should've caused the publisher to expire all subscriptions on the endpoint
311 waitFor(t, func() bool {
312 subs, err := s.webPush.SubscriptionsForTopic("test-topic")
313 require.Nil(t, err)
314 return len(subs) == 0
315 })
316 requireSubscriptionCount(t, s, "test-topic-abc", 0)
317 })
318 }
319
320 func TestServer_WebPush_Expiry(t *testing.T) {
321 forEachBackend(t, func(t *testing.T, databaseURL string) {
322 s := newTestServer(t, newTestConfigWithWebPush(t, databaseURL))
323
324 var received atomic.Bool
325
326 pushService := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
327 _, err := io.ReadAll(r.Body)
328 require.Nil(t, err)
329 w.WriteHeader(200)
330 w.Write([]byte(``))
331 received.Store(true)
332 }))
333 defer pushService.Close()
334
335 endpoint := pushService.URL + "/push-receive"
336 addSubscription(t, s, endpoint, "test-topic")
337 requireSubscriptionCount(t, s, "test-topic", 1)
338
339 require.Nil(t, s.webPush.SetSubscriptionUpdatedAt(endpoint, time.Now().Add(-55*24*time.Hour).Unix()))
340
341 s.pruneAndNotifyWebPushSubscriptions()
342 requireSubscriptionCount(t, s, "test-topic", 1)
343
344 waitFor(t, func() bool {
345 return received.Load()
346 })
347
348 require.Nil(t, s.webPush.SetSubscriptionUpdatedAt(endpoint, time.Now().Add(-60*24*time.Hour).Unix()))
349
350 s.pruneAndNotifyWebPushSubscriptions()
351 waitFor(t, func() bool {
352 subs, err := s.webPush.SubscriptionsForTopic("test-topic")
353 require.Nil(t, err)
354 return len(subs) == 0
355 })
356 })
357 }
358
359 func payloadForTopics(t *testing.T, topics []string, endpoint string) string {
360 topicsJSON, err := json.Marshal(topics)
361 require.Nil(t, err)
362
363 return fmt.Sprintf(`{
364 "topics": %s,
365 "endpoint": "%s",
366 "p256dh": "p256dh-key",
367 "auth": "auth-key"
368 }`, topicsJSON, endpoint)
369 }
370
371 func addSubscription(t *testing.T, s *Server, endpoint string, topics ...string) {
372 require.Nil(t, s.webPush.UpsertSubscription(endpoint, "kSC3T8aN1JCQxxPdrFLrZg", "BMKKbxdUU_xLS7G1Wh5AN8PvWOjCzkCuKZYb8apcqYrDxjOF_2piggBnoJLQYx9IeSD70fNuwawI3e9Y8m3S3PE", "u_123", netip.MustParseAddr("1.2.3.4"), topics)) // Test auth and p256dh
373 }
374
375 func requireSubscriptionCount(t *testing.T, s *Server, topic string, expectedLength int) {
376 subs, err := s.webPush.SubscriptionsForTopic(topic)
377 require.Nil(t, err)
378 require.Len(t, subs, expectedLength)
379 }
380
381 func newTestConfigWithWebPush(t *testing.T, databaseURL string) *Config {
382 conf := newTestConfig(t, databaseURL)
383 privateKey, publicKey, err := webpush.GenerateVAPIDKeys()
384 require.Nil(t, err)
385 if conf.DatabaseURL == "" {
386 conf.WebPushFile = filepath.Join(t.TempDir(), "webpush.db")
387 }
388 conf.WebPushEmailAddress = "[email protected]"
389 conf.WebPushPrivateKey = privateKey
390 conf.WebPushPublicKey = publicKey
391 return conf
392 }