server_firebase.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "strings"
  9. firebase "firebase.google.com/go/v4"
  10. "firebase.google.com/go/v4/messaging"
  11. "google.golang.org/api/option"
  12. "heckel.io/ntfy/auth"
  13. )
  14. const (
  15. fcmMessageLimit = 4000
  16. fcmApnsBodyMessageLimit = 100
  17. )
  18. var (
  19. errFirebaseQuotaExceeded = errors.New("quota exceeded for Firebase messages to topic")
  20. )
  21. // firebaseClient is a generic client that formats and sends messages to Firebase.
  22. // The actual Firebase implementation is implemented in firebaseSenderImpl, to make it testable.
  23. type firebaseClient struct {
  24. sender firebaseSender
  25. auther auth.Auther
  26. }
  27. func newFirebaseClient(sender firebaseSender, auther auth.Auther) *firebaseClient {
  28. return &firebaseClient{
  29. sender: sender,
  30. auther: auther,
  31. }
  32. }
  33. func (c *firebaseClient) Send(v *visitor, m *message) error {
  34. if err := v.FirebaseAllowed(); err != nil {
  35. return errFirebaseQuotaExceeded
  36. }
  37. fbm, err := toFirebaseMessage(m, c.auther)
  38. if err != nil {
  39. return err
  40. }
  41. err = c.sender.Send(fbm)
  42. if err == errFirebaseQuotaExceeded {
  43. log.Printf("[%s] FB quota exceeded for topic %s, temporarily denying FB access to visitor", v.ip, m.Topic)
  44. v.FirebaseTemporarilyDeny()
  45. }
  46. return err
  47. }
  48. // firebaseSender is an interface that represents a client that can send to Firebase Cloud Messaging.
  49. // In tests, this can be implemented with a mock.
  50. type firebaseSender interface {
  51. // Send sends a message to Firebase, or returns an error. It returns errFirebaseQuotaExceeded
  52. // if a rate limit has reached.
  53. Send(m *messaging.Message) error
  54. }
  55. // firebaseSenderImpl is a firebaseSender that actually talks to Firebase
  56. type firebaseSenderImpl struct {
  57. client *messaging.Client
  58. }
  59. func newFirebaseSender(credentialsFile string) (*firebaseSenderImpl, error) {
  60. fb, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsFile(credentialsFile))
  61. if err != nil {
  62. return nil, err
  63. }
  64. client, err := fb.Messaging(context.Background())
  65. if err != nil {
  66. return nil, err
  67. }
  68. return &firebaseSenderImpl{
  69. client: client,
  70. }, nil
  71. }
  72. func (c *firebaseSenderImpl) Send(m *messaging.Message) error {
  73. _, err := c.client.Send(context.Background(), m)
  74. if err != nil && messaging.IsQuotaExceeded(err) {
  75. return errFirebaseQuotaExceeded
  76. }
  77. return err
  78. }
  79. // toFirebaseMessage converts a message to a Firebase message.
  80. //
  81. // Normal messages ("message"):
  82. // - For Android, we can receive data messages from Firebase and process them as code, so we just send all fields
  83. // in the "data" attribute. In the Android app, we then turn those into a notification and display it.
  84. // - On iOS, we are not allowed to receive data-only messages, so we build messages with an "alert" (with title and
  85. // message), and still send the rest of the data along in the "aps" attribute. We can then locally modify the
  86. // message in the Notification Service Extension.
  87. //
  88. // Keepalive messages ("keepalive"):
  89. // - On Android, we subscribe to the "~control" topic, which is used to restart the foreground service (if it died,
  90. // e.g. after an app update). We send these keepalive messages regularly (see Config.FirebaseKeepaliveInterval).
  91. // - On iOS, we subscribe to the "~poll" topic, which is used to poll all topics regularly. This is because iOS
  92. // does not allow any background or scheduled activity at all.
  93. //
  94. // Poll request messages ("poll_request"):
  95. // - Normal messages are turned into poll request messages if anonymous users are not allowed to read the message.
  96. // On Android, this will trigger the app to poll the topic and thereby displaying new messages.
  97. // - If UpstreamBaseURL is set, messages are forwarded as poll requests to an upstream server and then forwarded
  98. // to Firebase here. This is mainly for iOS to support self-hosted servers.
  99. func toFirebaseMessage(m *message, auther auth.Auther) (*messaging.Message, error) {
  100. var data map[string]string // Mostly matches https://ntfy.sh/docs/subscribe/api/#json-message-format
  101. var apnsConfig *messaging.APNSConfig
  102. switch m.Event {
  103. case keepaliveEvent, openEvent:
  104. data = map[string]string{
  105. "id": m.ID,
  106. "time": fmt.Sprintf("%d", m.Time),
  107. "event": m.Event,
  108. "topic": m.Topic,
  109. }
  110. apnsConfig = createAPNSBackgroundConfig(data)
  111. case pollRequestEvent:
  112. data = map[string]string{
  113. "id": m.ID,
  114. "time": fmt.Sprintf("%d", m.Time),
  115. "event": m.Event,
  116. "topic": m.Topic,
  117. "message": m.Message,
  118. "poll_id": m.PollID,
  119. }
  120. apnsConfig = createAPNSAlertConfig(m, data)
  121. case messageEvent:
  122. allowForward := true
  123. if auther != nil {
  124. allowForward = auther.Authorize(nil, m.Topic, auth.PermissionRead) == nil
  125. }
  126. if allowForward {
  127. data = map[string]string{
  128. "id": m.ID,
  129. "time": fmt.Sprintf("%d", m.Time),
  130. "event": m.Event,
  131. "topic": m.Topic,
  132. "priority": fmt.Sprintf("%d", m.Priority),
  133. "tags": strings.Join(m.Tags, ","),
  134. "click": m.Click,
  135. "title": m.Title,
  136. "message": m.Message,
  137. "encoding": m.Encoding,
  138. }
  139. if len(m.Actions) > 0 {
  140. actions, err := json.Marshal(m.Actions)
  141. if err != nil {
  142. return nil, err
  143. }
  144. data["actions"] = string(actions)
  145. }
  146. if m.Attachment != nil {
  147. data["attachment_name"] = m.Attachment.Name
  148. data["attachment_type"] = m.Attachment.Type
  149. data["attachment_size"] = fmt.Sprintf("%d", m.Attachment.Size)
  150. data["attachment_expires"] = fmt.Sprintf("%d", m.Attachment.Expires)
  151. data["attachment_url"] = m.Attachment.URL
  152. }
  153. apnsConfig = createAPNSAlertConfig(m, data)
  154. } else {
  155. // If anonymous read for a topic is not allowed, we cannot send the message along
  156. // via Firebase. Instead, we send a "poll_request" message, asking the client to poll.
  157. data = map[string]string{
  158. "id": m.ID,
  159. "time": fmt.Sprintf("%d", m.Time),
  160. "event": pollRequestEvent,
  161. "topic": m.Topic,
  162. }
  163. // TODO Handle APNS?
  164. }
  165. }
  166. var androidConfig *messaging.AndroidConfig
  167. if m.Priority >= 4 {
  168. androidConfig = &messaging.AndroidConfig{
  169. Priority: "high",
  170. }
  171. }
  172. return maybeTruncateFCMMessage(&messaging.Message{
  173. Topic: m.Topic,
  174. Data: data,
  175. Android: androidConfig,
  176. APNS: apnsConfig,
  177. }), nil
  178. }
  179. // maybeTruncateFCMMessage performs best-effort truncation of FCM messages.
  180. // The docs say the limit is 4000 characters, but during testing it wasn't quite clear
  181. // what fields matter; so we're just capping the serialized JSON to 4000 bytes.
  182. func maybeTruncateFCMMessage(m *messaging.Message) *messaging.Message {
  183. s, err := json.Marshal(m)
  184. if err != nil {
  185. return m
  186. }
  187. if len(s) > fcmMessageLimit {
  188. over := len(s) - fcmMessageLimit + 16 // = len("truncated":"1",), sigh ...
  189. message, ok := m.Data["message"]
  190. if ok && len(message) > over {
  191. m.Data["truncated"] = "1"
  192. m.Data["message"] = message[:len(message)-over]
  193. }
  194. }
  195. return m
  196. }
  197. // createAPNSAlertConfig creates an APNS config for iOS notifications that show up as an alert (only relevant for iOS).
  198. // We must set the Alert struct ("alert"), and we need to set MutableContent ("mutable-content"), so the Notification Service
  199. // Extension in iOS can modify the message.
  200. func createAPNSAlertConfig(m *message, data map[string]string) *messaging.APNSConfig {
  201. apnsData := make(map[string]interface{})
  202. for k, v := range data {
  203. apnsData[k] = v
  204. }
  205. return &messaging.APNSConfig{
  206. Payload: &messaging.APNSPayload{
  207. CustomData: apnsData,
  208. Aps: &messaging.Aps{
  209. MutableContent: true,
  210. Alert: &messaging.ApsAlert{
  211. Title: m.Title,
  212. Body: maybeTruncateAPNSBodyMessage(m.Message),
  213. },
  214. },
  215. },
  216. }
  217. }
  218. // createAPNSBackgroundConfig creates an APNS config for a silent background message (only relevant for iOS). Apple only
  219. // allows us to send 2-3 of these notifications per hour, and delivery not guaranteed. We use this only for the ~poll
  220. // topic, which triggers the iOS app to poll all topics for changes.
  221. //
  222. // See https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app
  223. func createAPNSBackgroundConfig(data map[string]string) *messaging.APNSConfig {
  224. apnsData := make(map[string]interface{})
  225. for k, v := range data {
  226. apnsData[k] = v
  227. }
  228. return &messaging.APNSConfig{
  229. Headers: map[string]string{
  230. "apns-push-type": "background",
  231. "apns-priority": "5",
  232. },
  233. Payload: &messaging.APNSPayload{
  234. Aps: &messaging.Aps{
  235. ContentAvailable: true,
  236. },
  237. CustomData: apnsData,
  238. },
  239. }
  240. }
  241. // maybeTruncateAPNSBodyMessage truncates the body for APNS.
  242. //
  243. // The "body" of the push notification can contain the entire message, which would count doubly for the overall length
  244. // of the APNS payload. I set a limit of 100 characters before truncating the notification "body" with ellipsis.
  245. // The message would not be changed (unless truncated for being too long). Note: if the payload is too large (>4KB),
  246. // APNS will simply reject / discard the notification, meaning it will never arrive on the iOS device.
  247. func maybeTruncateAPNSBodyMessage(s string) string {
  248. if len(s) >= fcmApnsBodyMessageLimit {
  249. over := len(s) - fcmApnsBodyMessageLimit + 3 // len("...")
  250. return s[:len(s)-over] + "..."
  251. }
  252. return s
  253. }