server_firebase.go 9.3 KB

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