π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add bulk collection sharing endpoints
Neeraj Gupta6902fc39ff26
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 3c2e58df2f..c93032dc7a 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -749,11 +749,13 @@ func main() {storageAPI.GET("/collections/v2", collectionHandler.GetV2)storageAPI.GET("/collections/v3", collectionHandler.GetWithLimit)storageAPI.POST("/collections/share", collectionHandler.Share)+ storageAPI.POST("/collections/share/bulk", collectionHandler.BulkShare)storageAPI.POST("/collections/join-link", collectionHandler.JoinLink)storageAPI.POST("/collections/share-url", collectionHandler.ShareURL)storageAPI.PUT("/collections/share-url", collectionHandler.UpdateShareURL)storageAPI.DELETE("/collections/share-url/:collectionID", collectionHandler.UnShareURL)storageAPI.POST("/collections/unshare", collectionHandler.UnShare)+ storageAPI.POST("/collections/unshare/bulk", collectionHandler.BulkUnShare)storageAPI.POST("/collections/leave/:collectionID", collectionHandler.Leave)storageAPI.POST("/collections/add-files", collectionHandler.AddFiles)storageAPI.POST("/collections/move-files", collectionHandler.MoveFiles)diff --git a/server/ente/collection.go b/server/ente/collection.goindex b5139b1441..d738c03a41 100644--- a/server/ente/collection.go+++ b/server/ente/collection.go@@ -45,6 +45,12 @@ func (c *Collection) AllowSharing() bool {return true}+// AllowParticipantSharing indicates whether a collection can be shared+// directly with a participant in the given role.+func (c *Collection) AllowParticipantSharing(role CollectionParticipantRole) bool {+ return c != nil && (c.Type != "uncategorized" || role == VIEWER)+}+// AllowDelete indicates if this particular collection type can be deleted by the user// or notfunc (c *Collection) AllowDelete() bool {@@ -98,6 +104,54 @@ type AlterShareRequest struct {Role *CollectionParticipantRole `json:"role"`}+type CollectionShareSource string++const (+ ManualShare CollectionShareSource = "manual"+ AutomaticShare CollectionShareSource = "automatic"+)++func (s CollectionShareSource) IsValid() bool {+ return s == ManualShare || s == AutomaticShare+}++type CollectionShareStatus string++const (+ CollectionShared CollectionShareStatus = "shared"+ CollectionAlreadyShared CollectionShareStatus = "already_shared"+ CollectionUnshared CollectionShareStatus = "unshared"+ CollectionAlreadyUnshared CollectionShareStatus = "already_unshared"+ CollectionNotShared CollectionShareStatus = "not_shared"+ CollectionBlockedPriorRemoval CollectionShareStatus = "blocked_previous_removal"+ CollectionShareOperationFailed CollectionShareStatus = "failed"+)++const MaxCollectionShareBatchSize = 100++type BulkCollectionShareItem struct {+ CollectionID int64 `json:"collectionID" binding:"required"`+ EncryptedKey string `json:"encryptedKey" binding:"required"`+ Role CollectionParticipantRole `json:"role" binding:"required"`+}++type BulkCollectionShareRequest struct {+ RecipientUserID int64 `json:"recipientUserID" binding:"required"`+ Source CollectionShareSource `json:"source" binding:"required"`+ Collections []BulkCollectionShareItem `json:"collections" binding:"required"`+}++type BulkCollectionUnshareRequest struct {+ RecipientUserID int64 `json:"recipientUserID" binding:"required"`+ Source CollectionShareSource `json:"source" binding:"required"`+ CollectionIDs []int64 `json:"collectionIDs" binding:"required"`+}++type BulkCollectionShareResult struct {+ CollectionID int64 `json:"collectionID"`+ Status CollectionShareStatus `json:"status"`+}+type JoinCollectionViaLinkRequest struct {CollectionID int64 `json:"collectionID" binding:"required"`EncryptedKey string `json:"encryptedKey" binding:"required"`diff --git a/server/pkg/api/collection.go b/server/pkg/api/collection.goindex eb339812ea..0baa50b5a8 100644--- a/server/pkg/api/collection.go+++ b/server/pkg/api/collection.go@@ -132,6 +132,21 @@ func (h *CollectionHandler) Share(c *gin.Context) {})}+// BulkShare shares up to 100 collections with one user.+func (h *CollectionHandler) BulkShare(c *gin.Context) {+ var request ente.BulkCollectionShareRequest+ if err := handler.BindJSON(c, &request); err != nil {+ handler.Error(c, stacktrace.Propagate(err, ""))+ return+ }+ results, err := h.Controller.BulkShare(c, request)+ if err != nil {+ handler.Error(c, stacktrace.Propagate(err, ""))+ return+ }+ c.JSON(http.StatusOK, gin.H{"results": results})+}+func (h *CollectionHandler) JoinLink(c *gin.Context) {var request ente.JoinCollectionViaLinkRequestif err := handler.BindJSON(c, &request); err != nil {@@ -213,6 +228,21 @@ func (h *CollectionHandler) UnShare(c *gin.Context) {})}+// BulkUnShare revokes one user's access to up to 100 collections.+func (h *CollectionHandler) BulkUnShare(c *gin.Context) {+ var request ente.BulkCollectionUnshareRequest+ if err := handler.BindJSON(c, &request); err != nil {+ handler.Error(c, stacktrace.Propagate(err, ""))+ return+ }+ results, err := h.Controller.BulkUnShare(c, request)+ if err != nil {+ handler.Error(c, stacktrace.Propagate(err, ""))+ return+ }+ c.JSON(http.StatusOK, gin.H{"results": results})+}+// Leave allows user to leave a shared collection, which is not owned by themfunc (h *CollectionHandler) Leave(c *gin.Context) {cID, err := strconv.ParseInt(c.Param("collectionID"), 10, 64)diff --git a/server/pkg/controller/collections/share.go b/server/pkg/controller/collections/share.goindex e30283d0f7..a3a00cff8a 100644--- a/server/pkg/controller/collections/share.go+++ b/server/pkg/controller/collections/share.go@@ -20,35 +20,19 @@ import (func (c *CollectionController) Share(ctx *gin.Context, req ente.AlterShareRequest) ([]ente.CollectionUser, error) {fromUserID := auth.GetUserID(ctx.Request.Header)- cID := req.CollectionID- encryptedKey := req.EncryptedKey- if err := validateSealedCollectionKey(encryptedKey); err != nil {+ if err := validateSealedCollectionKey(req.EncryptedKey); err != nil {return nil, err}- // default role typerole := ente.VIEWERif req.Role != nil {role = *req.Role}- collection, err := c.CollectionRepo.Get(cID)+ collection, err := c.collectionForShareMutation(req.CollectionID, fromUserID)if err != nil {- return nil, stacktrace.Propagate(err, "")- }- shareActorID := collection.Owner.ID- if fromUserID != collection.Owner.ID {- shareeRole, err := c.CollectionRepo.GetCollectionShareeRole(cID, fromUserID)- if err != nil {- if errors.Is(err, sql.ErrNoRows) {- return nil, stacktrace.Propagate(ente.ErrPermissionDenied, "")- }- return nil, stacktrace.Propagate(err, "")- }- if shareeRole == nil || *shareeRole != ente.ADMIN {- return nil, stacktrace.Propagate(ente.ErrPermissionDenied, "")- }+ return nil, err}- if !collection.AllowSharing() {+ if !collection.AllowParticipantSharing(role) {return nil, stacktrace.Propagate(ente.ErrBadRequest, "sharing %s is not allowed", collection.Type)}@@ -56,23 +40,180 @@ func (c *CollectionController) Share(ctx *gin.Context, req ente.AlterShareRequesif err != nil {return nil, stacktrace.Propagate(err, "")}- if toUserID == fromUserID {- return nil, stacktrace.Propagate(ente.ErrBadRequest, "Can not share collection with self")- }- if toUserID == collection.Owner.ID {- return nil, stacktrace.Propagate(ente.ErrBadRequest, "Can not share collection with owner")+ if err := validateShareRecipient(fromUserID, collection.Owner.ID, toUserID); err != nil {+ return nil, err}- err = c.CollectionRepo.Share(cID, shareActorID, toUserID, encryptedKey, role, time.Microseconds())+ err = c.CollectionRepo.Share(+ req.CollectionID,+ collection.Owner.ID,+ toUserID,+ req.EncryptedKey,+ role,+ time.Microseconds(),+ )if err != nil {return nil, stacktrace.Propagate(err, "")}- sharees, err := c.GetSharees(ctx, cID, fromUserID)+ sharees, err := c.GetSharees(ctx, req.CollectionID, fromUserID)if err != nil {return nil, stacktrace.Propagate(err, "")}return sharees, nil}+func (c *CollectionController) BulkShare(+ ctx *gin.Context,+ req ente.BulkCollectionShareRequest,+) ([]ente.BulkCollectionShareResult, error) {+ if err := validateCollectionShareBatch(req.Collections, req.Source); err != nil {+ return nil, err+ }+ fromUserID := auth.GetUserID(ctx.Request.Header)+ if err := c.validateBulkShareRecipient(fromUserID, req.RecipientUserID); err != nil {+ return nil, err+ }++ results := make([]ente.BulkCollectionShareResult, 0, len(req.Collections))+ for _, item := range req.Collections {+ status, err := c.shareCollectionWithUserID(+ ctx,+ fromUserID,+ req.RecipientUserID,+ req.Source,+ item,+ )+ if err != nil {+ log.WithError(err).WithFields(log.Fields{+ "collection_id": item.CollectionID,+ "from_user_id": fromUserID,+ "recipient_user_id": req.RecipientUserID,+ }).Warn("bulk collection share failed")+ status = ente.CollectionShareOperationFailed+ }+ results = append(results, ente.BulkCollectionShareResult{+ CollectionID: item.CollectionID,+ Status: status,+ })+ }+ return results, nil+}++func (c *CollectionController) validateBulkShareRecipient(actorUserID, recipientUserID int64) error {+ if actorUserID == recipientUserID {+ return stacktrace.Propagate(ente.ErrBadRequest, "Can not share collections with self")+ }+ _, err := c.UserRepo.Get(recipientUserID)+ if errors.Is(err, sql.ErrNoRows) {+ return stacktrace.Propagate(ente.ErrNotFound, "")+ }+ return stacktrace.Propagate(err, "")+}++func (c *CollectionController) shareCollectionWithUserID(+ ctx context.Context,+ fromUserID int64,+ toUserID int64,+ source ente.CollectionShareSource,+ item ente.BulkCollectionShareItem,+) (ente.CollectionShareStatus, error) {+ if err := validateSealedCollectionKey(item.EncryptedKey); err != nil {+ return "", err+ }+ collection, err := c.collectionForShareMutation(item.CollectionID, fromUserID)+ if err != nil {+ return "", err+ }+ if source == ente.AutomaticShare && fromUserID != collection.Owner.ID {+ return "", stacktrace.Propagate(ente.ErrPermissionDenied, "")+ }+ if !collection.AllowParticipantSharing(item.Role) {+ return "", stacktrace.Propagate(+ ente.ErrBadRequest,+ "sharing %s as %s is not allowed",+ collection.Type,+ item.Role,+ )+ }+ if err := validateShareRecipient(fromUserID, collection.Owner.ID, toUserID); err != nil {+ return "", err+ }+ updationTime := time.Microseconds()+ if source == ente.ManualShare {+ err := c.CollectionRepo.Share(+ item.CollectionID,+ collection.Owner.ID,+ toUserID,+ item.EncryptedKey,+ item.Role,+ updationTime,+ )+ return ente.CollectionShared, err+ }+ return c.CollectionRepo.ShareAutomatically(+ ctx,+ item.CollectionID,+ collection.Owner.ID,+ toUserID,+ item.EncryptedKey,+ item.Role,+ updationTime,+ )+}++func (c *CollectionController) collectionForShareMutation(+ collectionID int64,+ actorUserID int64,+) (ente.Collection, error) {+ collection, err := c.CollectionRepo.Get(collectionID)+ if err != nil {+ return ente.Collection{}, stacktrace.Propagate(err, "")+ }+ if actorUserID == collection.Owner.ID {+ return collection, nil+ }+ shareeRole, err := c.CollectionRepo.GetCollectionShareeRole(collectionID, actorUserID)+ if err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return ente.Collection{}, stacktrace.Propagate(ente.ErrPermissionDenied, "")+ }+ return ente.Collection{}, stacktrace.Propagate(err, "")+ }+ if shareeRole == nil || *shareeRole != ente.ADMIN {+ return ente.Collection{}, stacktrace.Propagate(ente.ErrPermissionDenied, "")+ }+ return collection, nil+}++func validateShareRecipient(actorUserID, ownerUserID, recipientUserID int64) error {+ if recipientUserID == actorUserID {+ return stacktrace.Propagate(ente.ErrBadRequest, "Can not share collection with self")+ }+ if recipientUserID == ownerUserID {+ return stacktrace.Propagate(ente.ErrBadRequest, "Can not share collection with owner")+ }+ return nil+}++func validateCollectionShareBatch(+ items []ente.BulkCollectionShareItem,+ source ente.CollectionShareSource,+) error {+ if !source.IsValid() || len(items) == 0 {+ return stacktrace.Propagate(ente.ErrBadRequest, "")+ }+ if len(items) > ente.MaxCollectionShareBatchSize {+ return stacktrace.Propagate(ente.ErrBatchSizeTooLarge, "")+ }+ seen := make(map[int64]struct{}, len(items))+ for _, item := range items {+ if _, exists := seen[item.CollectionID]; exists {+ return stacktrace.Propagate(ente.ErrBadRequest, "duplicate collection ID %d", item.CollectionID)+ }+ seen[item.CollectionID] = struct{}{}+ }+ return nil+}+func (c *CollectionController) JoinViaLink(ctx *gin.Context, req ente.JoinCollectionViaLinkRequest) error {if err := validateSealedCollectionKey(req.EncryptedKey); err != nil {return err@@ -126,21 +267,9 @@ func (c *CollectionController) JoinViaLink(ctx *gin.Context, req ente.JoinCollec// UnShare unshares a collection with a userfunc (c *CollectionController) UnShare(ctx *gin.Context, cID int64, fromUserID int64, toUserEmail string) ([]ente.CollectionUser, error) {- collection, err := c.CollectionRepo.Get(cID)+ collection, err := c.collectionForShareMutation(cID, fromUserID)if err != nil {- return nil, stacktrace.Propagate(err, "")- }- if fromUserID != collection.Owner.ID {- shareeRole, err := c.CollectionRepo.GetCollectionShareeRole(cID, fromUserID)- if err != nil {- if errors.Is(err, sql.ErrNoRows) {- return nil, stacktrace.Propagate(ente.ErrPermissionDenied, "")- }- return nil, stacktrace.Propagate(err, "")- }- if shareeRole == nil || *shareeRole != ente.ADMIN {- return nil, stacktrace.Propagate(ente.ErrPermissionDenied, "")- }+ return nil, err}sharees, err := c.CollectionRepo.GetSharees(cID)@@ -160,14 +289,113 @@ func (c *CollectionController) UnShare(ctx *gin.Context, cID int64, fromUserID iif err != nil {return nil, stacktrace.Propagate(err, "")}- if err := c.removeUserSocialActivity(ctx, cID, toUserID); err != nil {+ if err := c.cleanupRevokedShare(ctx, cID, toUserID); err != nil {return nil, err}- err = c.CastRepo.RevokeForGivenUserAndCollection(ctx, cID, toUserID)+ return slices.Delete(sharees, toUserIndex, toUserIndex+1), nil+}++func (c *CollectionController) BulkUnShare(+ ctx *gin.Context,+ req ente.BulkCollectionUnshareRequest,+) ([]ente.BulkCollectionShareResult, error) {+ // Automatic callers must submit only shares they previously created.+ if err := validateCollectionUnshareBatch(req.CollectionIDs, req.Source); err != nil {+ return nil, err+ }+ fromUserID := auth.GetUserID(ctx.Request.Header)+ if err := c.validateBulkShareRecipient(fromUserID, req.RecipientUserID); err != nil {+ return nil, err+ }++ results := make([]ente.BulkCollectionShareResult, 0, len(req.CollectionIDs))+ for _, collectionID := range req.CollectionIDs {+ status, err := c.unshareCollectionWithUserID(+ ctx,+ collectionID,+ fromUserID,+ req.RecipientUserID,+ req.Source,+ )+ if err != nil {+ log.WithError(err).WithFields(log.Fields{+ "collection_id": collectionID,+ "from_user_id": fromUserID,+ "recipient_user_id": req.RecipientUserID,+ }).Warn("bulk collection unshare failed")+ status = ente.CollectionShareOperationFailed+ }+ results = append(results, ente.BulkCollectionShareResult{+ CollectionID: collectionID,+ Status: status,+ })+ }+ return results, nil+}++func (c *CollectionController) unshareCollectionWithUserID(+ ctx context.Context,+ collectionID int64,+ fromUserID int64,+ toUserID int64,+ source ente.CollectionShareSource,+) (ente.CollectionShareStatus, error) {+ collection, err := c.collectionForShareMutation(collectionID, fromUserID)if err != nil {- return nil, stacktrace.Propagate(err, "")+ return "", err}- return slices.Delete(sharees, toUserIndex, toUserIndex+1), nil+ if source == ente.AutomaticShare && fromUserID != collection.Owner.ID {+ return "", stacktrace.Propagate(ente.ErrPermissionDenied, "")+ }+ if err := validateShareRecipient(fromUserID, collection.Owner.ID, toUserID); err != nil {+ return "", err+ }++ status, err := c.CollectionRepo.UnShareContext(ctx, collectionID, toUserID)+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if status == ente.CollectionNotShared {+ return status, nil+ }+ if err := c.cleanupRevokedShare(ctx, collectionID, toUserID); err != nil {+ return "", err+ }+ return status, nil+}++func (c *CollectionController) cleanupRevokedShare(+ ctx context.Context,+ collectionID int64,+ userID int64,+) error {+ if err := c.removeUserSocialActivity(ctx, collectionID, userID); err != nil {+ return err+ }+ if err := c.CastRepo.RevokeForGivenUserAndCollection(ctx, collectionID, userID); err != nil {+ return stacktrace.Propagate(err, "")+ }+ return nil+}++func validateCollectionUnshareBatch(+ collectionIDs []int64,+ source ente.CollectionShareSource,+) error {+ if !source.IsValid() || len(collectionIDs) == 0 {+ return stacktrace.Propagate(ente.ErrBadRequest, "")+ }+ if len(collectionIDs) > ente.MaxCollectionShareBatchSize {+ return stacktrace.Propagate(ente.ErrBatchSizeTooLarge, "")+ }+ seen := make(map[int64]struct{}, len(collectionIDs))+ for _, collectionID := range collectionIDs {+ if _, exists := seen[collectionID]; exists {+ return stacktrace.Propagate(ente.ErrBadRequest, "duplicate collection ID %d", collectionID)+ }+ seen[collectionID] = struct{}{}+ }+ return nil}func shareeIndexForEmail(sharees []ente.CollectionUser, targetEmail string) int {diff --git a/server/pkg/controller/collections/share_test.go b/server/pkg/controller/collections/share_test.goindex fd42dee889..4661f4b2cb 100644--- a/server/pkg/controller/collections/share_test.go+++ b/server/pkg/controller/collections/share_test.go@@ -1,6 +1,7 @@package collectionsimport (+ "context""database/sql""errors""net/http/httptest"@@ -38,13 +39,22 @@ func newShareTestCollectionRepo(db *sql.DB) *repo.CollectionRepository {}func createShareTestCollection(t *testing.T, collectionRepo *repo.CollectionRepository, ownerID int64) int64 {+ return createShareTestCollectionOfType(t, collectionRepo, ownerID, "album")+}++func createShareTestCollectionOfType(+ t *testing.T,+ collectionRepo *repo.CollectionRepository,+ ownerID int64,+ collectionType string,+) int64 {t.Helper()collection, err := collectionRepo.Create(ente.Collection{Owner: ente.CollectionUser{ID: ownerID},EncryptedKey: "encrypted-key",KeyDecryptionNonce: "key-nonce",Name: "Test collection",- Type: "album",+ Type: collectionType,Attributes: ente.CollectionAttributes{},UpdationTime: 1,App: string(ente.Photos),@@ -55,6 +65,38 @@ func createShareTestCollection(t *testing.T, collectionRepo *repo.CollectionReporeturn collection.ID}+func setupCollectionShareTest(+ t *testing.T,+) (*sql.DB, *repo.CollectionRepository, int64, int64) {+ t.Helper()+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() { testutil.ResetTables(t, db) })+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: 1,+ Email: "[email protected]",+ CreationTime: 1,+ })+ shareeID := testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: 2,+ Email: "[email protected]",+ CreationTime: 1,+ })+ return db, newShareTestCollectionRepo(db), ownerID, shareeID+}++func requireCollectionShareStatus(+ t *testing.T,+ status, want ente.CollectionShareStatus,+ err error,+) {+ t.Helper()+ if err != nil || status != want {+ t.Fatalf("share status = %q, want %q; error = %v", status, want, err)+ }+}+func addShareTestShare(t *testing.T,collectionRepo *repo.CollectionRepository,@@ -250,3 +292,192 @@ func TestCollectionOwnerCannotBecomeShareeOrBeUnshared(t *testing.T) {t.Fatalf("owner state changed: share deleted=%t, file deleted=%t", ownerShareDeleted, ownerFileDeleted)}}++func TestAutomaticShareLifecycle(t *testing.T) {+ db, collectionRepo, ownerID, shareeID := setupCollectionShareTest(t)+ ctx := context.Background()++ manualCollectionID := createShareTestCollection(t, collectionRepo, ownerID)+ if err := collectionRepo.Share(+ manualCollectionID,+ ownerID,+ shareeID,+ "manual-key",+ ente.ADMIN,+ 1,+ ); err != nil {+ t.Fatal(err)+ }+ status, err := collectionRepo.ShareAutomatically(+ ctx,+ manualCollectionID,+ ownerID,+ shareeID,+ "automatic-key",+ ente.VIEWER,+ 2,+ )+ requireCollectionShareStatus(t, status, ente.CollectionAlreadyShared, err)++ var encryptedKey, role string+ var isDeleted bool+ err = db.QueryRow(+ `SELECT encrypted_key, role_type, is_deleted+ FROM collection_shares+ WHERE collection_id = $1 AND to_user_id = $2`,+ manualCollectionID,+ shareeID,+ ).Scan(&encryptedKey, &role, &isDeleted)+ if err != nil {+ t.Fatal(err)+ }+ if encryptedKey != "manual-key" || role != string(ente.ADMIN) || isDeleted {+ t.Fatalf(+ "manual share changed: key=%q role=%q deleted=%t",+ encryptedKey,+ role,+ isDeleted,+ )+ }+ status, err = collectionRepo.UnShareContext(+ ctx,+ manualCollectionID,+ shareeID,+ )+ requireCollectionShareStatus(t, status, ente.CollectionUnshared, err)+ status, err = collectionRepo.ShareAutomatically(+ ctx,+ manualCollectionID,+ ownerID,+ shareeID,+ "automatic-key",+ ente.VIEWER,+ 3,+ )+ requireCollectionShareStatus(t, status, ente.CollectionBlockedPriorRemoval, err)++ automaticCollectionID := createShareTestCollection(t, collectionRepo, ownerID)+ status, err = collectionRepo.ShareAutomatically(+ ctx,+ automaticCollectionID,+ ownerID,+ shareeID,+ "automatic-key",+ ente.VIEWER,+ 1,+ )+ requireCollectionShareStatus(t, status, ente.CollectionShared, err)+}++func TestUncategorizedCollectionsOnlyAllowViewerShares(t *testing.T) {+ _, collectionRepo, ownerID, shareeID := setupCollectionShareTest(t)+ collectionID := createShareTestCollectionOfType(+ t,+ collectionRepo,+ ownerID,+ "uncategorized",+ )+ controller := &CollectionController{CollectionRepo: collectionRepo}+ item := ente.BulkCollectionShareItem{+ CollectionID: collectionID,+ EncryptedKey: b64OfLen(sealedCollectionKeyLen),+ Role: ente.VIEWER,+ }++ status, err := controller.shareCollectionWithUserID(+ context.Background(),+ ownerID,+ shareeID,+ ente.ManualShare,+ item,+ )+ requireCollectionShareStatus(t, status, ente.CollectionShared, err)++ item.Role = ente.ADMIN+ _, err = controller.shareCollectionWithUserID(+ context.Background(),+ ownerID,+ shareeID,+ ente.ManualShare,+ item,+ )+ if !errors.Is(err, ente.ErrBadRequest) {+ t.Fatalf("admin share error = %v, want %v", err, ente.ErrBadRequest)+ }+}++func TestBulkShareAndUnshareReturnPerCollectionStatuses(t *testing.T) {+ db, collectionRepo, ownerID, shareeID := setupCollectionShareTest(t)+ albumID := createShareTestCollection(t, collectionRepo, ownerID)+ neverSharedID := createShareTestCollection(t, collectionRepo, ownerID)+ uncategorizedID := createShareTestCollectionOfType(+ t,+ collectionRepo,+ ownerID,+ "uncategorized",+ )+ controller := &CollectionController{+ CollectionRepo: collectionRepo,+ UserRepo: &repo.UserRepository{+ DB: db,+ SecretEncryptionKey: testutil.SecretEncryptionKey(),+ },+ CastRepo: &castRepo.Repository{DB: db},+ }+ ctx, _ := gin.CreateTestContext(httptest.NewRecorder())+ ctx.Request = httptest.NewRequest("POST", "/collections/share/bulk", nil)+ ctx.Request.Header.Set("X-Auth-User-ID", strconv.FormatInt(ownerID, 10))++ results, err := controller.BulkShare(ctx, ente.BulkCollectionShareRequest{+ RecipientUserID: shareeID,+ Source: ente.AutomaticShare,+ Collections: []ente.BulkCollectionShareItem{+ {+ CollectionID: albumID,+ EncryptedKey: b64OfLen(sealedCollectionKeyLen),+ Role: ente.VIEWER,+ },+ {+ CollectionID: uncategorizedID,+ EncryptedKey: b64OfLen(sealedCollectionKeyLen),+ Role: ente.ADMIN,+ },+ },+ })+ if err != nil {+ t.Fatal(err)+ }+ if results[0].Status != ente.CollectionShared ||+ results[1].Status != ente.CollectionShareOperationFailed {+ t.Fatalf("bulk share results = %+v", results)+ }++ unshareResults, err := controller.BulkUnShare(ctx, ente.BulkCollectionUnshareRequest{+ RecipientUserID: shareeID,+ Source: ente.AutomaticShare,+ CollectionIDs: []int64{albumID, neverSharedID},+ })+ if err != nil {+ t.Fatal(err)+ }+ if unshareResults[0].Status != ente.CollectionUnshared ||+ unshareResults[1].Status != ente.CollectionNotShared {+ t.Fatalf("bulk unshare results = %+v", unshareResults)+ }+}++func TestBulkShareRejectsOversizedBatch(t *testing.T) {+ items := make([]ente.BulkCollectionShareItem, ente.MaxCollectionShareBatchSize+1)+ for index := range items {+ items[index].CollectionID = int64(index + 1)+ }+ controller := &CollectionController{}+ _, err := controller.BulkShare(&gin.Context{}, ente.BulkCollectionShareRequest{+ RecipientUserID: 1,+ Source: ente.AutomaticShare,+ Collections: items,+ })+ if !errors.Is(err, ente.ErrBatchSizeTooLarge) {+ t.Fatalf("oversized batch error = %v, want %v", err, ente.ErrBatchSizeTooLarge)+ }+}diff --git a/server/pkg/repo/collection.go b/server/pkg/repo/collection.goindex 8445010a9c..6c2a435e97 100644--- a/server/pkg/repo/collection.go+++ b/server/pkg/repo/collection.go@@ -536,6 +536,64 @@ func (repo *CollectionRepository) Share(return stacktrace.Propagate(err, "")}+// ShareAutomatically creates a share without modifying a prior share.+func (repo *CollectionRepository) ShareAutomatically(+ ctx context.Context,+ collectionID int64,+ fromUserID int64,+ toUserID int64,+ encryptedKey string,+ role ente.CollectionParticipantRole,+ updationTime int64,+) (ente.CollectionShareStatus, error) {+ if role != ente.VIEWER && role != ente.COLLABORATOR && role != ente.ADMIN {+ return "", stacktrace.Propagate(fmt.Errorf("invalid role %s", role), "")+ }+ tx, err := repo.DB.BeginTx(ctx, nil)+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ defer tx.Rollback()++ result, err := tx.ExecContext(ctx, `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 NOTHING+ `, collectionID, fromUserID, toUserID, encryptedKey, updationTime, role, updationTime)+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ affected, err := result.RowsAffected()+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if affected == 0 {+ var isDeleted bool+ err := tx.QueryRowContext(ctx, `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 {+ return "", stacktrace.Propagate(err, "")+ }+ if isDeleted {+ return ente.CollectionBlockedPriorRemoval, nil+ }+ return ente.CollectionAlreadyShared, nil+ }++ if _, err = tx.ExecContext(ctx, `UPDATE collections SET updation_time = $1 WHERE collection_id = $2`, updationTime, collectionID); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if err := tx.Commit(); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ return ente.CollectionShared, nil+}+// UpdateShareeMetadata shares a collection with a userIDfunc (repo *CollectionRepository) UpdateShareeMetadata(collectionID int64,@@ -578,37 +636,67 @@ func (repo *CollectionRepository) UpdateShareeMetadata(// UnShare un-shares a collection from a userIDfunc (repo *CollectionRepository) UnShare(collectionID int64, toUserID int64) error {+ _, err := repo.UnShareContext(context.Background(), collectionID, toUserID)+ return err+}++// UnShareContext revokes access to a collection.+func (repo *CollectionRepository) UnShareContext(+ ctx context.Context,+ collectionID int64,+ toUserID int64,+) (ente.CollectionShareStatus, error) {updationTime := time.Microseconds()- context := context.Background()- tx, err := repo.DB.BeginTx(context, nil)+ tx, err := repo.DB.BeginTx(ctx, nil)if err != nil {- return stacktrace.Propagate(err, "")+ return "", stacktrace.Propagate(err, "")+ }+ defer tx.Rollback()++ status := ente.CollectionAlreadyUnshared+ var isDeleted bool+ err = tx.QueryRowContext(ctx, `SELECT is_deleted+ FROM collection_shares+ WHERE collection_id = $1 AND to_user_id = $2+ FOR UPDATE`, collectionID, toUserID).Scan(&isDeleted)+ if errors.Is(err, sql.ErrNoRows) {+ return ente.CollectionNotShared, nil}- _, err = tx.ExecContext(context, `UPDATE collection_shares- SET is_deleted = $1, updation_time = $2- WHERE collection_id = $3 AND to_user_id = $4`, true, updationTime, collectionID, toUserID)if err != nil {- tx.Rollback()- return stacktrace.Propagate(err, "")+ return "", stacktrace.Propagate(err, "")}- // remove all the files which were added by this user- // todo: should we also add c_owner_id != toUserId- _, err = tx.ExecContext(context, `UPDATE collection_files- SET is_deleted = $1, updation_time = $2- WHERE collection_id = $3 AND f_owner_id = $4`, true, updationTime, collectionID, toUserID)+ if !isDeleted {+ status = ente.CollectionUnshared+ }+ _, err = tx.ExecContext(ctx, `UPDATE collection_shares+ SET is_deleted = TRUE, updation_time = $1+ WHERE collection_id = $2 AND to_user_id = $3 AND is_deleted = FALSE`,+ updationTime, collectionID, toUserID)if err != nil {- tx.Rollback()- return stacktrace.Propagate(err, "")+ return "", stacktrace.Propagate(err, "")}- _, err = tx.ExecContext(context, `UPDATE collections SET updation_time = $1- WHERE collection_id = $2`, updationTime, collectionID)+ result, err := tx.ExecContext(ctx, `UPDATE collection_files+ SET is_deleted = TRUE, updation_time = $1+ WHERE collection_id = $2 AND f_owner_id = $3 AND is_deleted = FALSE`,+ updationTime, collectionID, toUserID)if err != nil {- tx.Rollback()- return stacktrace.Propagate(err, "")+ return "", stacktrace.Propagate(err, "")}- err = tx.Commit()- return stacktrace.Propagate(err, "")+ fileRows, err := result.RowsAffected()+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if status == ente.CollectionUnshared || fileRows > 0 {+ if _, err = tx.ExecContext(ctx, `UPDATE collections SET updation_time = $1+ WHERE collection_id = $2`, updationTime, collectionID); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ }+ if err := tx.Commit(); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ return status, nil}// AddFiles adds files to a collection