server_firebase_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package server
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "heckel.io/ntfy/user"
  7. "net/netip"
  8. "strings"
  9. "sync"
  10. "testing"
  11. "firebase.google.com/go/v4/messaging"
  12. "github.com/stretchr/testify/require"
  13. )
  14. type testAuther struct {
  15. Allow bool
  16. }
  17. var _ user.Auther = (*testAuther)(nil)
  18. func (t testAuther) Authenticate(_, _ string) (*user.User, error) {
  19. return nil, errors.New("not used")
  20. }
  21. func (t testAuther) Authorize(_ *user.User, _ string, _ user.Permission) error {
  22. if t.Allow {
  23. return nil
  24. }
  25. return errors.New("unauthorized")
  26. }
  27. type testFirebaseSender struct {
  28. allowed int
  29. messages []*messaging.Message
  30. mu sync.Mutex
  31. }
  32. func newTestFirebaseSender(allowed int) *testFirebaseSender {
  33. return &testFirebaseSender{
  34. allowed: allowed,
  35. messages: make([]*messaging.Message, 0),
  36. }
  37. }
  38. func (s *testFirebaseSender) Send(m *messaging.Message) error {
  39. s.mu.Lock()
  40. defer s.mu.Unlock()
  41. if len(s.messages)+1 > s.allowed {
  42. return errFirebaseQuotaExceeded
  43. }
  44. s.messages = append(s.messages, m)
  45. return nil
  46. }
  47. func (s *testFirebaseSender) Messages() []*messaging.Message {
  48. s.mu.Lock()
  49. defer s.mu.Unlock()
  50. return append(make([]*messaging.Message, 0), s.messages...)
  51. }
  52. func TestToFirebaseMessage_Keepalive(t *testing.T) {
  53. m := newKeepaliveMessage("mytopic")
  54. fbm, err := toFirebaseMessage(m, nil)
  55. require.Nil(t, err)
  56. require.Equal(t, "mytopic", fbm.Topic)
  57. require.Nil(t, fbm.Android)
  58. require.Equal(t, &messaging.APNSConfig{
  59. Headers: map[string]string{
  60. "apns-push-type": "background",
  61. "apns-priority": "5",
  62. },
  63. Payload: &messaging.APNSPayload{
  64. Aps: &messaging.Aps{
  65. ContentAvailable: true,
  66. },
  67. CustomData: map[string]any{
  68. "id": m.ID,
  69. "time": fmt.Sprintf("%d", m.Time),
  70. "event": m.Event,
  71. "topic": m.Topic,
  72. },
  73. },
  74. }, fbm.APNS)
  75. require.Equal(t, map[string]string{
  76. "id": m.ID,
  77. "time": fmt.Sprintf("%d", m.Time),
  78. "event": m.Event,
  79. "topic": m.Topic,
  80. }, fbm.Data)
  81. }
  82. func TestToFirebaseMessage_Open(t *testing.T) {
  83. m := newOpenMessage("mytopic")
  84. fbm, err := toFirebaseMessage(m, nil)
  85. require.Nil(t, err)
  86. require.Equal(t, "mytopic", fbm.Topic)
  87. require.Nil(t, fbm.Android)
  88. require.Equal(t, &messaging.APNSConfig{
  89. Headers: map[string]string{
  90. "apns-push-type": "background",
  91. "apns-priority": "5",
  92. },
  93. Payload: &messaging.APNSPayload{
  94. Aps: &messaging.Aps{
  95. ContentAvailable: true,
  96. },
  97. CustomData: map[string]any{
  98. "id": m.ID,
  99. "time": fmt.Sprintf("%d", m.Time),
  100. "event": m.Event,
  101. "topic": m.Topic,
  102. },
  103. },
  104. }, fbm.APNS)
  105. require.Equal(t, map[string]string{
  106. "id": m.ID,
  107. "time": fmt.Sprintf("%d", m.Time),
  108. "event": m.Event,
  109. "topic": m.Topic,
  110. }, fbm.Data)
  111. }
  112. func TestToFirebaseMessage_Message_Normal_Allowed(t *testing.T) {
  113. m := newDefaultMessage("mytopic", "this is a message")
  114. m.Priority = 4
  115. m.Tags = []string{"tag 1", "tag2"}
  116. m.Click = "https://google.com"
  117. m.Icon = "https://ntfy.sh/static/img/ntfy.png"
  118. m.Title = "some title"
  119. m.Actions = []*action{
  120. {
  121. ID: "123",
  122. Action: "view",
  123. Label: "Open page",
  124. Clear: true,
  125. URL: "https://ntfy.sh",
  126. },
  127. {
  128. ID: "456",
  129. Action: "http",
  130. Label: "Close door",
  131. URL: "https://door.com/close",
  132. Method: "PUT",
  133. Headers: map[string]string{
  134. "really": "yes",
  135. },
  136. },
  137. }
  138. m.Attachment = &attachment{
  139. Name: "some file.jpg",
  140. Type: "image/jpeg",
  141. Size: 12345,
  142. Expires: 98765543,
  143. URL: "https://example.com/file.jpg",
  144. }
  145. fbm, err := toFirebaseMessage(m, &testAuther{Allow: true})
  146. require.Nil(t, err)
  147. require.Equal(t, "mytopic", fbm.Topic)
  148. require.Equal(t, &messaging.AndroidConfig{
  149. Priority: "high",
  150. }, fbm.Android)
  151. require.Equal(t, &messaging.APNSConfig{
  152. Payload: &messaging.APNSPayload{
  153. Aps: &messaging.Aps{
  154. MutableContent: true,
  155. Alert: &messaging.ApsAlert{
  156. Title: "some title",
  157. Body: "this is a message",
  158. },
  159. },
  160. CustomData: map[string]any{
  161. "id": m.ID,
  162. "time": fmt.Sprintf("%d", m.Time),
  163. "event": "message",
  164. "topic": "mytopic",
  165. "priority": "4",
  166. "tags": strings.Join(m.Tags, ","),
  167. "click": "https://google.com",
  168. "icon": "https://ntfy.sh/static/img/ntfy.png",
  169. "title": "some title",
  170. "message": "this is a message",
  171. "actions": `[{"id":"123","action":"view","label":"Open page","clear":true,"url":"https://ntfy.sh"},{"id":"456","action":"http","label":"Close door","clear":false,"url":"https://door.com/close","method":"PUT","headers":{"really":"yes"}}]`,
  172. "content_type": "",
  173. "encoding": "",
  174. "attachment_name": "some file.jpg",
  175. "attachment_type": "image/jpeg",
  176. "attachment_size": "12345",
  177. "attachment_expires": "98765543",
  178. "attachment_url": "https://example.com/file.jpg",
  179. },
  180. },
  181. }, fbm.APNS)
  182. require.Equal(t, map[string]string{
  183. "id": m.ID,
  184. "time": fmt.Sprintf("%d", m.Time),
  185. "event": "message",
  186. "topic": "mytopic",
  187. "priority": "4",
  188. "tags": strings.Join(m.Tags, ","),
  189. "click": "https://google.com",
  190. "icon": "https://ntfy.sh/static/img/ntfy.png",
  191. "title": "some title",
  192. "message": "this is a message",
  193. "actions": `[{"id":"123","action":"view","label":"Open page","clear":true,"url":"https://ntfy.sh"},{"id":"456","action":"http","label":"Close door","clear":false,"url":"https://door.com/close","method":"PUT","headers":{"really":"yes"}}]`,
  194. "content_type": "",
  195. "encoding": "",
  196. "attachment_name": "some file.jpg",
  197. "attachment_type": "image/jpeg",
  198. "attachment_size": "12345",
  199. "attachment_expires": "98765543",
  200. "attachment_url": "https://example.com/file.jpg",
  201. }, fbm.Data)
  202. }
  203. func TestToFirebaseMessage_Message_Normal_Not_Allowed(t *testing.T) {
  204. m := newDefaultMessage("mytopic", "this is a message")
  205. m.Priority = 5
  206. fbm, err := toFirebaseMessage(m, &testAuther{Allow: false}) // Not allowed!
  207. require.Nil(t, err)
  208. require.Equal(t, "mytopic", fbm.Topic)
  209. require.Equal(t, &messaging.AndroidConfig{
  210. Priority: "high",
  211. }, fbm.Android)
  212. require.Equal(t, "", fbm.Data["message"])
  213. require.Equal(t, "", fbm.Data["priority"])
  214. require.Equal(t, map[string]string{
  215. "id": m.ID,
  216. "time": fmt.Sprintf("%d", m.Time),
  217. "event": "poll_request",
  218. "topic": "mytopic",
  219. }, fbm.Data)
  220. }
  221. func TestToFirebaseMessage_PollRequest(t *testing.T) {
  222. m := newPollRequestMessage("mytopic", "fOv6k1QbCzo6")
  223. fbm, err := toFirebaseMessage(m, nil)
  224. require.Nil(t, err)
  225. require.Equal(t, "mytopic", fbm.Topic)
  226. require.Nil(t, fbm.Android)
  227. require.Equal(t, &messaging.APNSConfig{
  228. Payload: &messaging.APNSPayload{
  229. Aps: &messaging.Aps{
  230. MutableContent: true,
  231. Alert: &messaging.ApsAlert{
  232. Title: "",
  233. Body: "New message",
  234. },
  235. },
  236. CustomData: map[string]any{
  237. "id": m.ID,
  238. "time": fmt.Sprintf("%d", m.Time),
  239. "event": "poll_request",
  240. "topic": "mytopic",
  241. "message": "New message",
  242. "poll_id": "fOv6k1QbCzo6",
  243. },
  244. },
  245. }, fbm.APNS)
  246. require.Equal(t, map[string]string{
  247. "id": m.ID,
  248. "time": fmt.Sprintf("%d", m.Time),
  249. "event": "poll_request",
  250. "topic": "mytopic",
  251. "message": "New message",
  252. "poll_id": "fOv6k1QbCzo6",
  253. }, fbm.Data)
  254. }
  255. func TestMaybeTruncateFCMMessage(t *testing.T) {
  256. origMessage := strings.Repeat("this is a long string", 300)
  257. origFCMMessage := &messaging.Message{
  258. Topic: "mytopic",
  259. Data: map[string]string{
  260. "id": "abcdefg",
  261. "time": "1641324761",
  262. "event": "message",
  263. "topic": "mytopic",
  264. "priority": "0",
  265. "tags": "",
  266. "title": "",
  267. "message": origMessage,
  268. },
  269. Android: &messaging.AndroidConfig{
  270. Priority: "high",
  271. },
  272. }
  273. origMessageLength := len(origFCMMessage.Data["message"])
  274. serializedOrigFCMMessage, _ := json.Marshal(origFCMMessage)
  275. require.Greater(t, len(serializedOrigFCMMessage), fcmMessageLimit) // Pre-condition
  276. truncatedFCMMessage := maybeTruncateFCMMessage(origFCMMessage)
  277. truncatedMessageLength := len(truncatedFCMMessage.Data["message"])
  278. serializedTruncatedFCMMessage, _ := json.Marshal(truncatedFCMMessage)
  279. require.Equal(t, fcmMessageLimit, len(serializedTruncatedFCMMessage))
  280. require.Equal(t, "1", truncatedFCMMessage.Data["truncated"])
  281. require.NotEqual(t, origMessageLength, truncatedMessageLength)
  282. }
  283. func TestMaybeTruncateFCMMessage_NotTooLong(t *testing.T) {
  284. origMessage := "not really a long string"
  285. origFCMMessage := &messaging.Message{
  286. Topic: "mytopic",
  287. Data: map[string]string{
  288. "id": "abcdefg",
  289. "time": "1641324761",
  290. "event": "message",
  291. "topic": "mytopic",
  292. "priority": "0",
  293. "tags": "",
  294. "title": "",
  295. "message": origMessage,
  296. },
  297. }
  298. origMessageLength := len(origFCMMessage.Data["message"])
  299. serializedOrigFCMMessage, _ := json.Marshal(origFCMMessage)
  300. require.LessOrEqual(t, len(serializedOrigFCMMessage), fcmMessageLimit) // Pre-condition
  301. notTruncatedFCMMessage := maybeTruncateFCMMessage(origFCMMessage)
  302. notTruncatedMessageLength := len(notTruncatedFCMMessage.Data["message"])
  303. serializedNotTruncatedFCMMessage, _ := json.Marshal(notTruncatedFCMMessage)
  304. require.Equal(t, origMessageLength, notTruncatedMessageLength)
  305. require.Equal(t, len(serializedOrigFCMMessage), len(serializedNotTruncatedFCMMessage))
  306. require.Equal(t, "", notTruncatedFCMMessage.Data["truncated"])
  307. }
  308. func TestToFirebaseSender_Abuse(t *testing.T) {
  309. sender := &testFirebaseSender{allowed: 2}
  310. client := newFirebaseClient(sender, &testAuther{})
  311. visitor := newVisitor(newTestConfig(t), newMemTestCache(t), nil, netip.MustParseAddr("1.2.3.4"), nil)
  312. require.Nil(t, client.Send(visitor, &message{Topic: "mytopic"}))
  313. require.Equal(t, 1, len(sender.Messages()))
  314. require.Nil(t, client.Send(visitor, &message{Topic: "mytopic"}))
  315. require.Equal(t, 2, len(sender.Messages()))
  316. require.Equal(t, errFirebaseQuotaExceeded, client.Send(visitor, &message{Topic: "mytopic"}))
  317. require.Equal(t, 2, len(sender.Messages()))
  318. sender.messages = make([]*messaging.Message, 0) // Reset to test that time limit is working
  319. require.Equal(t, errFirebaseTemporarilyBanned, client.Send(visitor, &message{Topic: "mytopic"}))
  320. require.Equal(t, 0, len(sender.Messages()))
  321. }