server_firebase.go 9.2 KB

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