server_firebase_test.go 10 KB

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