π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add temporary collection cleanup API
Neeraj Guptaa0fadc13c80f
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 054e84c3b9..b7695ad71a 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -961,6 +961,7 @@ func main() {adminAPI.DELETE("/user/delete", adminHandler.DeleteUser)adminAPI.POST("/user/recover", adminHandler.RecoverAccount)adminAPI.POST("/user/update-flag", adminHandler.UpdateFeatureFlag)+ adminAPI.POST("/collections/cleanup-bad-entries", adminHandler.CleanupBadCollectionEntries)adminAPI.GET("/email-hash", adminHandler.GetEmailHash)adminAPI.POST("/emails-from-hashes", adminHandler.GetEmailsFromHashes)adminAPI.PUT("/user/subscription", adminHandler.UpdateSubscription)diff --git a/server/ente/admin.go b/server/ente/admin.goindex d70002dd70..f345ca8299 100644--- a/server/ente/admin.go+++ b/server/ente/admin.go@@ -91,6 +91,11 @@ type ChangeEmailRequest struct {Email string `json:"email" binding:"required"`}+type CleanupBadCollectionEntriesRequest struct {+ ApplyCollectionFilesCleanup bool `json:"applyCollectionFilesCleanup"`+ ApplyCollectionSharesCleanup bool `json:"applyCollectionSharesCleanup"`+}+type AddOnAction stringconst (diff --git a/server/pkg/api/admin.go b/server/pkg/api/admin.goindex 2feae2d074..64d9255085 100644--- a/server/pkg/api/admin.go+++ b/server/pkg/api/admin.go@@ -3,6 +3,7 @@ package apiimport ("errors""fmt"+ "io""net/http""strconv""strings"@@ -489,6 +490,29 @@ func (h *AdminHandler) ChangeEmail(c *gin.Context) {c.JSON(http.StatusOK, gin.H{})}+func (h *AdminHandler) CleanupBadCollectionEntries(c *gin.Context) {+ var r ente.CleanupBadCollectionEntriesRequest+ if err := c.ShouldBindJSON(&r); err != nil && !errors.Is(err, io.EOF) {+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "Bad request"))+ return+ }+ result, err := h.CollectionRepo.CleanupBadCollectionEntries(c, r.ApplyCollectionFilesCleanup, r.ApplyCollectionSharesCleanup)+ if err != nil {+ handler.Error(c, stacktrace.Propagate(err, ""))+ return+ }+ if r.ApplyCollectionFilesCleanup || r.ApplyCollectionSharesCleanup {+ adminID := auth.GetUserID(c.Request.Header)+ h.notifyAdminAction(+ adminID,+ "cleaned bad collection entries: collection_files=%d collection_shares=%d",+ result.CollectionFilesDeleted,+ result.CollectionSharesDeleted,+ )+ }+ c.JSON(http.StatusOK, result)+}+func (h *AdminHandler) ReQueueItem(c *gin.Context) {var r ente.ReQueueItemRequestif err := c.ShouldBindJSON(&r); err != nil {diff --git a/server/pkg/repo/collection_cleanup.go b/server/pkg/repo/collection_cleanup.gonew file mode 100644index 0000000000..0740df101d--- /dev/null+++ b/server/pkg/repo/collection_cleanup.go@@ -0,0 +1,175 @@+package repo++import (+ "context"+ "database/sql"+ "encoding/base64"++ "github.com/ente-io/museum/pkg/utils/time"+ "github.com/ente-io/stacktrace"+ "github.com/lib/pq"+)++const (+ badCollectionFilesCollectionID = 1580559966740107+ sealedCollectionKeyLen = 80+)++var badCollectionFileIDs = []int64{588219655, 588220428, 588220482, 588220590}++type badCollectionShare struct {+ collectionID int64+ fromUserID int64+ toUserID int64+}++var badCollectionShares = []badCollectionShare{+ {collectionID: 1580559964131155, fromUserID: 1580559962588538, toUserID: 1580559962407419},+ {collectionID: 1580559966298981, fromUserID: 1580559962649891, toUserID: 1580559962653442},+}++type BadCollectionEntriesCleanupResult struct {+ CollectionFilesDeleted int64 `json:"collectionFilesDeleted"`+ CollectionFilesWouldDelete int64 `json:"collectionFilesWouldDelete"`+ CollectionSharesDeleted int64 `json:"collectionSharesDeleted"`+ CollectionSharesWouldDelete int64 `json:"collectionSharesWouldDelete"`+}++func (repo *CollectionRepository) CleanupBadCollectionEntries(ctx context.Context, applyFiles bool, applyShares bool) (BadCollectionEntriesCleanupResult, error) {+ var result BadCollectionEntriesCleanupResult+ now := time.Microseconds()+ touchedCollections := make(map[int64]bool)++ tx, err := repo.DB.BeginTx(ctx, nil)+ if err != nil {+ return result, stacktrace.Propagate(err, "")+ }+ defer tx.Rollback()++ fileCount, err := cleanupBadCollectionFiles(ctx, tx, now, applyFiles)+ if err != nil {+ return result, stacktrace.Propagate(err, "")+ }+ if applyFiles {+ result.CollectionFilesDeleted = fileCount+ } else {+ result.CollectionFilesWouldDelete = fileCount+ }+ if fileCount > 0 && applyFiles {+ touchedCollections[badCollectionFilesCollectionID] = true+ }++ shareCount, shareCollections, err := cleanupBadCollectionShares(ctx, tx, now, applyShares)+ if err != nil {+ return result, stacktrace.Propagate(err, "")+ }+ if applyShares {+ result.CollectionSharesDeleted = shareCount+ } else {+ result.CollectionSharesWouldDelete = shareCount+ }+ if shareCount > 0 && applyShares {+ for collectionID := range shareCollections {+ touchedCollections[collectionID] = true+ }+ }++ for collectionID := range touchedCollections {+ if _, err := tx.ExecContext(ctx, `UPDATE collections SET updation_time = $1 WHERE collection_id = $2`, now, collectionID); err != nil {+ return result, stacktrace.Propagate(err, "")+ }+ }++ return result, stacktrace.Propagate(tx.Commit(), "")+}++func cleanupBadCollectionFiles(ctx context.Context, tx *sql.Tx, updationTime int64, apply bool) (int64, error) {+ if !apply {+ var count int64+ err := tx.QueryRowContext(ctx, `+ SELECT count(*)+ FROM collection_files cf+ WHERE cf.collection_id = $1+ AND cf.file_id = ANY($2)+ AND cf.is_deleted = false+ AND EXISTS (+ SELECT 1+ FROM collection_files other_cf+ WHERE other_cf.file_id = cf.file_id+ AND other_cf.collection_id <> cf.collection_id+ AND other_cf.is_deleted = false+ )`,+ badCollectionFilesCollectionID, pq.Array(badCollectionFileIDs)).Scan(&count)+ return count, stacktrace.Propagate(err, "")+ }++ res, err := tx.ExecContext(ctx, `+ UPDATE collection_files cf+ SET is_deleted = true, updation_time = $1+ WHERE cf.collection_id = $2+ AND cf.file_id = ANY($3)+ AND cf.is_deleted = false+ AND EXISTS (+ SELECT 1+ FROM collection_files other_cf+ WHERE other_cf.file_id = cf.file_id+ AND other_cf.collection_id <> cf.collection_id+ AND other_cf.is_deleted = false+ )`,+ updationTime, badCollectionFilesCollectionID, pq.Array(badCollectionFileIDs))+ if err != nil {+ return 0, stacktrace.Propagate(err, "")+ }+ count, err := res.RowsAffected()+ return count, stacktrace.Propagate(err, "")+}++func cleanupBadCollectionShares(ctx context.Context, tx *sql.Tx, updationTime int64, apply bool) (int64, map[int64]bool, error) {+ var count int64+ touchedCollections := make(map[int64]bool)+ for _, share := range badCollectionShares {+ var encryptedKey string+ err := tx.QueryRowContext(ctx, `+ SELECT encrypted_key+ FROM collection_shares+ WHERE collection_id = $1+ AND from_user_id = $2+ AND to_user_id = $3+ AND is_deleted = false`,+ share.collectionID, share.fromUserID, share.toUserID).Scan(&encryptedKey)+ if err == sql.ErrNoRows {+ continue+ }+ if err != nil {+ return 0, nil, stacktrace.Propagate(err, "")+ }+ decoded, err := base64.StdEncoding.DecodeString(encryptedKey)+ if err != nil || len(decoded) == sealedCollectionKeyLen {+ continue+ }+ if !apply {+ count+++ continue+ }+ res, err := tx.ExecContext(ctx, `+ UPDATE collection_shares+ SET is_deleted = true, updation_time = $1+ WHERE collection_id = $2+ AND from_user_id = $3+ AND to_user_id = $4+ AND is_deleted = false`,+ updationTime, share.collectionID, share.fromUserID, share.toUserID)+ if err != nil {+ return 0, nil, stacktrace.Propagate(err, "")+ }+ affected, err := res.RowsAffected()+ if err != nil {+ return 0, nil, stacktrace.Propagate(err, "")+ }+ count += affected+ if affected > 0 {+ touchedCollections[share.collectionID] = true+ }+ }+ return count, touchedCollections, nil+}diff --git a/server/pkg/repo/collection_cleanup_test.go b/server/pkg/repo/collection_cleanup_test.gonew file mode 100644index 0000000000..0e3a2324a9--- /dev/null+++ b/server/pkg/repo/collection_cleanup_test.go@@ -0,0 +1,252 @@+package repo++import (+ "context"+ "database/sql"+ "encoding/base64"+ "fmt"+ "testing"++ "github.com/ente-io/museum/ente"+ "github.com/ente-io/museum/internal/testutil"+)++func TestCleanupBadCollectionEntriesDryRun(t *testing.T) {+ repo, db := setupBadCollectionEntriesCleanupTest(t, 81)++ result, err := repo.CleanupBadCollectionEntries(context.Background(), false, false)+ if err != nil {+ t.Fatalf("CleanupBadCollectionEntries dry-run error = %v", err)+ }+ if result.CollectionFilesWouldDelete != 3 || result.CollectionFilesDeleted != 0 {+ t.Fatalf("unexpected file counts: %+v", result)+ }+ if result.CollectionSharesWouldDelete != 2 || result.CollectionSharesDeleted != 0 {+ t.Fatalf("unexpected share counts: %+v", result)+ }+ for _, fileID := range badCollectionFileIDs {+ if cleanupCollectionFileDeleted(t, db, badCollectionFilesCollectionID, fileID) {+ t.Fatalf("file %d was deleted during dry-run", fileID)+ }+ }+ for _, share := range badCollectionShares {+ if cleanupCollectionShareDeleted(t, db, share.collectionID, share.fromUserID, share.toUserID) {+ t.Fatalf("share %+v was deleted during dry-run", share)+ }+ }+}++func TestCleanupBadCollectionEntriesAppliesFileFlagOnly(t *testing.T) {+ repo, db := setupBadCollectionEntriesCleanupTest(t, 81)++ result, err := repo.CleanupBadCollectionEntries(context.Background(), true, false)+ if err != nil {+ t.Fatalf("CleanupBadCollectionEntries file apply error = %v", err)+ }+ if result.CollectionFilesDeleted != 3 || result.CollectionFilesWouldDelete != 0 {+ t.Fatalf("unexpected file counts: %+v", result)+ }+ if result.CollectionSharesDeleted != 0 || result.CollectionSharesWouldDelete != 2 {+ t.Fatalf("unexpected share counts: %+v", result)+ }+ for _, fileID := range badCollectionFileIDs[:3] {+ if !cleanupCollectionFileDeleted(t, db, badCollectionFilesCollectionID, fileID) {+ t.Fatalf("file %d was not deleted", fileID)+ }+ }+ if cleanupCollectionFileDeleted(t, db, badCollectionFilesCollectionID, badCollectionFileIDs[3]) {+ t.Fatalf("file without active alternate collection was deleted")+ }+ for _, share := range badCollectionShares {+ if cleanupCollectionShareDeleted(t, db, share.collectionID, share.fromUserID, share.toUserID) {+ t.Fatalf("share %+v was deleted by file-only cleanup", share)+ }+ }+ if cleanupCollectionUpdationTime(t, db, badCollectionFilesCollectionID) <= 1 {+ t.Fatal("file collection updation_time was not bumped")+ }+}++func TestCleanupBadCollectionEntriesAppliesShareFlagOnlyAndSkipsValidKey(t *testing.T) {+ repo, db := setupBadCollectionEntriesCleanupTest(t, sealedCollectionKeyLen)++ result, err := repo.CleanupBadCollectionEntries(context.Background(), false, true)+ if err != nil {+ t.Fatalf("CleanupBadCollectionEntries share apply error = %v", err)+ }+ if result.CollectionSharesDeleted != 1 || result.CollectionSharesWouldDelete != 0 {+ t.Fatalf("unexpected share counts: %+v", result)+ }+ if result.CollectionFilesDeleted != 0 || result.CollectionFilesWouldDelete != 3 {+ t.Fatalf("unexpected file counts: %+v", result)+ }++ badShare := badCollectionShares[0]+ if !cleanupCollectionShareDeleted(t, db, badShare.collectionID, badShare.fromUserID, badShare.toUserID) {+ t.Fatal("invalid share was not deleted")+ }+ validShare := badCollectionShares[1]+ if cleanupCollectionShareDeleted(t, db, validShare.collectionID, validShare.fromUserID, validShare.toUserID) {+ t.Fatal("valid sealed-key share was deleted")+ }+ for _, fileID := range badCollectionFileIDs {+ if cleanupCollectionFileDeleted(t, db, badCollectionFilesCollectionID, fileID) {+ t.Fatalf("file %d was deleted by share-only cleanup", fileID)+ }+ }+ if cleanupCollectionUpdationTime(t, db, badShare.collectionID) <= 1 {+ t.Fatal("bad share collection updation_time was not bumped")+ }+ if cleanupCollectionUpdationTime(t, db, validShare.collectionID) != 1 {+ t.Fatal("valid share collection updation_time was bumped")+ }+}++func setupBadCollectionEntriesCleanupTest(t *testing.T, secondShareKeyLen int) (*CollectionRepository, *sql.DB) {+ t.Helper()+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() {+ testutil.ResetTables(t, db)+ })++ userIDs := []int64{+ 1001,+ 1580559962588538,+ 1580559962407419,+ 1580559962649891,+ 1580559962653442,+ }+ for _, userID := range userIDs {+ testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: userID,+ Email: fmt.Sprintf("cleanup-%[email protected]", userID),+ CreationTime: 1,+ })+ }++ insertCleanupCollection(t, db, badCollectionFilesCollectionID, 1001)+ insertCleanupCollection(t, db, badCollectionFilesCollectionID+1, 1001)+ insertCleanupCollection(t, db, badCollectionShares[0].collectionID, badCollectionShares[0].fromUserID)+ insertCleanupCollection(t, db, badCollectionShares[1].collectionID, badCollectionShares[1].fromUserID)++ for idx, fileID := range badCollectionFileIDs {+ insertCleanupFile(t, db, fileID, 1001)+ insertCleanupCollectionFile(t, db, badCollectionFilesCollectionID, fileID, 1001)+ if idx < 3 {+ insertCleanupCollectionFile(t, db, badCollectionFilesCollectionID+1, fileID, 1001)+ }+ }++ insertCleanupCollectionShare(t, db, badCollectionShares[0], 79)+ insertCleanupCollectionShare(t, db, badCollectionShares[1], secondShareKeyLen)++ return &CollectionRepository{DB: db}, db+}++func insertCleanupCollection(t *testing.T, db *sql.DB, collectionID int64, ownerID int64) {+ t.Helper()+ _, err := db.Exec(+ `INSERT INTO collections(collection_id, owner_id, encrypted_key, key_decryption_nonce, name, type, attributes, updation_time, app)+ OVERRIDING SYSTEM VALUE+ VALUES($1, $2, $3, $4, $5, $6, $7::jsonb, $8, $9)`,+ collectionID,+ ownerID,+ "encrypted-key",+ "key-nonce",+ "Cleanup collection",+ "album",+ "{}",+ int64(1),+ string(ente.Photos),+ )+ if err != nil {+ t.Fatalf("failed to insert collection %d: %v", collectionID, err)+ }+}++func insertCleanupFile(t *testing.T, db *sql.DB, fileID int64, ownerID int64) {+ t.Helper()+ _, err := db.Exec(+ `INSERT INTO files(file_id, owner_id, file_decryption_header, thumbnail_decryption_header, metadata_decryption_header, encrypted_metadata, updation_time, info)+ VALUES($1, $2, $3, $4, $5, $6, $7, $8::jsonb)`,+ fileID,+ ownerID,+ "file-header",+ "thumbnail-header",+ "metadata-header",+ "encrypted-metadata",+ int64(1),+ "{}",+ )+ if err != nil {+ t.Fatalf("failed to insert file %d: %v", fileID, err)+ }+}++func insertCleanupCollectionFile(t *testing.T, db *sql.DB, collectionID int64, fileID int64, ownerID int64) {+ t.Helper()+ _, err := db.Exec(+ `INSERT INTO collection_files(collection_id, file_id, encrypted_key, key_decryption_nonce, updation_time, c_owner_id, f_owner_id)+ VALUES($1, $2, $3, $4, $5, $6, $7)`,+ collectionID,+ fileID,+ "collection-file-key",+ "collection-file-nonce",+ int64(1),+ ownerID,+ ownerID,+ )+ if err != nil {+ t.Fatalf("failed to insert collection file %d/%d: %v", collectionID, fileID, err)+ }+}++func insertCleanupCollectionShare(t *testing.T, db *sql.DB, share badCollectionShare, keyLen int) {+ t.Helper()+ _, err := db.Exec(+ `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)`,+ share.collectionID,+ share.fromUserID,+ share.toUserID,+ base64.StdEncoding.EncodeToString(make([]byte, keyLen)),+ int64(1),+ string(ente.VIEWER),+ int64(1),+ )+ if err != nil {+ t.Fatalf("failed to insert collection share %+v: %v", share, err)+ }+}++func cleanupCollectionFileDeleted(t *testing.T, db *sql.DB, collectionID int64, fileID int64) bool {+ t.Helper()+ var isDeleted bool+ err := db.QueryRow(`SELECT is_deleted FROM collection_files WHERE collection_id = $1 AND file_id = $2`, collectionID, fileID).Scan(&isDeleted)+ if err != nil {+ t.Fatalf("failed to fetch collection file %d/%d: %v", collectionID, fileID, err)+ }+ return isDeleted+}++func cleanupCollectionShareDeleted(t *testing.T, db *sql.DB, collectionID int64, fromUserID int64, toUserID int64) bool {+ t.Helper()+ var isDeleted bool+ err := db.QueryRow(`SELECT is_deleted FROM collection_shares WHERE collection_id = $1 AND from_user_id = $2 AND to_user_id = $3`, collectionID, fromUserID, toUserID).Scan(&isDeleted)+ if err != nil {+ t.Fatalf("failed to fetch collection share %d/%d/%d: %v", collectionID, fromUserID, toUserID, err)+ }+ return isDeleted+}++func cleanupCollectionUpdationTime(t *testing.T, db *sql.DB, collectionID int64) int64 {+ t.Helper()+ var updationTime int64+ err := db.QueryRow(`SELECT updation_time FROM collections WHERE collection_id = $1`, collectionID).Scan(&updationTime)+ if err != nil {+ t.Fatalf("failed to fetch collection %d updation_time: %v", collectionID, err)+ }+ return updationTime+}