π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add encrypted album-share pushes for internal iOS users
AmanRajSinghMourya7479716565ae
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 5ff35b710e..3297b4dbfa 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -406,6 +406,7 @@ func main() {collectionController := &collections.CollectionController{CollectionRepo: collectionRepo,EmailCtrl: emailNotificationCtrl,+ PushCtrl: pushController,AccessCtrl: accessCtrl,CollectionLinkCtrl: collectionLinkCtrl,UserRepo: userRepo,diff --git a/server/ente/push.go b/server/ente/push.goindex 31f77fd0f8..390a186680 100644--- a/server/ente/push.go+++ b/server/ente/push.go@@ -6,16 +6,24 @@ import ()type PushTokenRequest struct {- FCMToken string `json:"fcmToken" binding:"required"`- APNSToken string `json:"apnsToken"`+ FCMToken string `json:"fcmToken" binding:"required"`+ APNSToken string `json:"apnsToken"`+ Platform *string `json:"platform" binding:"required,oneof=ios android"`+ Notification *PushNotificationRegistration `json:"notification"`LastNotificationTime int64}+type PushNotificationRegistration struct {+ Version int `json:"version" binding:"required,eq=1"`+ PublicKey []byte `json:"publicKey" binding:"required,len=32"`+}+type PushToken struct {- UserID int64 `json:"userID"`- FCMToken string `json:"fcmToken"`- CreatedAt int64 `json:"createdAt"`- LastNotifiedAt int64 `json:"lastNotifiedAt"`+ UserID int64 `json:"userID"`+ FCMToken string `json:"fcmToken"`+ CreatedAt int64 `json:"createdAt"`+ LastNotifiedAt int64 `json:"lastNotifiedAt"`+ NotificationPublicKey []byte `json:"-"`}func (pt *PushToken) MarshalJSON() ([]byte, error) {diff --git a/server/migrations/150_push_notification_registration.down.sql b/server/migrations/150_push_notification_registration.down.sqlnew file mode 100644index 0000000000..5f58086181--- /dev/null+++ b/server/migrations/150_push_notification_registration.down.sql@@ -0,0 +1,3 @@+ALTER TABLE push_tokens+ DROP COLUMN notification_public_key,+ DROP COLUMN platform;diff --git a/server/migrations/150_push_notification_registration.up.sql b/server/migrations/150_push_notification_registration.up.sqlnew file mode 100644index 0000000000..e8bc28b6a1--- /dev/null+++ b/server/migrations/150_push_notification_registration.up.sql@@ -0,0 +1,3 @@+ALTER TABLE push_tokens+ ADD COLUMN platform TEXT NOT NULL DEFAULT 'ios' CHECK (platform IN ('ios', 'android')),+ ADD COLUMN notification_public_key BYTEA CHECK (octet_length(notification_public_key) = 32);diff --git a/server/pkg/api/push.go b/server/pkg/api/push.goindex 30772d344d..63919466f7 100644--- a/server/pkg/api/push.go+++ b/server/pkg/api/push.go@@ -16,7 +16,8 @@ type PushHandler struct {}func (h *PushHandler) AddToken(c *gin.Context) {- var req ente.PushTokenRequest+ platform := "ios"+ req := ente.PushTokenRequest{Platform: &platform}err := handler.BindJSON(c, &req)if err != nil {handler.Error(c, stacktrace.Propagate(err, ""))diff --git a/server/pkg/api/push_test.go b/server/pkg/api/push_test.goindex bedf12f255..d8c13428a7 100644--- a/server/pkg/api/push_test.go+++ b/server/pkg/api/push_test.go@@ -1,7 +1,9 @@package apiimport (+ "crypto/rand""encoding/base64"+ "encoding/json""fmt""net/http""net/http/httptest"@@ -15,6 +17,7 @@ import ("github.com/ente/museum/pkg/utils/auth""github.com/gin-gonic/gin""github.com/stretchr/testify/require"+ "golang.org/x/crypto/nacl/box")func TestPushRegistrationBindsRequestSession(t *testing.T) {@@ -63,3 +66,116 @@ func TestPushRegistrationBindsRequestSession(t *testing.T) {expected := auth.HashToken("session-2")require.Equal(t, expected[:], hash)}++func TestPushRegistrationRejectsInvalidNotificationEnrollment(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() { testutil.ResetTables(t, db) })+ testutil.InsertUser(t, db, testutil.UserFixture{UserID: 1, Email: "[email protected]", CreationTime: 1})+ require.NoError(t, (&repo.UserAuthRepository{DB: db}).AddToken(1, ente.Photos, "session", "", ""))+ router := gin.New()+ handler := PushHandler{PushController: &controller.PushController{PushRepo: &repo.PushTokenRepository{DB: db}}}+ router.POST("/push/token", handler.AddToken)+ key := base64.StdEncoding.EncodeToString(append([]byte{9}, make([]byte, 31)...))+ for _, fields := range []string{+ `"platform":"web"`,+ `"platform":null`,+ `"notification":{}`,+ fmt.Sprintf(`"notification":{"version":2,"publicKey":"%s"}`, key),+ `"notification":{"version":1,"publicKey":"invalid"}`,+ `"notification":{"version":1,"publicKey":"AQ=="}`,+ fmt.Sprintf(`"notification":{"version":1,"publicKey":"%s"}`, base64.StdEncoding.EncodeToString(make([]byte, 32))),+ fmt.Sprintf(`"platform":"android","notification":{"version":1,"publicKey":"%s"}`, key),+ } {+ t.Run(fields, func(t *testing.T) {+ request := httptest.NewRequest(http.MethodPost, "/push/token", strings.NewReader(`{"fcmToken":"device",`+fields+`}`))+ request.Header.Set("Content-Type", "application/json")+ request.Header.Set("X-Auth-User-ID", "1")+ request.Header.Set("X-Auth-Token", "session")+ response := httptest.NewRecorder()+ router.ServeHTTP(response, request)+ require.Equal(t, http.StatusBadRequest, response.Code, response.Body.String())+ })+ }+ var count int+ require.NoError(t, db.QueryRow(`SELECT count(*) FROM push_tokens`).Scan(&count))+ require.Zero(t, count)+}++func TestPushNotificationRegistrationLifecycle(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() { testutil.ResetTables(t, db) })+ authRepo := &repo.UserAuthRepository{DB: db}+ for _, id := range []int64{1, 2} {+ testutil.InsertUser(t, db, testutil.UserFixture{UserID: id, Email: fmt.Sprintf("user%[email protected]", id), CreationTime: 1})+ require.NoError(t, authRepo.AddToken(id, ente.Photos, fmt.Sprintf("session-%d", id), "", ""))+ }+ firstKey, _, err := box.GenerateKey(rand.Reader)+ require.NoError(t, err)+ secondKey, _, err := box.GenerateKey(rand.Reader)+ require.NoError(t, err)+ router := gin.New()+ handler := PushHandler{PushController: &controller.PushController{PushRepo: &repo.PushTokenRepository{DB: db}}}+ router.POST("/push/token", handler.AddToken)+ for _, tc := range []struct {+ name string+ userID int64+ platform string+ key []byte+ omit bool+ }{+ {"old client", 1, "", nil, true},+ {"enroll", 1, "ios", firstKey[:], false},+ {"replace key", 1, "ios", secondKey[:], false},+ {"unenroll", 1, "ios", nil, false},+ {"enroll again", 1, "ios", firstKey[:], false},+ {"switch account", 2, "ios", secondKey[:], false},+ {"omitted enrollment clears key", 2, "android", nil, true},+ {"enroll before logout", 2, "ios", secondKey[:], false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ body := map[string]any{"fcmToken": "device", "apnsToken": "apns"}+ if tc.platform != "" {+ body["platform"] = tc.platform+ }+ if !tc.omit {+ body["notification"] = nil+ if tc.key != nil {+ body["notification"] = map[string]any{"version": 1, "publicKey": tc.key}+ }+ }+ encoded, err := json.Marshal(body)+ require.NoError(t, err)+ request := httptest.NewRequest(http.MethodPost, "/push/token", strings.NewReader(string(encoded)))+ request.Header.Set("Content-Type", "application/json")+ request.Header.Set("X-Auth-User-ID", fmt.Sprint(tc.userID))+ session := fmt.Sprintf("session-%d", tc.userID)+ request.Header.Set("X-Auth-Token", session)+ response := httptest.NewRecorder()+ router.ServeHTTP(response, request)+ require.Equal(t, http.StatusOK, response.Code, response.Body.String())+ var userID int64+ var platform string+ var key, hash []byte+ require.NoError(t, db.QueryRow(`SELECT user_id, platform, notification_public_key, session_token_hash FROM push_tokens WHERE fcm_token='device'`).Scan(&userID, &platform, &key, &hash))+ require.Equal(t, tc.userID, userID)+ wantPlatform := tc.platform+ if wantPlatform == "" {+ wantPlatform = "ios"+ }+ require.Equal(t, wantPlatform, platform)+ require.Equal(t, tc.key, key)+ expected := auth.HashToken(session)+ require.Equal(t, expected[:], hash)+ })+ }+ hash := auth.HashToken("session-2")+ _, err = authRepo.RemoveTokenByHash(2, hash[:])+ require.NoError(t, err)+ var count int+ require.NoError(t, db.QueryRow(`SELECT count(*) FROM push_tokens`).Scan(&count))+ require.Zero(t, count)+}diff --git a/server/pkg/controller/collections/collection.go b/server/pkg/controller/collections/collection.goindex 9f888bbc87..795e0b8286 100644--- a/server/pkg/controller/collections/collection.go+++ b/server/pkg/controller/collections/collection.go@@ -25,9 +25,14 @@ const (CollectionDiffLimit = 2500)+type CollectionPushNotifier interface {+ NotifyAlbumShare(ctx context.Context, recipients []int64)+}+type CollectionController struct {CollectionLinkCtrl *public.CollectionLinkControllerEmailCtrl *email.EmailNotificationController+ PushCtrl CollectionPushNotifierAccessCtrl access.ControllerBillingCtrl *controller.BillingControllerUserLookup controller.UserLookupdiff --git a/server/pkg/controller/collections/share.go b/server/pkg/controller/collections/share.goindex 95c456a89f..ab0a4ea6c6 100644--- a/server/pkg/controller/collections/share.go+++ b/server/pkg/controller/collections/share.go@@ -44,7 +44,7 @@ func (c *CollectionController) Share(ctx *gin.Context, req ente.AlterShareRequesif err := validateShareRecipient(fromUserID, collection.Owner.ID, toUserID); err != nil {return nil, err}- err = c.CollectionRepo.Share(+ added, err := c.CollectionRepo.Share(req.CollectionID,collection.Owner.ID,toUserID,@@ -55,6 +55,9 @@ func (c *CollectionController) Share(ctx *gin.Context, req ente.AlterShareRequesif err != nil {return nil, stacktrace.Propagate(err, "")}+ if added && collection.App == string(ente.Photos) {+ go c.PushCtrl.NotifyAlbumShare(ctx.Request.Context(), []int64{toUserID})+ }sharees, err := c.GetSharees(ctx, req.CollectionID, fromUserID)if err != nil {return nil, stacktrace.Propagate(err, "")@@ -104,7 +107,7 @@ func (c *CollectionController) BatchShare(ctx *gin.Context, shares []ente.AlterS})}- err = c.CollectionRepo.BatchShare(+ added, err := c.CollectionRepo.BatchShare(ctx.Request.Context(),collection.ID,collection.Owner.ID,@@ -114,6 +117,9 @@ func (c *CollectionController) BatchShare(ctx *gin.Context, shares []ente.AlterSif err != nil {return nil, stacktrace.Propagate(err, "")}+ if len(added) > 0 && collection.App == string(ente.Photos) {+ go c.PushCtrl.NotifyAlbumShare(ctx.Request.Context(), added)+ }sharees, err := c.GetSharees(ctx, collection.ID, fromUserID)if err != nil {return nil, stacktrace.Propagate(err, "")@@ -178,9 +184,10 @@ func (c *CollectionController) BulkShare(}}+ notify := falseresults := make([]ente.BulkCollectionShareResult, 0, len(req.Collections))for _, item := range req.Collections {- status, err := c.shareCollectionWithUserID(+ status, addedShare, err := c.shareCollectionWithUserID(ctx,fromUserID,req.RecipientUserID,@@ -195,11 +202,15 @@ func (c *CollectionController) BulkShare(}).Warn("bulk collection share failed")status = ente.CollectionShareOperationFailed}+ notify = notify || (err == nil && addedShare)results = append(results, ente.BulkCollectionShareResult{CollectionID: item.CollectionID,Status: status,})}+ if notify {+ go c.PushCtrl.NotifyAlbumShare(ctx.Request.Context(), []int64{req.RecipientUserID})+ }return results, nil}@@ -219,19 +230,19 @@ func (c *CollectionController) shareCollectionWithUserID(toUserID int64,source ente.CollectionShareSource,item ente.BulkCollectionShareItem,-) (ente.CollectionShareStatus, error) {+) (ente.CollectionShareStatus, bool, error) {if err := validateSealedCollectionKey(item.EncryptedKey); err != nil {- return "", err+ return "", false, err}collection, err := c.collectionForShareMutation(item.CollectionID, fromUserID)if err != nil {- return "", err+ return "", false, err}if source == ente.AutomaticShare && fromUserID != collection.Owner.ID {- return "", stacktrace.Propagate(ente.ErrPermissionDenied, "")+ return "", false, stacktrace.Propagate(ente.ErrPermissionDenied, "")}if !collection.AllowParticipantSharing(item.Role) {- return "", stacktrace.Propagate(+ return "", false, stacktrace.Propagate(ente.ErrBadRequest,"sharing %s as %s is not allowed",collection.Type,@@ -239,11 +250,11 @@ func (c *CollectionController) shareCollectionWithUserID()}if err := validateShareRecipient(fromUserID, collection.Owner.ID, toUserID); err != nil {- return "", err+ return "", false, err}updationTime := time.Microseconds()if source == ente.ManualShare {- err := c.CollectionRepo.Share(+ added, err := c.CollectionRepo.Share(item.CollectionID,collection.Owner.ID,toUserID,@@ -251,9 +262,9 @@ func (c *CollectionController) shareCollectionWithUserID(item.Role,updationTime,)- return ente.CollectionShared, err+ return ente.CollectionShared, added && collection.App == string(ente.Photos), err}- return c.CollectionRepo.ShareAutomatically(+ status, err := c.CollectionRepo.ShareAutomatically(ctx,item.CollectionID,collection.Owner.ID,@@ -262,6 +273,7 @@ func (c *CollectionController) shareCollectionWithUserID(item.Role,updationTime,)+ return status, false, err}func (c *CollectionController) collectionForShareMutation(@@ -361,7 +373,7 @@ func (c *CollectionController) JoinViaLink(ctx *gin.Context, req ente.JoinCollecif collectionLinkToken.EnableCollect {role = ente.COLLABORATOR}- joinErr := c.CollectionRepo.Share(req.CollectionID, collection.Owner.ID, userID, req.EncryptedKey, role, time.Microseconds())+ _, joinErr := c.CollectionRepo.Share(req.CollectionID, collection.Owner.ID, userID, req.EncryptedKey, role, time.Microseconds())if joinErr != nil {return stacktrace.Propagate(joinErr, "")}diff --git a/server/pkg/controller/collections/share_test.go b/server/pkg/controller/collections/share_test.goindex 38dc4252f6..d50ac43b95 100644--- a/server/pkg/controller/collections/share_test.go+++ b/server/pkg/controller/collections/share_test.go@@ -6,7 +6,10 @@ import ("errors""net/http/httptest""strconv"+ "sync"+ "sync/atomic""testing"+ "time""github.com/ente/museum/ente""github.com/ente/museum/internal/testutil"@@ -16,6 +19,8 @@ import (castRepo "github.com/ente/museum/pkg/repo/cast"publicRepo "github.com/ente/museum/pkg/repo/public""github.com/gin-gonic/gin"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require")type panicUserLookup struct{}@@ -116,6 +121,7 @@ func newBatchShareTestController(collectionRepo *repo.CollectionRepository,) *CollectionController {return &CollectionController{+ PushCtrl: &museumcontroller.PushController{},AccessCtrl: access.NewAccessController(collectionRepo, nil),CollectionRepo: collectionRepo,UserLookup: newShareTestUserLookup(db),@@ -183,7 +189,7 @@ func addShareTestShare(role ente.CollectionParticipantRole,) {t.Helper()- if err := collectionRepo.Share(collectionID, ownerID, shareeID, "share-key", role, 1); err != nil {+ if _, err := collectionRepo.Share(collectionID, ownerID, shareeID, "share-key", role, 1); err != nil {t.Fatal(err)}}@@ -363,7 +369,7 @@ func TestAutomaticShareLifecycle(t *testing.T) {ctx := context.Background()manualCollectionID := createShareTestCollection(t, collectionRepo, ownerID)- if err := collectionRepo.Share(+ if _, err := collectionRepo.Share(manualCollectionID,ownerID,shareeID,@@ -438,7 +444,7 @@ func TestUnShareContextBumpsCollectionForDeletedShareRow(t *testing.T) {db, collectionRepo, ownerID, shareeID := setupCollectionShareTest(t)ctx := context.Background()collectionID := createShareTestCollection(t, collectionRepo, ownerID)- if err := collectionRepo.Share(+ if _, err := collectionRepo.Share(collectionID,ownerID,shareeID,@@ -480,7 +486,7 @@ func TestUncategorizedCollectionsOnlyAllowViewerShares(t *testing.T) {Role: ente.VIEWER,}- status, err := controller.shareCollectionWithUserID(+ status, _, err := controller.shareCollectionWithUserID(context.Background(),ownerID,shareeID,@@ -490,7 +496,7 @@ func TestUncategorizedCollectionsOnlyAllowViewerShares(t *testing.T) {requireCollectionShareStatus(t, status, ente.CollectionShared, err)item.Role = ente.ADMIN- _, err = controller.shareCollectionWithUserID(+ _, _, err = controller.shareCollectionWithUserID(context.Background(),ownerID,shareeID,@@ -567,6 +573,7 @@ func TestBulkShareAndUnshareReturnPerCollectionStatuses(t *testing.T) {func TestBulkShareAutomaticRecipientMustBeInSameFamily(t *testing.T) {db, collectionRepo, ownerID, shareeID := setupCollectionShareTest(t)controller := &CollectionController{+ PushCtrl: &museumcontroller.PushController{},CollectionRepo: collectionRepo,UserRepo: &repo.UserRepository{DB: db},UserLookup: newShareTestUserLookup(db),@@ -780,7 +787,7 @@ func TestBatchShareRollsBackWhenAnyWriteFails(t *testing.T) {collectionID := createShareTestCollection(t, collectionRepo, ownerID)originalCollectionTime := collectionUpdationTime(t, db, collectionID)- err := collectionRepo.BatchShare(+ _, err := collectionRepo.BatchShare(context.Background(),collectionID,ownerID,@@ -829,7 +836,7 @@ func TestBatchShareRejectsDeletedCollection(t *testing.T) {t.Fatalf("unauthorized BatchShare() error = %v, want %v", err, ente.ErrPermissionDenied)}- err = collectionRepo.BatchShare(+ _, err = collectionRepo.BatchShare(context.Background(),collectionID,ownerID,@@ -941,3 +948,229 @@ func TestBatchShareRejectsOversizedBatch(t *testing.T) {t.Fatalf("oversized share batch error = %v, want %v", err, ente.ErrBatchSizeTooLarge)}}++type albumSharePushFunc func(context.Context, []int64)++func (f albumSharePushFunc) NotifyAlbumShare(ctx context.Context, recipients []int64) {+ f(ctx, recipients)+}++func TestAlbumShareNotifiesOnlyNewAccess(t *testing.T) {+ db, r, owner, recipient := setupCollectionShareTest(t)+ c := newBatchShareTestController(db, r)+ id := createShareTestCollection(t, r, owner)+ notifications := make(chan []int64, 4)+ c.PushCtrl = albumSharePushFunc(func(ctx context.Context, users []int64) {+ _, pooledContext := ctx.(*gin.Context)+ assert.False(t, pooledContext)+ var active bool+ assert.NoError(t, db.QueryRow(`SELECT NOT is_deleted FROM collection_shares WHERE collection_id=$1 AND to_user_id=$2`, id, recipient).Scan(&active))+ assert.True(t, active, "notification must run after commit")+ notifications <- users+ })+ request := ente.AlterShareRequest{CollectionID: id, Email: "[email protected]", EncryptedKey: b64OfLen(sealedCollectionKeyLen)}+ _, err := c.Share(newBatchShareTestContext(owner), request)+ require.NoError(t, err)+ require.Eventually(t, func() bool { return len(notifications) == 1 }, time.Second, time.Millisecond)+ require.Equal(t, []int64{recipient}, <-notifications)+ _, err = c.BatchShare(newBatchShareTestContext(owner), []ente.AlterShareRequest{request})+ require.NoError(t, err)+ role := ente.COLLABORATOR+ request.Role = &role+ _, err = c.Share(newBatchShareTestContext(owner), request)+ require.NoError(t, err)+ require.Never(t, func() bool { return len(notifications) > 0 }, 50*time.Millisecond, time.Millisecond, "retry and role change must not notify")+ var storedRole ente.CollectionParticipantRole+ var deleted bool+ var encryptedKey string+ require.NoError(t, db.QueryRow(`SELECT role_type, is_deleted, encrypted_key FROM collection_shares WHERE collection_id=$1 AND to_user_id=$2`, id, recipient).Scan(&storedRole, &deleted, &encryptedKey))+ require.Equal(t, role, storedRole)+ require.False(t, deleted)+ require.Equal(t, request.EncryptedKey, encryptedKey)+ require.NoError(t, r.UnShare(id, recipient))+ _, err = c.BatchShare(newBatchShareTestContext(owner), []ente.AlterShareRequest{request})+ require.NoError(t, err)+ require.Eventually(t, func() bool { return len(notifications) == 1 }, time.Second, time.Millisecond)+ require.Equal(t, []int64{recipient}, <-notifications, "restored access should notify")+ _, err = db.Exec(`UPDATE collection_shares SET is_deleted = NULL WHERE collection_id=$1 AND to_user_id=$2`, id, recipient)+ require.NoError(t, err)+ _, err = c.Share(newBatchShareTestContext(owner), request)+ require.NoError(t, err)+ require.Eventually(t, func() bool { return len(notifications) == 1 }, time.Second, time.Millisecond)+ require.Equal(t, []int64{recipient}, <-notifications, "re-sharing should repair a null deletion flag")+ request.EncryptedKey = "invalid"+ _, err = c.Share(newBatchShareTestContext(owner), request)+ require.Error(t, err)+ require.Never(t, func() bool { return len(notifications) > 0 }, 50*time.Millisecond, time.Millisecond)+ require.NoError(t, r.UnShare(id, recipient))+ _, err = db.Exec(`UPDATE collections SET is_deleted = TRUE WHERE collection_id = $1`, id)+ require.NoError(t, err)+ request.EncryptedKey = b64OfLen(sealedCollectionKeyLen)+ _, err = c.Share(newBatchShareTestContext(owner), request)+ require.ErrorIs(t, err, ente.ErrCollectionDeleted)+ require.Never(t, func() bool { return len(notifications) > 0 }, 50*time.Millisecond, time.Millisecond)+ require.NoError(t, db.QueryRow(`SELECT is_deleted FROM collection_shares WHERE collection_id=$1 AND to_user_id=$2`, id, recipient).Scan(&deleted))+ require.True(t, deleted, "failed share must roll back restored access")+}++func TestBatchShareNotifiesOnlyNewRecipient(t *testing.T) {+ db, r, owner, existingRecipient := setupCollectionShareTest(t)+ newRecipient := testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: 3, Email: "[email protected]", CreationTime: 1,+ })+ id := createShareTestCollection(t, r, owner)+ addShareTestShare(t, r, id, owner, existingRecipient, ente.VIEWER)+ c := newBatchShareTestController(db, r)+ notifications := make(chan []int64, 1)+ c.PushCtrl = albumSharePushFunc(func(_ context.Context, recipients []int64) {+ notifications <- recipients+ })+ admin, collaborator := ente.ADMIN, ente.COLLABORATOR+ sharees, err := c.BatchShare(newBatchShareTestContext(owner), []ente.AlterShareRequest{+ {CollectionID: id, Email: "[email protected]", EncryptedKey: b64OfLen(sealedCollectionKeyLen), Role: &admin},+ {CollectionID: id, Email: "[email protected]", EncryptedKey: b64OfLen(sealedCollectionKeyLen), Role: &collaborator},+ })+ require.NoError(t, err)+ require.Len(t, sharees, 2)+ roles := make(map[int64]ente.CollectionParticipantRole)+ for _, sharee := range sharees {+ roles[sharee.ID] = sharee.Role+ }+ require.Equal(t, ente.ADMIN, roles[existingRecipient])+ require.Equal(t, ente.COLLABORATOR, roles[newRecipient])+ select {+ case recipients := <-notifications:+ require.Equal(t, []int64{newRecipient}, recipients)+ case <-time.After(time.Second):+ t.Fatal("new recipient was not notified")+ }+}++func TestConcurrentAlbumShareGrantsAccessOnce(t *testing.T) {+ _, r, owner, recipient := setupCollectionShareTest(t)+ id := createShareTestCollection(t, r, owner)+ var count atomic.Int32+ var wg sync.WaitGroup+ for range 8 {+ wg.Go(func() {+ added, err := r.BatchShare(context.Background(), id, owner, []repo.CollectionShareItem{{ToUserID: recipient, EncryptedKey: "test-key", Role: ente.VIEWER}}, 2)+ if err != nil {+ t.Error(err)+ return+ }+ count.Add(int32(len(added)))+ })+ }+ wg.Wait()+ require.EqualValues(t, 1, count.Load())+}++func TestBulkAlbumShareNotifiesOnceAfterAllMutations(t *testing.T) {+ db, r, owner, recipient := setupCollectionShareTest(t)+ c := newBatchShareTestController(db, r)+ request := ente.BulkCollectionShareRequest{RecipientUserID: recipient, RecipientEmail: "[email protected]", Source: ente.ManualShare}+ for range 2 {+ request.Collections = append(request.Collections, ente.BulkCollectionShareItem{CollectionID: createShareTestCollection(t, r, owner), EncryptedKey: b64OfLen(sealedCollectionKeyLen), Role: ente.VIEWER})+ }+ var calls atomic.Int32+ c.PushCtrl = albumSharePushFunc(func(_ context.Context, _ []int64) {+ for _, item := range request.Collections {+ var count int+ assert.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM collection_shares WHERE collection_id=$1`, item.CollectionID).Scan(&count))+ assert.Equal(t, 1, count)+ }+ calls.Add(1)+ })+ for range 2 {+ _, err := c.BulkShare(newBatchShareTestContext(owner), request)+ require.NoError(t, err)+ }+ require.Eventually(t, func() bool { return calls.Load() == 1 }, time.Second, time.Millisecond)+ require.Never(t, func() bool { return calls.Load() > 1 }, 50*time.Millisecond, time.Millisecond)+}++func TestAlbumSharePushEligibility(t *testing.T) {+ db, r, owner, recipient := setupCollectionShareTest(t)+ c := newBatchShareTestController(db, r)+ var calls atomic.Int32+ var expected int32+ c.PushCtrl = albumSharePushFunc(func(context.Context, []int64) { calls.Add(1) })+ for _, collection := range []ente.Collection{+ {Type: "album", App: string(ente.Photos)},+ {Type: "album", App: string(ente.Locker)},+ {Type: "folder", App: string(ente.Photos)},+ {Type: "favorites", App: string(ente.Photos)},+ {Type: "uncategorized", App: string(ente.Photos)},+ } {+ id := createShareTestCollection(t, r, owner)+ _, err := db.Exec(`UPDATE collections SET type=$2, app=$3 WHERE collection_id=$1`, id, collection.Type, collection.App)+ require.NoError(t, err)+ for _, flow := range []string{"single", "batch", "bulk"} {+ request := ente.AlterShareRequest{CollectionID: id, Email: "[email protected]", EncryptedKey: b64OfLen(sealedCollectionKeyLen)}+ switch flow {+ case "single":+ _, err = c.Share(newBatchShareTestContext(owner), request)+ case "batch":+ _, err = c.BatchShare(newBatchShareTestContext(owner), []ente.AlterShareRequest{request})+ case "bulk":+ _, err = c.BulkShare(newBatchShareTestContext(owner), ente.BulkCollectionShareRequest{+ RecipientUserID: recipient, RecipientEmail: request.Email, Source: ente.ManualShare,+ Collections: []ente.BulkCollectionShareItem{{CollectionID: id, EncryptedKey: request.EncryptedKey, Role: ente.VIEWER}},+ })+ }+ require.NoError(t, err)+ require.Equal(t, 1, collectionShareCount(t, db, id))+ require.NoError(t, r.UnShare(id, recipient))+ }+ if collection.App == string(ente.Photos) {+ expected += 3+ require.Eventually(t, func() bool { return calls.Load() == expected }, time.Second, time.Millisecond)+ }+ }+ require.Never(t, func() bool { return calls.Load() > expected }, 50*time.Millisecond, time.Millisecond)+}++func TestAlbumShareDoesNotWaitForPush(t *testing.T) {+ for _, flow := range []string{"single", "batch", "bulk"} {+ t.Run(flow, func(t *testing.T) {+ db, r, owner, recipient := setupCollectionShareTest(t)+ c := newBatchShareTestController(db, r)+ id := createShareTestCollection(t, r, owner)+ request := ente.AlterShareRequest{CollectionID: id, Email: "[email protected]", EncryptedKey: b64OfLen(sealedCollectionKeyLen)}+ started := make(chan struct{})+ release := make(chan struct{})+ returned := make(chan struct{})+ c.PushCtrl = albumSharePushFunc(func(context.Context, []int64) {+ close(started)+ <-release+ })+ t.Cleanup(func() { close(release); <-returned })+ var err error+ go func() {+ switch flow {+ case "single":+ _, err = c.Share(newBatchShareTestContext(owner), request)+ case "batch":+ _, err = c.BatchShare(newBatchShareTestContext(owner), []ente.AlterShareRequest{request})+ case "bulk":+ _, err = c.BulkShare(newBatchShareTestContext(owner), ente.BulkCollectionShareRequest{+ RecipientUserID: recipient, RecipientEmail: request.Email, Source: ente.ManualShare,+ Collections: []ente.BulkCollectionShareItem{{CollectionID: id, EncryptedKey: request.EncryptedKey, Role: ente.VIEWER}},+ })+ }+ close(returned)+ }()+ select {+ case <-returned:+ require.NoError(t, err)+ case <-time.After(5 * time.Second):+ t.Fatal("sharing must return while push delivery is blocked")+ }+ select {+ case <-started:+ case <-time.After(time.Second):+ t.Fatal("push delivery was not started")+ }+ })+ }+}diff --git a/server/pkg/controller/push.go b/server/pkg/controller/push.goindex ee779f63ba..22c9adf397 100644--- a/server/pkg/controller/push.go+++ b/server/pkg/controller/push.go@@ -3,6 +3,8 @@ package controllerimport ("bytes""context"+ "crypto/rand"+ "encoding/base64""encoding/json""errors""fmt"@@ -17,10 +19,12 @@ import ("github.com/ente/museum/ente""github.com/ente/museum/pkg/repo""github.com/ente/museum/pkg/utils/config"+ "github.com/ente/museum/pkg/utils/crypto""github.com/ente/museum/pkg/utils/time""github.com/ente/stacktrace"log "github.com/sirupsen/logrus""github.com/spf13/viper"+ "golang.org/x/crypto/nacl/box""golang.org/x/oauth2""golang.org/x/oauth2/google")@@ -100,9 +104,60 @@ func newFCMClient() (*fcmClient, error) {}func (c *PushController) AddToken(userID int64, sessionTokenHash []byte, token ente.PushTokenRequest) error {+ if token.Notification != nil {+ if *token.Platform != "ios" {+ return ente.NewBadRequestWithMessage("notification enrollment is only supported on iOS")+ }+ if err := crypto.ValidateSealedBoxPublicKey(base64.StdEncoding.EncodeToString(token.Notification.PublicKey)); err != nil {+ return ente.NewBadRequestWithMessage("invalid notification public key")+ }+ }return stacktrace.Propagate(c.PushRepo.AddToken(userID, sessionTokenHash, token), "")}+func (c *PushController) NotifyAlbumShare(ctx context.Context, recipients []int64) {+ if viper.GetBool("internal.silent") || c.fcm == nil || len(recipients) == 0 {+ return+ }+ ctx = context.WithoutCancel(ctx)+ lookupCtx, cancel := context.WithTimeout(ctx, 5*gotime.Second)+ tokens, err := c.PushRepo.GetTokensForAlbumShare(lookupCtx, recipients)+ cancel()+ if err != nil {+ log.WithError(err).Warn("album share push token lookup failed")+ return+ }+ for _, token := range tokens {+ ciphertext, err := box.SealAnonymous(nil, []byte(`{"version":1,"eventType":"album_shared"}`), (*[32]byte)(token.NotificationPublicKey), rand.Reader)+ if err != nil {+ log.WithError(err).Warn("album share notification encryption failed")+ continue+ }+ err = c.fcm.sendMessage(ctx, map[string]any{+ "token": token.FCMToken,+ "apns": map[string]any{+ "headers": map[string]string{+ "apns-push-type": "alert",+ "apns-priority": "10",+ "apns-expiration": strconv.FormatInt(gotime.Now().Add(24*gotime.Hour).Unix(), 10),+ },+ "payload": map[string]any{+ "aps": map[string]any{+ "alert": map[string]string{"title": "Ente Photos", "body": "New activity"},+ "mutable-content": 1,+ "sound": "default",+ },+ "notificationVersion": 1,+ "notificationCiphertext": base64.StdEncoding.EncodeToString(ciphertext),+ },+ },+ })+ if err != nil {+ log.WithError(err).Warn("album share push failed; album remains shared")+ }+ }+}+func (c *PushController) RemoveTokensForUser(userID int64) error {return stacktrace.Propagate(c.PushRepo.RemoveTokensForUser(userID), "")}@@ -224,21 +279,23 @@ func (c *PushController) pruneTokens(fcmTokens []string) {}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}},+ return c.sendMessage(ctx, 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}},},})+}++func (c *fcmClient) sendMessage(ctx context.Context, message map[string]any) error {+ body, err := json.Marshal(map[string]any{"message": message})if err != nil {return stacktrace.Propagate(err, "")}diff --git a/server/pkg/controller/push_test.go b/server/pkg/controller/push_test.goindex 3b2d54b4f7..d68a50a97f 100644--- a/server/pkg/controller/push_test.go+++ b/server/pkg/controller/push_test.go@@ -2,18 +2,27 @@ package controllerimport ("context"+ "crypto/rand"+ "encoding/base64""encoding/json""errors""io""net/http"+ "strconv""strings""sync/atomic""testing"+ "time""github.com/ente/museum/ente"+ "github.com/ente/museum/internal/testutil"+ "github.com/ente/museum/pkg/repo"+ "github.com/ente/museum/pkg/utils/auth"log "github.com/sirupsen/logrus"logtest "github.com/sirupsen/logrus/hooks/test"+ "github.com/spf13/viper""github.com/stretchr/testify/require"+ "golang.org/x/crypto/nacl/box")type roundTripFunc func(*http.Request) (*http.Response, error)@@ -159,6 +168,92 @@ func TestFCMSendDoesNotClassifyInvalidArgumentAsUnregistered(t *testing.T) {require.False(t, errors.Is(err, errUnregisteredToken))}+func TestAlbumShareEncryptsEventForEachDevice(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() { testutil.ResetTables(t, db) })+ testutil.InsertUser(t, db, testutil.UserFixture{UserID: 1, Email: "[email protected]", CreationTime: 1})+ _, err := db.Exec(`INSERT INTO remote_store(user_id,key_name,key_value) VALUES(1,'internalUser','true')`)+ require.NoError(t, err)+ require.NoError(t, (&repo.UserAuthRepository{DB: db}).AddToken(1, ente.Photos, "session", "", ""))+ hash := auth.HashToken("session")+ platform := "ios"+ controller := &PushController{PushRepo: &repo.PushTokenRepository{DB: db}}+ keys := make(map[string][2]*[32]byte)+ for _, device := range []string{"first-device", "second-device"} {+ publicKey, privateKey, err := box.GenerateKey(rand.Reader)+ require.NoError(t, err)+ keys[device] = [2]*[32]byte{publicKey, privateKey}+ require.NoError(t, controller.AddToken(1, hash[:], ente.PushTokenRequest{+ FCMToken: device, APNSToken: "apns", Platform: &platform,+ Notification: &ente.PushNotificationRegistration{Version: 1, PublicKey: publicKey[:]},+ }))+ }+ var messages []map[string]any+ controller.fcm = &fcmClient{projectID: "test-project", httpClient: &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {+ require.NoError(t, request.Context().Err())+ var envelope struct {+ Message map[string]any `json:"message"`+ }+ require.NoError(t, json.NewDecoder(request.Body).Decode(&envelope))+ messages = append(messages, envelope.Message)+ return jsonResponse(http.StatusOK, "{}"), nil+ })}}+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ before := time.Now().Add(24 * time.Hour).Unix()+ controller.NotifyAlbumShare(ctx, []int64{1})+ require.Len(t, messages, 2)+ for _, message := range messages {+ require.Len(t, message, 2)+ device := message["token"].(string)+ apns := message["apns"].(map[string]any)+ headers := apns["headers"].(map[string]any)+ require.Equal(t, "alert", headers["apns-push-type"])+ require.Equal(t, "10", headers["apns-priority"])+ expires, err := strconv.ParseInt(headers["apns-expiration"].(string), 10, 64)+ require.NoError(t, err)+ require.GreaterOrEqual(t, expires, before)+ require.LessOrEqual(t, expires, time.Now().Add(24*time.Hour).Unix())+ payload := apns["payload"].(map[string]any)+ require.Len(t, payload, 3)+ require.EqualValues(t, 1, payload["notificationVersion"])+ aps := payload["aps"].(map[string]any)+ require.EqualValues(t, 1, aps["mutable-content"])+ require.Equal(t, map[string]any{"title": "Ente Photos", "body": "New activity"}, aps["alert"])+ ciphertext, err := base64.StdEncoding.DecodeString(payload["notificationCiphertext"].(string))+ require.NoError(t, err)+ plaintext, ok := box.OpenAnonymous(nil, ciphertext, keys[device][0], keys[device][1])+ require.True(t, ok)+ require.JSONEq(t, `{"version":1,"eventType":"album_shared"}`, string(plaintext))+ encoded, err := json.Marshal(message)+ require.NoError(t, err)+ require.NotContains(t, string(encoded), "album_shared")+ require.NotContains(t, string(encoded), "[email protected]")+ otherPublic, otherPrivate, err := box.GenerateKey(rand.Reader)+ require.NoError(t, err)+ _, ok = box.OpenAnonymous(nil, ciphertext, otherPublic, otherPrivate)+ require.False(t, ok)+ }++ messages = nil+ controller.fcm.httpClient.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {+ messages = append(messages, nil)+ return jsonResponse(http.StatusInternalServerError, "unavailable"), nil+ })+ controller.NotifyAlbumShare(context.Background(), []int64{1})+ require.Len(t, messages, 2, "one device failure must not stop the other send")+}++func TestAlbumShareHonorsSilentMode(t *testing.T) {+ previous := viper.GetBool("internal.silent")+ viper.Set("internal.silent", true)+ t.Cleanup(func() { viper.Set("internal.silent", previous) })+ controller := &PushController{fcm: &fcmClient{}}+ controller.NotifyAlbumShare(context.Background(), []int64{1})+}+func captureLogs(t *testing.T) *logtest.Hook {t.Helper()logger := log.StandardLogger()diff --git a/server/pkg/repo/collection.go b/server/pkg/repo/collection.goindex 928a16d8ea..894b793727 100644--- a/server/pkg/repo/collection.go+++ b/server/pkg/repo/collection.go@@ -511,18 +511,18 @@ func (repo *CollectionRepository) Share(toUserID int64,encryptedKey string,role ente.CollectionParticipantRole,- updationTime int64) error {+ updationTime int64) (bool, error) {context := context.Background()tx, err := repo.DB.BeginTx(context, nil)if err != nil {- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}defer tx.Rollback()if role != ente.VIEWER && role != ente.COLLABORATOR && role != ente.ADMIN {err = fmt.Errorf("invalid role %s", string(role))- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}- _, err = tx.ExecContext(context, `INSERT INTO collection_shares(collection_id, from_user_id, to_user_id, encrypted_key, updation_time, role_type, shared_at) VALUES($1, $2, $3, $4, $5, $6, $7)+ result, err := tx.ExecContext(context, `INSERT INTO collection_shares(collection_id, from_user_id, to_user_id, encrypted_key, updation_time, role_type, shared_at) VALUES($1, $2, $3, $4, $5, $6, $7)ON CONFLICT (collection_id, from_user_id, to_user_id)DO UPDATE SETis_deleted = FALSE,@@ -531,17 +531,40 @@ func (repo *CollectionRepository) Share(shared_at = CASEWHEN collection_shares.is_deleted = TRUE THEN $7ELSE collection_shares.shared_at- END`,+ END+ WHERE collection_shares.is_deleted IS NOT FALSE`,collectionID, fromUserID, toUserID, encryptedKey, updationTime, role, updationTime)if err != nil {- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}- _, err = tx.ExecContext(context, `UPDATE collections SET updation_time = $1 WHERE collection_id = $2`, updationTime, collectionID)+ added, err := result.RowsAffected()if err != nil {- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}- err = tx.Commit()- return stacktrace.Propagate(err, "")+ if added == 0 {+ _, err = tx.ExecContext(context, `UPDATE collection_shares SET updation_time = $4, role_type = $5+ WHERE collection_id = $1 AND from_user_id = $2 AND to_user_id = $3`,+ collectionID, fromUserID, toUserID, updationTime, role)+ if err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ }+ result, err = tx.ExecContext(context, `UPDATE collections SET updation_time = $1+ WHERE collection_id = $2 AND is_deleted = FALSE`, updationTime, collectionID)+ if err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ updated, err := result.RowsAffected()+ if err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ if updated == 0 {+ return false, stacktrace.Propagate(ente.ErrCollectionDeleted, "")+ }+ if err := tx.Commit(); err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ return added == 1, nil}func (repo *CollectionRepository) BatchShare(@@ -550,7 +573,7 @@ func (repo *CollectionRepository) BatchShare(fromUserID int64,shares []CollectionShareItem,updationTime int64,-) error {+) ([]int64, error) {toUserIDs := make([]int64, len(shares))encryptedKeys := make([]string, len(shares))roles := make([]string, len(shares))@@ -562,11 +585,11 @@ func (repo *CollectionRepository) BatchShare(tx, err := repo.DB.BeginTx(ctx, nil)if err != nil {- return stacktrace.Propagate(err, "")+ return nil, stacktrace.Propagate(err, "")}defer tx.Rollback()- _, err = tx.ExecContext(ctx, `INSERT INTO collection_shares+ rows, err := tx.QueryContext(ctx, `INSERT INTO collection_shares(collection_id, from_user_id, to_user_id, encrypted_key, updation_time, role_type, shared_at)SELECT $1, $2, input.to_user_id, input.encrypted_key, $3, input.role, $3FROM unnest($4::bigint[], $5::text[], $6::role_enum[])@@ -580,7 +603,9 @@ func (repo *CollectionRepository) BatchShare(shared_at = CASEWHEN collection_shares.is_deleted = TRUE THEN EXCLUDED.shared_atELSE collection_shares.shared_at- END`,+ END+ WHERE collection_shares.is_deleted IS NOT FALSE+ RETURNING to_user_id`,collectionID,fromUserID,updationTime,@@ -589,22 +614,49 @@ func (repo *CollectionRepository) BatchShare(pq.Array(roles),)if err != nil {- return stacktrace.Propagate(err, "")+ return nil, stacktrace.Propagate(err, "")+ }++ added := []int64{}+ for rows.Next() {+ var id int64+ if err := rows.Scan(&id); err != nil {+ rows.Close()+ return nil, stacktrace.Propagate(err, "")+ }+ added = append(added, id)+ }+ rows.Close()+ if err := rows.Err(); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ if len(added) < len(shares) {+ _, err = tx.ExecContext(ctx, `UPDATE collection_shares s SET role_type = input.role, updation_time = $3+ FROM unnest($4::bigint[], $5::role_enum[]) AS input(to_user_id, role)+ WHERE s.collection_id = $1 AND s.from_user_id = $2 AND s.to_user_id = input.to_user_id+ AND s.to_user_id <> ALL($6::bigint[])`,+ collectionID, fromUserID, updationTime, pq.Array(toUserIDs), pq.Array(roles), pq.Array(added))+ if err != nil {+ return nil, stacktrace.Propagate(err, "")+ }}result, err := tx.ExecContext(ctx, `UPDATE collections SET updation_time = $1WHERE collection_id = $2 AND is_deleted = FALSE`, updationTime, collectionID)if err != nil {- return stacktrace.Propagate(err, "")+ return nil, stacktrace.Propagate(err, "")}updated, err := result.RowsAffected()if err != nil {- return stacktrace.Propagate(err, "")+ return nil, stacktrace.Propagate(err, "")}if updated == 0 {- return stacktrace.Propagate(ente.ErrCollectionDeleted, "")+ return nil, stacktrace.Propagate(ente.ErrCollectionDeleted, "")}- return stacktrace.Propagate(tx.Commit(), "")+ if err := tx.Commit(); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ return added, nil}// ShareAutomatically creates a share without modifying a prior share.diff --git a/server/pkg/repo/push.go b/server/pkg/repo/push.goindex 7a03055b5e..96bdb3eff0 100644--- a/server/pkg/repo/push.go+++ b/server/pkg/repo/push.go@@ -1,6 +1,7 @@package repoimport (+ "context""database/sql""github.com/ente/museum/ente"@@ -14,12 +15,17 @@ type PushTokenRepository struct {}func (repo *PushTokenRepository) AddToken(userID int64, sessionTokenHash []byte, token ente.PushTokenRequest) error {- result, err := repo.DB.Exec(`INSERT INTO push_tokens(user_id, fcm_token, apns_token, session_token_hash)- SELECT user_id, $2, $3, token_hash FROM tokens+ var publicKey any+ if token.Notification != nil {+ publicKey = token.Notification.PublicKey+ }+ result, err := repo.DB.Exec(`INSERT INTO push_tokens(user_id, fcm_token, apns_token, session_token_hash, platform, notification_public_key)+ SELECT user_id, $2, $3, token_hash, $5, $6 FROM tokensWHERE user_id = $1 AND token_hash = $4 AND is_deleted = false FOR SHAREON CONFLICT (fcm_token) DO UPDATE- SET user_id = EXCLUDED.user_id, apns_token = EXCLUDED.apns_token, session_token_hash = EXCLUDED.session_token_hash`,- userID, token.FCMToken, token.APNSToken, sessionTokenHash)+ SET user_id = EXCLUDED.user_id, apns_token = EXCLUDED.apns_token, session_token_hash = EXCLUDED.session_token_hash,+ platform = EXCLUDED.platform, notification_public_key = EXCLUDED.notification_public_key`,+ userID, token.FCMToken, token.APNSToken, sessionTokenHash, token.Platform, publicKey)if err != nil {return stacktrace.Propagate(err, "")}@@ -35,7 +41,7 @@ func (repo *PushTokenRepository) AddToken(userID int64, sessionTokenHash []byte,func (repo *PushTokenRepository) GetTokensToBeNotified(lastNotificationTime int64, limit int) ([]ente.PushToken, error) {rows, err := repo.DB.Query(`SELECT p.user_id, p.fcm_token, p.created_at, p.last_notified_at FROM push_tokens p- WHERE p.last_notified_at < $1+ WHERE p.last_notified_at < $1 AND p.platform = 'ios'AND (p.session_token_hash IS NULL OR EXISTS (SELECT 1 FROM tokens t WHERE t.token_hash = p.session_token_hashAND t.user_id = p.user_id AND t.is_deleted = false@@ -56,6 +62,27 @@ func (repo *PushTokenRepository) GetTokensToBeNotified(lastNotificationTime int6return tokens, nil}+func (repo *PushTokenRepository) GetTokensForAlbumShare(ctx context.Context, userIDs []int64) ([]ente.PushToken, error) {+ rows, err := repo.DB.QueryContext(ctx, `SELECT p.fcm_token, p.notification_public_key FROM push_tokens p+ JOIN tokens t ON t.token_hash = p.session_token_hash AND t.user_id = p.user_id AND t.is_deleted = false AND t.app = $3+ JOIN remote_store r ON r.user_id = p.user_id AND r.key_name = $2 AND r.key_value = 'true'+ WHERE p.user_id = ANY($1) AND p.platform = 'ios' AND p.apns_token <> '' AND p.notification_public_key IS NOT NULL`,+ pq.Array(userIDs), string(ente.IsInternalUser), string(ente.Photos))+ if err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ defer rows.Close()+ var tokens []ente.PushToken+ for rows.Next() {+ var token ente.PushToken+ if err := rows.Scan(&token.FCMToken, &token.NotificationPublicKey); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ tokens = append(tokens, token)+ }+ return tokens, stacktrace.Propagate(rows.Err(), "")+}+func (repo *PushTokenRepository) SetLastNotificationTimeToNow(pushTokens []ente.PushToken) error {fcmTokens := make([]string, 0)for _, pushToken := range pushTokens {diff --git a/server/pkg/repo/push_test.go b/server/pkg/repo/push_test.goindex 8e4ed3ad3e..e3135b45a5 100644--- a/server/pkg/repo/push_test.go+++ b/server/pkg/repo/push_test.go@@ -1,6 +1,7 @@package repoimport (+ "context""crypto/sha256""fmt""os"@@ -88,7 +89,8 @@ func TestPushRegistrationRejectsRevokedSessionAfterAccountSwitch(t *testing.T) {require.NoError(t, authRepo.AddToken(id, ente.Photos, fmt.Sprint(id), "", ""))}oldHash, newHash := sha256.Sum256([]byte("1")), sha256.Sum256([]byte("2"))- request := ente.PushTokenRequest{FCMToken: "device"}+ platform := "ios"+ request := ente.PushTokenRequest{FCMToken: "device", Platform: &platform}require.NoError(t, pushRepo.AddToken(1, oldHash[:], request))_, err := authRepo.RemoveTokenByHash(1, oldHash[:])require.NoError(t, err)@@ -129,9 +131,10 @@ func TestPushRegistrationWaitsForSessionRevocation(t *testing.T) {require.NoError(t, err)var pid intrequire.NoError(t, revocation.QueryRow(`SELECT pg_backend_pid()`).Scan(&pid))+ platform := "ios"done := make(chan error, 1)go func() {- done <- (&PushTokenRepository{DB: db}).AddToken(userID, hash[:], ente.PushTokenRequest{FCMToken: "device"})+ done <- (&PushTokenRepository{DB: db}).AddToken(userID, hash[:], ente.PushTokenRequest{FCMToken: "device", Platform: &platform})}()require.EventuallyWithT(t, func(collect *assert.CollectT) {var blocked bool@@ -150,3 +153,99 @@ func TestPushRegistrationWaitsForSessionRevocation(t *testing.T) {require.NoError(t, db.QueryRow(`SELECT count(*) FROM push_tokens`).Scan(&count))require.Zero(t, count)}++func TestPushNotificationRegistrationMigration(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ tx, err := db.Begin()+ require.NoError(t, err)+ defer tx.Rollback()+ _, err = tx.Exec(`CREATE TEMP TABLE push_tokens (fcm_token TEXT) ON COMMIT DROP;+ INSERT INTO push_tokens VALUES ('legacy')`)+ require.NoError(t, err)+ up, err := os.ReadFile("migrations/150_push_notification_registration.up.sql")+ require.NoError(t, err)+ _, err = tx.Exec(string(up))+ require.NoError(t, err)+ _, err = tx.Exec(`INSERT INTO push_tokens (fcm_token) VALUES ('old-server')`)+ require.NoError(t, err)+ var count int+ require.NoError(t, tx.QueryRow(`SELECT count(*) FROM push_tokens WHERE platform='ios' AND notification_public_key IS NULL`).Scan(&count))+ require.Equal(t, 2, count)+ down, err := os.ReadFile("migrations/150_push_notification_registration.down.sql")+ require.NoError(t, err)+ _, err = tx.Exec(string(down))+ require.NoError(t, err)+ require.NoError(t, tx.QueryRow(`SELECT count(*) FROM push_tokens`).Scan(&count))+ require.Equal(t, 2, count)+}++func TestAlbumShareTokensRequireInternalIOSAndActiveSession(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() { testutil.ResetTables(t, db) })+ key := append([]byte{9}, make([]byte, 31)...)+ for id, tc := range []struct {+ name, platform, flag, session string+ app ente.App+ key []byte+ }{+ {"eligible", "ios", "true", "active", ente.Photos, key},+ {"android", "android", "true", "active", ente.Photos, key},+ {"non-internal", "ios", "false", "active", ente.Photos, key},+ {"missing flag", "ios", "", "active", ente.Photos, key},+ {"unenrolled", "ios", "true", "active", ente.Photos, nil},+ {"legacy", "ios", "true", "missing", ente.Photos, key},+ {"revoked", "ios", "true", "revoked", ente.Photos, key},+ {"wrong owner", "ios", "true", "wrong owner", ente.Photos, key},+ {"other app", "ios", "true", "active", ente.Locker, key},+ } {+ userID := int64(id + 1)+ testutil.InsertUser(t, db, testutil.UserFixture{UserID: userID, Email: fmt.Sprintf("user%[email protected]", userID), CreationTime: 1})+ hash := sha256.Sum256([]byte(tc.name))+ var sessionHash []byte+ if tc.session != "missing" {+ require.NoError(t, (&UserAuthRepository{DB: db}).AddToken(userID, tc.app, tc.name, "", ""))+ sessionHash = hash[:]+ }+ if tc.session == "revoked" {+ _, err := db.Exec(`UPDATE tokens SET is_deleted=true WHERE token_hash=$1`, hash[:])+ require.NoError(t, err)+ }+ if tc.session == "wrong owner" {+ hash = sha256.Sum256([]byte("eligible"))+ sessionHash = hash[:]+ }+ var publicKey any+ if tc.key != nil {+ publicKey = tc.key+ }+ _, err := db.Exec(`INSERT INTO push_tokens(user_id,fcm_token,apns_token,platform,notification_public_key,session_token_hash,last_notified_at)+ VALUES($1,$2,'apns',$3,$4,$5,0)`, userID, tc.name, tc.platform, publicKey, sessionHash)+ require.NoError(t, err)+ if tc.flag != "" {+ _, err = db.Exec(`INSERT INTO remote_store(user_id,key_name,key_value) VALUES($1,'internalUser',$2)`, userID, tc.flag)+ require.NoError(t, err)+ }+ }+ r := &PushTokenRepository{DB: db}+ tokens, err := r.GetTokensForAlbumShare(context.Background(), []int64{1, 2, 3, 4, 5, 6, 7, 8, 9})+ require.NoError(t, err)+ require.Len(t, tokens, 1)+ require.Equal(t, "eligible", tokens[0].FCMToken)+ require.Equal(t, key, tokens[0].NotificationPublicKey)+ tokens, err = r.GetTokensForAlbumShare(context.Background(), []int64{2})+ require.NoError(t, err)+ require.Empty(t, tokens)+ tokens, err = r.GetTokensToBeNotified(1, 100)+ require.NoError(t, err)+ for _, token := range tokens {+ require.NotEqual(t, "android", token.FCMToken)+ }+ _, err = db.Exec(`UPDATE remote_store SET key_value='false' WHERE user_id=1`)+ require.NoError(t, err)+ tokens, err = r.GetTokensForAlbumShare(context.Background(), []int64{1})+ require.NoError(t, err)+ require.Empty(t, tokens)+}