π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Send FCM pushes via the FCM HTTP v1 API
Manav Rathi9603fd7f1cd1
diff --git a/server/go.mod b/server/go.modindex 5f5b0a7b3c..5255f90a5d 100644--- a/server/go.mod+++ b/server/go.mod@@ -5,7 +5,6 @@ go 1.26.0toolchain go1.26.4require (- firebase.google.com/go v3.13.0+incompatiblegithub.com/TwiN/go-away v1.6.13github.com/avct/uasurfer v0.0.0-20191028135549-26b5daa857f1github.com/awa/go-iap v1.3.16@@ -46,7 +45,6 @@ require (require (cloud.google.com/go/compute/metadata v0.3.0 // indirect- cloud.google.com/go/longrunning v0.5.1 // indirectgithub.com/bytedance/sonic v1.9.1 // indirectgithub.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirectgithub.com/fxamacker/cbor/v2 v2.6.0 // indirect@@ -63,16 +61,10 @@ require (github.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/x448/float16 v0.8.4 // indirectgolang.org/x/arch v0.3.0 // indirect- golang.org/x/time v0.3.0 // indirect- google.golang.org/genproto/googleapis/api v0.0.0-20230711160842-782d3b101e98 // indirectgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect)require (- cloud.google.com/go v0.110.4 // indirect- cloud.google.com/go/firestore v1.11.0 // indirect- cloud.google.com/go/iam v1.1.1 // indirect- cloud.google.com/go/storage v1.30.1 // indirectgithub.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirectgithub.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d // indirectgithub.com/beorn7/perks v1.0.1 // indirect@@ -113,11 +105,9 @@ require (github.com/ugorji/go/codec v1.2.11 // indirectgo.opencensus.io v0.24.0 // indirectgolang.org/x/net v0.43.0- golang.org/x/oauth2 v0.27.0 // indirect+ golang.org/x/oauth2 v0.27.0golang.org/x/sys v0.35.0 // indirect- golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirectgoogle.golang.org/appengine v1.6.7 // indirect- google.golang.org/genproto v0.0.0-20230711160842-782d3b101e98 // indirectgoogle.golang.org/grpc v1.58.3 // indirectgoogle.golang.org/protobuf v1.31.0 // indirectgopkg.in/alecthomas/kingpin.v2 v2.2.6 // indirectdiff --git a/server/go.sum b/server/go.sumindex a82b803cd7..339f1d54be 100644--- a/server/go.sum+++ b/server/go.sum@@ -21,8 +21,6 @@ cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHcloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8=cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0=cloud.google.com/go v0.83.0/go.mod h1:Z7MJUsANfY0pYPdw0lbnivPx4/vhy/e2FEkSkF7vAVY=-cloud.google.com/go v0.110.4 h1:1JYyxKMN9hd5dR2MYTPWkGUgcoxVVhg0LKNKEo0qvmk=-cloud.google.com/go v0.110.4/go.mod h1:+EYjdK8e5RME/VY/qLCAtuyALQ9q67dvuum8i+H5xsI=cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE=cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc=@@ -34,12 +32,6 @@ cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hcloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk=cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk=-cloud.google.com/go/firestore v1.11.0 h1:PPgtwcYUOXV2jFe1bV3nda3RCrOa8cvBjTOn2MQVfW8=-cloud.google.com/go/firestore v1.11.0/go.mod h1:b38dKhgzlmNNGTNZZwe7ZRFEuRab1Hay3/DBsIGKKy4=-cloud.google.com/go/iam v1.1.1 h1:lW7fzj15aVIXYHREOqjRBV9PsH0Z6u8Y46a1YGvQP4Y=-cloud.google.com/go/iam v1.1.1/go.mod h1:A5avdyVL2tCppe4unb0951eI9jreack+RJ0/d+KUZOU=-cloud.google.com/go/longrunning v0.5.1 h1:Fr7TXftcqTudoyRJa113hyaqlGdiBQkp0Gq7tErFDWI=-cloud.google.com/go/longrunning v0.5.1/go.mod h1:spvimkwdz6SPWKEt/XBij79E9fiTkHSQl/fRUUQJYJc=cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw=cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA=@@ -50,11 +42,7 @@ cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0Zeocloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk=cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=-cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/oNM=-cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E=dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=-firebase.google.com/go v3.13.0+incompatible h1:3TdYC3DDi6aHn20qoRkxwGqNgdjtblwVAyRLQwGn/+4=-firebase.google.com/go v3.13.0+incompatible/go.mod h1:xlah6XbEyW6tbfSklcfe5FHJIwjt8toICdV5Wh9ptHs=github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 h1:w+iIsaOQNcT7OZ575w+acHgRric5iCyQh+xv+KJ4HB8=github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8=github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=@@ -292,13 +280,10 @@ github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUOgithub.com/google/go-tpm v0.9.0 h1:sQF6YqWMi+SCXpsmS3fd21oPy/vSddwZry4JnmltHVk=github.com/google/go-tpm v0.9.0/go.mod h1:FkNVkc6C+IsvDI9Jw1OveJmxGZUUaKxtrpOS47QWKfU=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=-github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no=github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=github.com/google/martian/v3 v3.2.1/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk=-github.com/google/martian/v3 v3.3.2 h1:IqNFLAmvJOgVlpdEBiQbDc2EwKW77amAycfTuWKdfvw=-github.com/google/martian/v3 v3.3.2/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk=github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=@@ -869,8 +854,6 @@ golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbgolang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=-golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=-golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=@@ -939,8 +922,6 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8Tgolang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=-golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk=-golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8=google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=diff --git a/server/pkg/controller/push.go b/server/pkg/controller/push.goindex e07a32c878..e67b67da37 100644--- a/server/pkg/controller/push.go+++ b/server/pkg/controller/push.go@@ -1,14 +1,18 @@package controllerimport (+ "bytes""context""encoding/json"- "errors""fmt"+ "io"+ "net/http"+ "os""strconv"+ "sync"+ "sync/atomic"+ gotime "time"- firebase "firebase.google.com/go"- "firebase.google.com/go/messaging""github.com/ente-io/museum/ente""github.com/ente-io/museum/pkg/repo""github.com/ente-io/museum/pkg/utils/config"@@ -16,15 +20,16 @@ import ("github.com/ente-io/stacktrace"log "github.com/sirupsen/logrus""github.com/spf13/viper"- "google.golang.org/api/option"+ "golang.org/x/oauth2"+ "golang.org/x/oauth2/google")// PushController controls all push related operationstype PushController struct {- PushRepo *repo.PushTokenRepository- TaskLockRepo *repo.TaskLockRepository- HostName string- FirebaseClient *messaging.Client+ PushRepo *repo.PushTokenRepository+ TaskLockRepo *repo.TaskLockRepository+ HostName string+ fcm *fcmClient}type PushToken struct {@@ -39,9 +44,11 @@ type PushToken struct {// Interval before which the last push was sentconst pushIntervalInMinutes = 60-// Limit defined by FirebaseClient.SendAll(...)+// Max number of devices to notify in a single run.const concurrentPushesInOneShot = 500+const fcmSendConcurrency = 10+const taskLockName = "fcm-push-lock"const taskLockDurationInMinutes = 5@@ -49,35 +56,49 @@ const taskLockDurationInMinutes = 5// As proposed by https://firebase.google.com/docs/cloud-messaging/manage-tokens#ensuring-registration-token-freshnessconst tokenExpiryDurationInDays = 61+const fcmSendScope = "https://www.googleapis.com/auth/firebase.messaging"++const fcmSendTimeout = 30 * gotime.Second+func NewPushController(pushRepo *repo.PushTokenRepository, taskLockRepo *repo.TaskLockRepository, hostName string) *PushController {- client, err := newFirebaseClient()+ client, err := newFCMClient()if err != nil {- log.Error(fmt.Errorf("error creating Firebase client: %v", err))+ log.Error(fmt.Errorf("error creating FCM client: %v", err))}- return &PushController{PushRepo: pushRepo, TaskLockRepo: taskLockRepo, HostName: hostName, FirebaseClient: client}+ return &PushController{PushRepo: pushRepo, TaskLockRepo: taskLockRepo, HostName: hostName, fcm: client}}-func newFirebaseClient() (*messaging.Client, error) {- firebaseCredentialsFile, err := config.CredentialFilePath("fcm-service-account.json")+// fcmClient sends pushes via the FCM HTTP v1 API directly. We avoid the Firebase+// Admin SDK because it pulls in the entire google.golang.org/api + Firestore ++// OpenTelemetry tree just to send a push.+type fcmClient struct {+ httpClient *http.Client+ projectID string+}++func newFCMClient() (*fcmClient, error) {+ credentialsFile, err := config.CredentialFilePath("fcm-service-account.json")if err != nil {return nil, stacktrace.Propagate(err, "")}- if firebaseCredentialsFile == "" {+ if credentialsFile == "" {// Can happen when running locallyreturn nil, nil}-- opt := option.WithCredentialsFile(firebaseCredentialsFile)- app, err := firebase.NewApp(context.Background(), nil, opt)+ data, err := os.ReadFile(credentialsFile)if err != nil {return nil, stacktrace.Propagate(err, "")}- client, err := app.Messaging(context.Background())+ creds, err := google.CredentialsFromJSON(context.Background(), data, fcmSendScope)if err != nil {return nil, stacktrace.Propagate(err, "")}-- return client, nil+ client := oauth2.NewClient(context.Background(), creds.TokenSource)+ client.Timeout = fcmSendTimeout+ return &fcmClient{+ httpClient: client,+ projectID: creds.ProjectID,+ }, nil}func (c *PushController) AddToken(userID int64, token ente.PushTokenRequest) error {@@ -141,48 +162,82 @@ func (c *PushController) updateLastNotificationTime(pushTokens []ente.PushToken)}func (c *PushController) sendFCMPushes(pushTokens []ente.PushToken, payload map[string]string) error {- firebaseClient := c.FirebaseClientsilent := viper.GetBool("internal.silent")- if silent || firebaseClient == nil {+ if silent || c.fcm == nil {if len(pushTokens) > 0 {log.Info("Skipping sending pushes to " + strconv.Itoa(len(pushTokens)) + " devices")}return nil}-- log.Info("Sending pushes to " + strconv.Itoa(len(pushTokens)) + " devices")if len(pushTokens) == 0 {return nil}- if len(pushTokens) > concurrentPushesInOneShot {- return errors.New("cannot send these many pushes in one shot")- }- marshal, _ := json.Marshal(pushTokens)- log.WithField("devices", string(marshal)).Info("push to following devices")- fcmTokens := make([]string, 0)- for _, pushTokenData := range pushTokens {- fcmTokens = append(fcmTokens, pushTokenData.FCMToken)- }-- message := &messaging.MulticastMessage{- Tokens: fcmTokens,- Data: payload,- Android: &messaging.AndroidConfig{Priority: "high"},- APNS: &messaging.APNSConfig{- Headers: map[string]string{- "apns-push-type": "background",- "apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.- "apns-topic": "io.ente.frame", // bundle identifier++ log.Info("Sending pushes to " + strconv.Itoa(len(pushTokens)) + " devices")+ var successCount, failureCount int64+ var lastErr atomic.Value+ var wg sync.WaitGroup+ sem := make(chan struct{}, fcmSendConcurrency)+ for _, pushToken := range pushTokens {+ wg.Add(1)+ sem <- struct{}{}+ go func(token string) {+ defer wg.Done()+ defer func() { <-sem }()+ if err := c.fcm.send(context.Background(), token, payload); err != nil {+ atomic.AddInt64(&failureCount, 1)+ lastErr.Store(err.Error())+ } else {+ atomic.AddInt64(&successCount, 1)+ }+ }(pushToken.FCMToken)+ }+ wg.Wait()++ if successCount == 0 && failureCount > 0 {+ msg, _ := lastErr.Load().(string)+ log.Error("Failed to send any pushes to " + strconv.FormatInt(failureCount, 10) ++ " devices; last error: " + msg)+ } else {+ log.Info("Send push result: success count: " + strconv.FormatInt(successCount, 10) ++ ", failure count: " + strconv.FormatInt(failureCount, 10))+ }+ return nil+}++func (c *fcmClient) send(ctx context.Context, token string, data map[string]string) error {+ body, err := json.Marshal(map[string]any{+ "message": map[string]any{+ "token": token,+ "data": data,+ "android": map[string]any{"priority": "high"},+ "apns": map[string]any{+ "headers": map[string]string{+ "apns-push-type": "background",+ "apns-priority": "5",+ "apns-topic": "io.ente.frame",+ },+ "payload": map[string]any{"aps": map[string]any{"content-available": 1}},},- Payload: &messaging.APNSPayload{Aps: &messaging.Aps{ContentAvailable: true}},},+ })+ if err != nil {+ return stacktrace.Propagate(err, "")}- result, err := firebaseClient.SendMulticast(context.Background(), message)+ url := fmt.Sprintf("https://fcm.googleapis.com/v1/projects/%s/messages:send", c.projectID)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))if err != nil {- return stacktrace.Propagate(err, "Error sending pushes")- } else {- log.Info("Send push result: success count: " + strconv.Itoa(result.SuccessCount) +- ", failure count: " + strconv.Itoa(result.FailureCount))- return nil+ return stacktrace.Propagate(err, "")+ }+ req.Header.Set("Content-Type", "application/json")+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ b, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))+ return fmt.Errorf("status %d: %s", resp.StatusCode, string(b))}+ return nil}diff --git a/server/pkg/controller/push_test.go b/server/pkg/controller/push_test.gonew file mode 100644index 0000000000..ddbe06df44--- /dev/null+++ b/server/pkg/controller/push_test.go@@ -0,0 +1,157 @@+package controller++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "strings"+ "sync/atomic"+ "testing"++ "github.com/ente-io/museum/ente"+ log "github.com/sirupsen/logrus"+ logtest "github.com/sirupsen/logrus/hooks/test"+ "github.com/stretchr/testify/require"+)++type roundTripFunc func(*http.Request) (*http.Response, error)++func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func jsonResponse(status int, body string) *http.Response {+ return &http.Response{+ StatusCode: status,+ Body: io.NopCloser(strings.NewReader(body)),+ Header: make(http.Header),+ }+}++// wireMsg mirrors the FCM HTTP v1 request body so tests can assert the exact+// JSON we put on the wire.+type wireMsg struct {+ Message struct {+ Token string `json:"token"`+ Data map[string]string `json:"data"`+ Android struct {+ Priority string `json:"priority"`+ } `json:"android"`+ APNS struct {+ Headers map[string]string `json:"headers"`+ Payload struct {+ Aps struct {+ ContentAvailable int `json:"content-available"`+ } `json:"aps"`+ } `json:"payload"`+ } `json:"apns"`+ } `json:"message"`+}++func TestFCMSendBuildsV1Request(t *testing.T) {+ var captured *http.Request+ var body []byte+ c := &fcmClient{+ projectID: "proj-123",+ httpClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ captured = r+ body, _ = io.ReadAll(r.Body)+ return jsonResponse(http.StatusOK, "{}"), nil+ })},+ }++ err := c.send(context.Background(), "device-token-abc", map[string]string{"action": "sync"})+ require.NoError(t, err)++ require.Equal(t, http.MethodPost, captured.Method)+ require.Equal(t, "https://fcm.googleapis.com/v1/projects/proj-123/messages:send", captured.URL.String())+ require.Equal(t, "application/json", captured.Header.Get("Content-Type"))++ var msg wireMsg+ require.NoError(t, json.Unmarshal(body, &msg))+ require.Equal(t, "device-token-abc", msg.Message.Token)+ require.Equal(t, map[string]string{"action": "sync"}, msg.Message.Data)+ require.Equal(t, "high", msg.Message.Android.Priority)+ require.Equal(t, map[string]string{+ "apns-push-type": "background",+ "apns-priority": "5",+ "apns-topic": "io.ente.frame",+ }, msg.Message.APNS.Headers)+ require.Equal(t, 1, msg.Message.APNS.Payload.Aps.ContentAvailable)+}++func TestFCMSendNon200ReturnsError(t *testing.T) {+ c := &fcmClient{+ projectID: "p",+ httpClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ return jsonResponse(http.StatusNotFound, `{"error":"not found"}`), nil+ })},+ }++ err := c.send(context.Background(), "tok", map[string]string{"action": "sync"})+ require.Error(t, err)+ require.Contains(t, err.Error(), "404")+}++func TestSendFCMPushesCountsResults(t *testing.T) {+ hook := captureLogs(t)+ var requests int64+ pc := &PushController{fcm: &fcmClient{+ projectID: "p",+ httpClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ atomic.AddInt64(&requests, 1)+ b, _ := io.ReadAll(r.Body)+ var m wireMsg+ _ = json.Unmarshal(b, &m)+ if strings.HasPrefix(m.Message.Token, "bad") {+ return jsonResponse(http.StatusBadRequest, `{"error":"bad"}`), nil+ }+ return jsonResponse(http.StatusOK, "{}"), nil+ })},+ }}++ tokens := []ente.PushToken{{FCMToken: "good-1"}, {FCMToken: "good-2"}, {FCMToken: "bad-3"}}+ require.NoError(t, pc.sendFCMPushes(tokens, map[string]string{"action": "sync"}))++ require.Equal(t, int64(3), atomic.LoadInt64(&requests))+ require.True(t, hasLog(hook, log.InfoLevel, "success count: 2, failure count: 1"))+ require.False(t, hasLog(hook, log.ErrorLevel, "Failed to send any pushes"))+}++func TestSendFCMPushesTotalFailureLogsError(t *testing.T) {+ hook := captureLogs(t)+ pc := &PushController{fcm: &fcmClient{+ projectID: "p",+ httpClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ return jsonResponse(http.StatusBadRequest, `{"error":"bad"}`), nil+ })},+ }}++ tokens := []ente.PushToken{{FCMToken: "a"}, {FCMToken: "b"}}+ require.NoError(t, pc.sendFCMPushes(tokens, map[string]string{"action": "sync"}))++ require.True(t, hasLog(hook, log.ErrorLevel, "Failed to send any pushes to 2 devices"))+}++func captureLogs(t *testing.T) *logtest.Hook {+ t.Helper()+ logger := log.StandardLogger()+ origHooks := logger.ReplaceHooks(make(log.LevelHooks))+ origOut := logger.Out+ logger.SetOutput(io.Discard)+ hook := logtest.NewGlobal()+ t.Cleanup(func() {+ logger.ReplaceHooks(origHooks)+ logger.SetOutput(origOut)+ hook.Reset()+ })+ return hook+}++func hasLog(hook *logtest.Hook, level log.Level, substr string) bool {+ for _, e := range hook.AllEntries() {+ if e.Level == level && strings.Contains(e.Message, substr) {+ return true+ }+ }+ return false+}