Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[server] Roll out encrypted Android album-share pushes (#14165)

aman-pilotecad2f1f6111
diff --git a/server/ente/push.go b/server/ente/push.go
index 90cd738c91..b12028608b 100644
--- a/server/ente/push.go
+++ b/server/ente/push.go
@@ -14,10 +14,11 @@ type PushTokenRequest struct {
}
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/pkg/controller/push.go b/server/pkg/controller/push.go
index 111524cd6f..12d8a51cce 100644
--- a/server/pkg/controller/push.go
+++ b/server/pkg/controller/push.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/hpke"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -123,9 +124,23 @@ func (c *PushController) NotifyAlbumShare(ctx context.Context, recipients []int6
}
var unregisteredTokens []string
for _, token := range tokens {
+ if token.NotificationPublicKey == nil {
+ continue
+ }
+ publicKey, err := hpke.MLKEM768X25519().NewPublicKey(token.NotificationPublicKey)
+ if err != nil {
+ log.WithError(err).Warn("invalid album share notification public key")
+ continue
+ }
+ ciphertext, err := hpke.Seal(publicKey, hpke.HKDFSHA256(), hpke.ChaCha20Poly1305(),
+ []byte("ente-push"), []byte(`{"eventType":"album_shared"}`))
+ if err != nil {
+ log.WithError(err).Warn("album share notification encryption failed")
+ continue
+ }
err = c.fcm.sendMessage(ctx, map[string]any{
"token": token.FCMToken,
- "data": map[string]string{"action": "sync"},
+ "data": map[string]string{"notificationCiphertext": base64.StdEncoding.EncodeToString(ciphertext)},
"android": map[string]string{"priority": "high", "ttl": "86400s"},
})
if err != nil {
diff --git a/server/pkg/controller/push_test.go b/server/pkg/controller/push_test.go
index 37a9bd167b..bb4aed4bd4 100644
--- a/server/pkg/controller/push_test.go
+++ b/server/pkg/controller/push_test.go
@@ -2,6 +2,8 @@ package controller
import (
"context"
+ "crypto/hpke"
+ "encoding/base64"
"encoding/json"
"errors"
"io"
@@ -163,7 +165,7 @@ func TestFCMSendDoesNotClassifyInvalidArgumentAsUnregistered(t *testing.T) {
require.False(t, errors.Is(err, errUnregisteredToken))
}
-func TestAlbumShareSendsOnlyAndroidSync(t *testing.T) {
+func TestAlbumShareSendsOnlyEnrolledAndroidDevices(t *testing.T) {
testutil.WithServerRoot(t)
db := testutil.RequireTestDB(t)
testutil.ResetTables(t, db)
@@ -174,9 +176,11 @@ func TestAlbumShareSendsOnlyAndroidSync(t *testing.T) {
require.NoError(t, (&repo.UserAuthRepository{DB: db}).AddToken(1, ente.Photos, "session", "", ""))
hash := auth.HashToken("session")
controller := &PushController{PushRepo: &repo.PushTokenRepository{DB: db}}
+ key, err := hpke.MLKEM768X25519().GenerateKey()
+ require.NoError(t, err)
for _, platform := range []string{"ios", "android"} {
require.NoError(t, controller.AddToken(1, hash[:], ente.PushTokenRequest{
- FCMToken: platform + "-device", Platform: &platform,
+ FCMToken: platform + "-device", Platform: &platform, NotificationKey: key.PublicKey().Bytes(),
}))
}
var messages []map[string]any
@@ -192,11 +196,56 @@ func TestAlbumShareSendsOnlyAndroidSync(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
controller.NotifyAlbumShare(ctx, []int64{1})
- require.Equal(t, []map[string]any{{
- "token": "android-device",
- "data": map[string]any{"action": "sync"},
- "android": map[string]any{"priority": "high", "ttl": "86400s"},
- }}, messages)
+ require.Len(t, messages, 1)
+ require.Equal(t, "android-device", messages[0]["token"])
+ require.Equal(t, map[string]any{"priority": "high", "ttl": "86400s"}, messages[0]["android"])
+}
+
+func TestAlbumShareEncryptsForEachEnrolledDevice(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: 8, Email: "[email protected]", CreationTime: 1})
+ require.NoError(t, (&repo.UserAuthRepository{DB: db}).AddToken(8, ente.Photos, "session", "", ""))
+ hash := auth.HashToken("session")
+ platform := "android"
+ c := &PushController{PushRepo: &repo.PushTokenRepository{DB: db}}
+ keys := make(map[string]hpke.PrivateKey)
+ for _, token := range []string{"first-device", "second-device"} {
+ key, err := hpke.MLKEM768X25519().GenerateKey()
+ require.NoError(t, err)
+ keys[token] = key
+ require.NoError(t, c.AddToken(8, hash[:], ente.PushTokenRequest{
+ FCMToken: token, Platform: &platform, NotificationKey: key.PublicKey().Bytes(),
+ }))
+ }
+ require.NoError(t, c.AddToken(8, hash[:], ente.PushTokenRequest{FCMToken: "legacy", Platform: &platform}))
+ var messages []wireMsg
+ c.fcm = &fcmClient{projectID: "test-project", httpClient: &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
+ var message wireMsg
+ require.NoError(t, json.NewDecoder(request.Body).Decode(&message))
+ messages = append(messages, message)
+ return jsonResponse(http.StatusOK, "{}"), nil
+ })}}
+ c.NotifyAlbumShare(context.Background(), []int64{8})
+ require.Len(t, messages, 2, "devices without a key must receive no push")
+ for _, envelope := range messages {
+ message := envelope.Message
+ require.Contains(t, keys, message.Token)
+ require.Contains(t, message.Data, "notificationCiphertext")
+ ciphertext, err := base64.StdEncoding.DecodeString(message.Data["notificationCiphertext"])
+ require.NoError(t, err)
+ plaintext, err := hpke.Open(keys[message.Token], hpke.HKDFSHA256(), hpke.ChaCha20Poly1305(), []byte("ente-push"), ciphertext)
+ require.NoError(t, err)
+ require.JSONEq(t, `{"eventType":"album_shared"}`, string(plaintext))
+ }
+ // Removing a device key must stop album-share pushes to that device.
+ require.NoError(t, c.AddToken(8, hash[:], ente.PushTokenRequest{FCMToken: "first-device", Platform: &platform}))
+ messages = nil
+ c.NotifyAlbumShare(context.Background(), []int64{8})
+ require.Len(t, messages, 1)
+ require.Equal(t, "second-device", messages[0].Message.Token)
}
func TestAlbumSharePrunesOnlyUnregisteredTokens(t *testing.T) {
@@ -221,9 +270,11 @@ func TestAlbumSharePrunesOnlyUnregisteredTokens(t *testing.T) {
"unauthorized": {http.StatusUnauthorized, "unauthorized"},
"invalid-argument": {http.StatusBadRequest, fcmInvalidArgumentBody},
}
+ key, err := hpke.MLKEM768X25519().GenerateKey()
+ require.NoError(t, err)
for token := range responses {
require.NoError(t, controller.AddToken(1, hash[:], ente.PushTokenRequest{
- FCMToken: token, Platform: &platform,
+ FCMToken: token, Platform: &platform, NotificationKey: key.PublicKey().Bytes(),
}))
}
var attempted []string
diff --git a/server/pkg/repo/push.go b/server/pkg/repo/push.go
index abac4a5e02..5b1ec15ec4 100644
--- a/server/pkg/repo/push.go
+++ b/server/pkg/repo/push.go
@@ -5,6 +5,7 @@ import (
"database/sql"
"github.com/ente/museum/ente"
+ "github.com/ente/museum/pkg/utils/rollout"
"github.com/ente/museum/pkg/utils/time"
"github.com/ente/stacktrace"
"github.com/lib/pq"
@@ -14,6 +15,11 @@ type PushTokenRepository struct {
DB *sql.DB
}
+const (
+ androidAlbumShareRolloutPercentage = 30
+ androidAlbumShareRollout = "android-album-share-v1"
+)
+
func (repo *PushTokenRepository) AddToken(userID int64, sessionTokenHash []byte, token ente.PushTokenRequest) error {
var publicKey any
if token.NotificationKey != nil {
@@ -63,9 +69,9 @@ func (repo *PushTokenRepository) GetTokensToBeNotified(lastNotificationTime int6
}
func (repo *PushTokenRepository) GetTokensForAlbumShare(ctx context.Context, userIDs []int64) ([]ente.PushToken, error) {
- rows, err := repo.DB.QueryContext(ctx, `SELECT p.fcm_token FROM push_tokens p
+ rows, err := repo.DB.QueryContext(ctx, `SELECT p.user_id, p.fcm_token, p.notification_public_key, r.user_id IS NOT NULL 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'
+ LEFT 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 = 'android'`,
pq.Array(userIDs), string(ente.IsInternalUser), string(ente.Photos))
if err != nil {
@@ -75,10 +81,13 @@ func (repo *PushTokenRepository) GetTokensForAlbumShare(ctx context.Context, use
var tokens []ente.PushToken
for rows.Next() {
var token ente.PushToken
- if err := rows.Scan(&token.FCMToken); err != nil {
+ var internalUser bool
+ if err := rows.Scan(&token.UserID, &token.FCMToken, &token.NotificationPublicKey, &internalUser); err != nil {
return nil, stacktrace.Propagate(err, "")
}
- tokens = append(tokens, token)
+ if internalUser || rollout.IsInPercentageRollout(token.UserID, androidAlbumShareRollout, androidAlbumShareRolloutPercentage) {
+ tokens = append(tokens, token)
+ }
}
return tokens, stacktrace.Propagate(rows.Err(), "")
}
diff --git a/server/pkg/repo/push_test.go b/server/pkg/repo/push_test.go
index 498456dbd7..5049f89b06 100644
--- a/server/pkg/repo/push_test.go
+++ b/server/pkg/repo/push_test.go
@@ -180,26 +180,29 @@ func TestPushPlatformRegistrationMigration(t *testing.T) {
require.Equal(t, 2, count)
}
-func TestAlbumShareTokensRequireInternalAndActiveSession(t *testing.T) {
+func TestAlbumShareTokensRequireRolloutAndActiveSession(t *testing.T) {
testutil.WithServerRoot(t)
db := testutil.RequireTestDB(t)
testutil.ResetTables(t, db)
t.Cleanup(func() { testutil.ResetTables(t, db) })
var userIDs []int64
- for id, tc := range []struct {
+ for _, tc := range []struct {
+ userID int64
name, platform, flag, session string
app ente.App
}{
- {"eligible", "android", "true", "active", ente.Photos},
- {"ios", "ios", "true", "active", ente.Photos},
- {"non-internal", "android", "false", "active", ente.Photos},
- {"missing flag", "android", "", "active", ente.Photos},
- {"legacy", "android", "true", "missing", ente.Photos},
- {"revoked", "android", "true", "revoked", ente.Photos},
- {"wrong owner", "android", "true", "wrong owner", ente.Photos},
- {"other app", "android", "true", "active", ente.Locker},
+ {2, "eligible", "android", "true", "active", ente.Photos},
+ {4, "ios", "ios", "true", "active", ente.Photos},
+ {3, "non-internal", "android", "false", "active", ente.Photos},
+ {22, "missing flag", "android", "", "active", ente.Photos},
+ {5, "legacy", "android", "true", "missing", ente.Photos},
+ {1, "revoked", "android", "true", "revoked", ente.Photos},
+ {7, "wrong owner", "android", "true", "wrong owner", ente.Photos},
+ {12, "other app", "android", "true", "active", ente.Locker},
+ {8, "rollout missing flag", "android", "", "active", ente.Photos},
+ {15, "rollout false flag", "android", "false", "active", ente.Photos},
} {
- userID := int64(id + 1)
+ userID := tc.userID
userIDs = append(userIDs, userID)
testutil.InsertUser(t, db, testutil.UserFixture{UserID: userID, Email: fmt.Sprintf("user%[email protected]", userID), CreationTime: 1})
hash := sha256.Sum256([]byte(tc.name))
@@ -231,11 +234,11 @@ func TestAlbumShareTokensRequireInternalAndActiveSession(t *testing.T) {
for _, token := range tokens {
selected = append(selected, token.FCMToken)
}
- require.Equal(t, []string{"eligible"}, selected)
+ require.ElementsMatch(t, []string{"eligible", "rollout missing flag", "rollout false flag"}, selected)
for _, apnsToken := range []any{"", nil} {
_, err := db.Exec(`UPDATE push_tokens SET apns_token=$1 WHERE fcm_token='eligible'`, apnsToken)
require.NoError(t, err)
- tokens, err := r.GetTokensForAlbumShare(context.Background(), []int64{1})
+ tokens, err := r.GetTokensForAlbumShare(context.Background(), []int64{2})
require.NoError(t, err)
require.Len(t, tokens, 1)
require.Equal(t, "eligible", tokens[0].FCMToken)
@@ -244,9 +247,9 @@ func TestAlbumShareTokensRequireInternalAndActiveSession(t *testing.T) {
require.NoError(t, err)
require.Len(t, tokens, 1)
require.Equal(t, "ios", tokens[0].FCMToken)
- _, err = db.Exec(`UPDATE remote_store SET key_value='false' WHERE user_id=1`)
+ _, err = db.Exec(`UPDATE remote_store SET key_value='false' WHERE user_id=2`)
require.NoError(t, err)
- tokens, err = r.GetTokensForAlbumShare(context.Background(), []int64{1})
+ tokens, err = r.GetTokensForAlbumShare(context.Background(), []int64{2})
require.NoError(t, err)
require.Empty(t, tokens)
}