Debian Codegraph @

server/server_firebase.go

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