server_firebase.go 9.1 KB

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