webpush_store_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package server
  2. import (
  3. "fmt"
  4. "github.com/stretchr/testify/require"
  5. "net/netip"
  6. "path/filepath"
  7. "testing"
  8. )
  9. func newTestWebPushStore(t *testing.T, filename string) *webPushStore {
  10. webPush, err := newWebPushStore(filename)
  11. require.Nil(t, err)
  12. return webPush
  13. }
  14. func TestWebPushStore_UpsertSubscription_SubscriptionsForTopic(t *testing.T) {
  15. webPush := newTestWebPushStore(t, filepath.Join(t.TempDir(), "webpush.db"))
  16. defer webPush.Close()
  17. require.Nil(t, webPush.UpsertSubscription(testWebPushEndpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"test-topic", "mytopic"}))
  18. subs, err := webPush.SubscriptionsForTopic("test-topic")
  19. require.Nil(t, err)
  20. require.Len(t, subs, 1)
  21. require.Equal(t, subs[0].Endpoint, testWebPushEndpoint)
  22. require.Equal(t, subs[0].P256dh, "p256dh-key")
  23. require.Equal(t, subs[0].Auth, "auth-key")
  24. require.Equal(t, subs[0].UserID, "u_1234")
  25. subs2, err := webPush.SubscriptionsForTopic("mytopic")
  26. require.Nil(t, err)
  27. require.Len(t, subs2, 1)
  28. require.Equal(t, subs[0].Endpoint, subs2[0].Endpoint)
  29. }
  30. func TestWebPushStore_UpsertSubscription_SubscriberIPLimitReached(t *testing.T) {
  31. webPush := newTestWebPushStore(t, filepath.Join(t.TempDir(), "webpush.db"))
  32. defer webPush.Close()
  33. // Insert 10 subscriptions with the same IP address
  34. for i := 0; i < 10; i++ {
  35. endpoint := fmt.Sprintf(testWebPushEndpoint+"%d", i)
  36. require.Nil(t, webPush.UpsertSubscription(endpoint, "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"test-topic", "mytopic"}))
  37. }
  38. // Another one for the same endpoint should be fine
  39. require.Nil(t, webPush.UpsertSubscription(testWebPushEndpoint+"0", "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"test-topic", "mytopic"}))
  40. // But with a different endpoint it should fail
  41. require.Equal(t, errWebPushTooManySubscriptions, webPush.UpsertSubscription(testWebPushEndpoint+"11", "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("1.2.3.4"), []string{"test-topic", "mytopic"}))
  42. // But with a different IP address it should be fine again
  43. require.Nil(t, webPush.UpsertSubscription(testWebPushEndpoint+"99", "auth-key", "p256dh-key", "u_1234", netip.MustParseAddr("9.9.9.9"), []string{"test-topic", "mytopic"}))
  44. }