Debian Codegraph @

webpush/store_test.go

raw
1 package webpush_test
2
3 import (
4 "database/sql"
5 "fmt"
6 "net/netip"
7 "path/filepath"
8 "testing"
9 "time"
10
11 "github.com/stretchr/testify/require"
12 dbtest "heckel.io/ntfy/v2/db/test"
13 "heckel.io/ntfy/v2/webpush"
14 )
15
16 const testWebPushEndpoint = "https://updates.push.services.mozilla.com/wpush/v1/AAABBCCCDDEEEFFF"
17
18 // Schema layout as written by ntfy releases before the db/schema framework; used to verify
19 // that existing databases open cleanly without an adoption step
20 const (
21 testPreFrameworkSQLiteSchema = `
22 CREATE TABLE subscription (
23 id TEXT PRIMARY KEY,
24 endpoint TEXT NOT NULL,
25 key_auth TEXT NOT NULL,
26 key_p256dh TEXT NOT NULL,
27 user_id TEXT NOT NULL,
28 subscriber_ip TEXT NOT NULL,
29 updated_at INT NOT NULL,
30 warned_at INT NOT NULL DEFAULT 0
31 );
32 CREATE UNIQUE INDEX idx_endpoint ON subscription (endpoint);
33 CREATE INDEX idx_subscriber_ip ON subscription (subscriber_ip);
34 CREATE TABLE subscription_topic (
35 subscription_id TEXT NOT NULL,
36 topic TEXT NOT NULL,
37 PRIMARY KEY (subscription_id, topic),
38 FOREIGN KEY (subscription_id) REFERENCES subscription (id) ON DELETE CASCADE
39 );
40 CREATE INDEX idx_topic ON subscription_topic (topic);
41 CREATE TABLE schemaVersion (id INT PRIMARY KEY, version INT NOT NULL);
42 INSERT INTO schemaVersion VALUES (1, 1);
43 `
44 testPreFrameworkPostgresSchema = `
45 CREATE TABLE webpush_subscription (
46 id TEXT PRIMARY KEY,
47 endpoint TEXT NOT NULL UNIQUE,
48 key_auth TEXT NOT NULL,
49 key_p256dh TEXT NOT NULL,
50 user_id TEXT NOT NULL,
51 subscriber_ip TEXT NOT NULL,
52 updated_at BIGINT NOT NULL,
53 warned_at BIGINT NOT NULL DEFAULT 0
54 );
55 CREATE INDEX idx_webpush_subscriber_ip ON webpush_subscription (subscriber_ip);
56 CREATE INDEX idx_webpush_updated_at ON webpush_subscription (updated_at);
57 CREATE INDEX idx_webpush_user_id ON webpush_subscription (user_id);
58 CREATE TABLE webpush_subscription_topic (
59 subscription_id TEXT NOT NULL REFERENCES webpush_subscription (id) ON DELETE CASCADE,
60 topic TEXT NOT NULL,
61 PRIMARY KEY (subscription_id, topic)
62 );
63 CREATE INDEX idx_webpush_topic ON webpush_subscription_topic (topic);
64 CREATE TABLE schema_version (store TEXT PRIMARY KEY, version INT NOT NULL);
65 INSERT INTO schema_version (store, version) VALUES ('webpush', 1);
66 `
67 )
68
69 // TestStoreSchemaEquivalence verifies that a database adopted from the pre-framework layout is
70 // structurally identical to a freshly created one: same tables, columns, indexes and keys.
71 func TestStoreSchemaEquivalence(t *testing.T) {
72 t.Run("sqlite", func(t *testing.T) {
73 freshFile := filepath.Join(t.TempDir(), "fresh.db")
74 fresh, err := webpush.NewSQLiteStore(freshFile, "")
75 require.Nil(t, err)
76 defer fresh.Close()
77 migratedFile := filepath.Join(t.TempDir(), "migrated.db")
78 d, err := sql.Open("sqlite3", migratedFile)
79 require.Nil(t, err)
80 _, err = d.Exec(testPreFrameworkSQLiteSchema)
81 require.Nil(t, err)
82 require.Nil(t, d.Close())
83 migrated, err := webpush.NewSQLiteStore(migratedFile, "")
84 require.Nil(t, err)
85 defer migrated.Close()
86 freshDB, err := sql.Open("sqlite3", freshFile)
87 require.Nil(t, err)
88 defer freshDB.Close()
89 migratedDB, err := sql.Open("sqlite3", migratedFile)
90 require.Nil(t, err)
91 defer migratedDB.Close()
92 require.Equal(t, dbtest.SQLiteSchema(t, freshDB), dbtest.SQLiteSchema(t, migratedDB))
93 })
94 t.Run("postgres", func(t *testing.T) {
95 freshDB := dbtest.CreateTestPostgres(t)
96 _, err := webpush.NewPostgresStore(freshDB)
97 require.Nil(t, err)
98 migratedDB := dbtest.CreateTestPostgres(t)
99 _, err = migratedDB.Exec(testPreFrameworkPostgresSchema)
100 require.Nil(t, err)
101 _, err = webpush.NewPostgresStore(migratedDB)
102 require.Nil(t, err)
103 require.Equal(t, dbtest.PostgresSchema(t, freshDB), dbtest.PostgresSchema(t, migratedDB))
104 })
105 }
106
107 func TestStoreSQLiteOpensExistingDatabase(t *testing.T) {
108 filename := filepath.Join(t.TempDir(), "webpush.db")
109 d, err := sql.Open("sqlite3", filename)
110 require.Nil(t, err)
111 _, err = d.Exec(testPreFrameworkSQLiteSchema)
112 require.Nil(t, err)
113 require.Nil(t, d.Close())
114 store, err := webpush.NewSQLiteStore(filename, "")
115 require.Nil(t, err)
116 defer store.Close()
117 requireStoreUsable(t, store)
118 }
119
120 func TestStorePostgresOpensExistingDatabase(t *testing.T) {
121 testDB := dbtest.CreateTestPostgres(t)
122 _, err := testDB.Exec(testPreFrameworkPostgresSchema)
123 require.Nil(t, err)
124 store, err := webpush.NewPostgresStore(testDB)
125 require.Nil(t, err)
126 requireStoreUsable(t, store)
127 }
128
129 func requireStoreUsable(t *testing.T, store *webpush.Store) {
130 t.Helper()
131 err := store.UpsertSubscription(testWebPushEndpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"mytopic"})
132 require.Nil(t, err)
133 subs, err := store.SubscriptionsForTopic("mytopic")
134 require.Nil(t, err)
135 require.Len(t, subs, 1)
136 require.Equal(t, testWebPushEndpoint, subs[0].Endpoint)
137 }
138
139 func forEachBackend(t *testing.T, f func(t *testing.T, store *webpush.Store)) {
140 t.Run("sqlite", func(t *testing.T) {
141 store, err := webpush.NewSQLiteStore(filepath.Join(t.TempDir(), "webpush.db"), "")
142 require.Nil(t, err)
143 t.Cleanup(func() { store.Close() })
144 f(t, store)
145 })
146 t.Run("postgres", func(t *testing.T) {
147 testDB := dbtest.CreateTestPostgres(t)
148 store, err := webpush.NewPostgresStore(testDB)
149 require.Nil(t, err)
150 f(t, store)
151 })
152 }
153
154 func TestStoreUpsertSubscriptionSubscriptionsForTopic(t *testing.T) {
155 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
156 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"test-topic", "mytopic"}))
157
158 subs, err := store.SubscriptionsForTopic("test-topic")
159 require.Nil(t, err)
160 require.Len(t, subs, 1)
161 require.Equal(t, subs[0].Endpoint, testWebPushEndpoint)
162 require.Equal(t, subs[0].P256dh, "p256dh-key")
163 require.Equal(t, subs[0].Auth, "auth-key")
164 require.Equal(t, subs[0].UserID, "u_1234")
165
166 subs2, err := store.SubscriptionsForTopic("mytopic")
167 require.Nil(t, err)
168 require.Len(t, subs2, 1)
169 require.Equal(t, subs[0].Endpoint, subs2[0].Endpoint)
170 })
171 }
172
173 func TestStoreUpsertSubscriptionSubscriberIPLimitReached(t *testing.T) {
174 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
175 // Insert 10 subscriptions with the same IP address
176 for i := 0; i < 10; i++ {
177 endpoint := fmt.Sprintf(testWebPushEndpoint+"%d", i)
178 require.Nil(t, store.UpsertSubscription(endpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"test-topic", "mytopic"}))
179 }
180
181 // Another one for the same endpoint should be fine
182 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint+"0", "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"test-topic", "mytopic"}))
183
184 // But with a different endpoint it should fail
185 require.Equal(t, webpush.ErrWebPushTooManySubscriptions, store.UpsertSubscription(testWebPushEndpoint+"11", "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"test-topic", "mytopic"}))
186
187 // But with a different IP address it should be fine again
188 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint+"99", "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("9.9.9.9"), []string{"test-topic", "mytopic"}))
189 })
190 }
191
192 func TestStoreUpsertSubscriptionUpdateTopics(t *testing.T) {
193 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
194 // Insert subscription with two topics, and another with one topic
195 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint+"0", "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"topic1", "topic2"}))
196 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint+"1", "auth-key", "p256dh-key", "", netip.MustParseAddr("9.9.9.9"), []string{"topic1"}))
197
198 subs, err := store.SubscriptionsForTopic("topic1")
199 require.Nil(t, err)
200 require.Len(t, subs, 2)
201 require.Equal(t, testWebPushEndpoint+"0", subs[0].Endpoint)
202 require.Equal(t, testWebPushEndpoint+"1", subs[1].Endpoint)
203
204 subs, err = store.SubscriptionsForTopic("topic2")
205 require.Nil(t, err)
206 require.Len(t, subs, 1)
207 require.Equal(t, testWebPushEndpoint+"0", subs[0].Endpoint)
208
209 // Update the first subscription to have only one topic
210 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint+"0", "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"topic1"}))
211
212 subs, err = store.SubscriptionsForTopic("topic1")
213 require.Nil(t, err)
214 require.Len(t, subs, 2)
215 require.Equal(t, testWebPushEndpoint+"0", subs[0].Endpoint)
216
217 subs, err = store.SubscriptionsForTopic("topic2")
218 require.Nil(t, err)
219 require.Len(t, subs, 0)
220 })
221 }
222
223 func TestStoreUpsertSubscriptionUpdateFields(t *testing.T) {
224 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
225 // Insert a subscription
226 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"topic1"}))
227
228 subs, err := store.SubscriptionsForTopic("topic1")
229 require.Nil(t, err)
230 require.Len(t, subs, 1)
231 require.Equal(t, "auth-key", subs[0].Auth)
232 require.Equal(t, "p256dh-key", subs[0].P256dh)
233 require.Equal(t, "u_1234", subs[0].UserID)
234
235 // Re-upsert the same endpoint with different auth, p256dh, and userID
236 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint, "new-auth", "new-p256dh", "u_5678", netip.MustParseAddr("1.2.3.4"), []string{"topic1"}))
237
238 subs, err = store.SubscriptionsForTopic("topic1")
239 require.Nil(t, err)
240 require.Len(t, subs, 1)
241 require.Equal(t, testWebPushEndpoint, subs[0].Endpoint)
242 require.Equal(t, "new-auth", subs[0].Auth)
243 require.Equal(t, "new-p256dh", subs[0].P256dh)
244 require.Equal(t, "u_5678", subs[0].UserID)
245 })
246 }
247
248 func TestStoreRemoveByUserIDMultiple(t *testing.T) {
249 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
250 // Insert two subscriptions for u_1234 and one for u_5678
251 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint+"0", "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"topic1"}))
252 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint+"1", "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"topic1"}))
253 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint+"2", "auth-key", "p256dh-key", "u_5678", netip.MustParseAddr("9.9.9.9"), []string{"topic1"}))
254
255 subs, err := store.SubscriptionsForTopic("topic1")
256 require.Nil(t, err)
257 require.Len(t, subs, 3)
258
259 // Remove all subscriptions for u_1234
260 require.Nil(t, store.RemoveSubscriptionsByUserID("u_1234"))
261
262 // Only u_5678's subscription should remain
263 subs, err = store.SubscriptionsForTopic("topic1")
264 require.Nil(t, err)
265 require.Len(t, subs, 1)
266 require.Equal(t, testWebPushEndpoint+"2", subs[0].Endpoint)
267 require.Equal(t, "u_5678", subs[0].UserID)
268 })
269 }
270
271 func TestStoreRemoveByEndpoint(t *testing.T) {
272 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
273 // Insert subscription with two topics
274 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"topic1", "topic2"}))
275 subs, err := store.SubscriptionsForTopic("topic1")
276 require.Nil(t, err)
277 require.Len(t, subs, 1)
278
279 // And remove it again
280 require.Nil(t, store.RemoveSubscriptionsByEndpoint(testWebPushEndpoint))
281 subs, err = store.SubscriptionsForTopic("topic1")
282 require.Nil(t, err)
283 require.Len(t, subs, 0)
284 })
285 }
286
287 func TestStoreRemoveByUserID(t *testing.T) {
288 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
289 // Insert subscription with two topics
290 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"topic1", "topic2"}))
291 subs, err := store.SubscriptionsForTopic("topic1")
292 require.Nil(t, err)
293 require.Len(t, subs, 1)
294
295 // And remove it again
296 require.Nil(t, store.RemoveSubscriptionsByUserID("u_1234"))
297 subs, err = store.SubscriptionsForTopic("topic1")
298 require.Nil(t, err)
299 require.Len(t, subs, 0)
300 })
301 }
302
303 func TestStoreRemoveByUserIDEmpty(t *testing.T) {
304 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
305 require.Equal(t, webpush.ErrWebPushUserIDCannotBeEmpty, store.RemoveSubscriptionsByUserID(""))
306 })
307 }
308
309 func TestStoreExpiryWarningSent(t *testing.T) {
310 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
311 // Insert subscription with two topics
312 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"topic1", "topic2"}))
313
314 // Set updated_at to the past so it shows up as expiring
315 require.Nil(t, store.SetSubscriptionUpdatedAt(testWebPushEndpoint, time.Now().Add(-8*24*time.Hour).Unix()))
316
317 // Verify subscription appears in expiring list (warned_at == 0)
318 subs, err := store.SubscriptionsExpiring(7 * 24 * time.Hour)
319 require.Nil(t, err)
320 require.Len(t, subs, 1)
321 require.Equal(t, testWebPushEndpoint, subs[0].Endpoint)
322
323 // Mark them as warning sent
324 require.Nil(t, store.MarkExpiryWarningSent(subs))
325
326 // Verify subscription no longer appears in expiring list (warned_at > 0)
327 subs, err = store.SubscriptionsExpiring(7 * 24 * time.Hour)
328 require.Nil(t, err)
329 require.Len(t, subs, 0)
330 })
331 }
332
333 func TestStoreExpiring(t *testing.T) {
334 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
335 // Insert subscription with two topics
336 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"topic1", "topic2"}))
337 subs, err := store.SubscriptionsForTopic("topic1")
338 require.Nil(t, err)
339 require.Len(t, subs, 1)
340
341 // Fake-mark them as soon-to-expire
342 require.Nil(t, store.SetSubscriptionUpdatedAt(testWebPushEndpoint, time.Now().Add(-8*24*time.Hour).Unix()))
343
344 // Should not be cleaned up yet
345 require.Nil(t, store.RemoveExpiredSubscriptions(9*24*time.Hour))
346
347 // Run expiration
348 subs, err = store.SubscriptionsExpiring(7 * 24 * time.Hour)
349 require.Nil(t, err)
350 require.Len(t, subs, 1)
351 require.Equal(t, testWebPushEndpoint, subs[0].Endpoint)
352 })
353 }
354
355 func TestStoreRemoveExpired(t *testing.T) {
356 forEachBackend(t, func(t *testing.T, store *webpush.Store) {
357 // Insert subscription with two topics
358 require.Nil(t, store.UpsertSubscription(testWebPushEndpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"topic1", "topic2"}))
359 subs, err := store.SubscriptionsForTopic("topic1")
360 require.Nil(t, err)
361 require.Len(t, subs, 1)
362
363 // Fake-mark them as expired
364 require.Nil(t, store.SetSubscriptionUpdatedAt(testWebPushEndpoint, time.Now().Add(-10*24*time.Hour).Unix()))
365
366 // Run expiration
367 require.Nil(t, store.RemoveExpiredSubscriptions(9*24*time.Hour))
368
369 // List again, should be 0
370 subs, err = store.SubscriptionsForTopic("topic1")
371 require.Nil(t, err)
372 require.Len(t, subs, 0)
373 })
374 }