Skip to content

armgit / ente

Public Imported from GitHub
0

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

[server] Link sharing support

Neeraj Gupta778397b10f63
diff --git a/server/ente/access.go b/server/ente/access.go
index 4133befeb9..b52c073d3c 100644
--- a/server/ente/access.go
+++ b/server/ente/access.go
@@ -39,3 +39,32 @@ func ConvertStringToCollectionParticipantRole(value string) CollectionParticipan
return UNKNOWN
}
}
+
+func (c *CollectionParticipantRole) IsValidShareRole() bool {
+ if c == nil {
+ return false
+ }
+ return *c == VIEWER || *c == COLLABORATOR || *c == ADMIN || *c == OWNER
+}
+
+func (c CollectionParticipantRole) roleRank() int {
+ switch c {
+ case VIEWER:
+ return 1
+ case COLLABORATOR:
+ return 2
+ case ADMIN:
+ return 3
+ case OWNER:
+ return 4
+ default:
+ return 0
+ }
+}
+
+func (c CollectionParticipantRole) Satisfies(min *CollectionParticipantRole) bool {
+ if min == nil {
+ return true
+ }
+ return c.roleRank() >= (*min).roleRank()
+}
diff --git a/server/ente/public_collection.go b/server/ente/public_collection.go
index 59e09f44bd..d7756f702e 100644
--- a/server/ente/public_collection.go
+++ b/server/ente/public_collection.go
@@ -19,22 +19,23 @@ type CreatePublicAccessTokenRequest struct {
}
type UpdatePublicAccessTokenRequest struct {
- CollectionID int64 `json:"collectionID" binding:"required"`
- ValidTill *int64 `json:"validTill"`
- DeviceLimit *int `json:"deviceLimit"`
- PassHash *string `json:"passHash"`
- Nonce *string `json:"nonce"`
- MemLimit *int64 `json:"memLimit"`
- OpsLimit *int64 `json:"opsLimit"`
- EnableDownload *bool `json:"enableDownload"`
- EnableCollect *bool `json:"enableCollect"`
- DisablePassword *bool `json:"disablePassword"`
- EnableJoin *bool `json:"enableJoin"`
+ CollectionID int64 `json:"collectionID" binding:"required"`
+ ValidTill *int64 `json:"validTill"`
+ DeviceLimit *int `json:"deviceLimit"`
+ PassHash *string `json:"passHash"`
+ Nonce *string `json:"nonce"`
+ MemLimit *int64 `json:"memLimit"`
+ OpsLimit *int64 `json:"opsLimit"`
+ EnableDownload *bool `json:"enableDownload"`
+ EnableCollect *bool `json:"enableCollect"`
+ DisablePassword *bool `json:"disablePassword"`
+ EnableJoin *bool `json:"enableJoin"`
+ MinRole *CollectionParticipantRole `json:"minRole"`
}
func (ut *UpdatePublicAccessTokenRequest) Validate() error {
if ut.DeviceLimit == nil && ut.ValidTill == nil && ut.DisablePassword == nil &&
- ut.Nonce == nil && ut.PassHash == nil && ut.EnableDownload == nil && ut.EnableCollect == nil && ut.EnableJoin == nil {
+ ut.Nonce == nil && ut.PassHash == nil && ut.EnableDownload == nil && ut.EnableCollect == nil && ut.EnableJoin == nil && ut.MinRole == nil {
return NewBadRequestWithMessage("all parameters are missing")
}
@@ -56,6 +57,10 @@ func (ut *UpdatePublicAccessTokenRequest) Validate() error {
if allPassParamsPresent && ut.DisablePassword != nil && *ut.DisablePassword {
return NewBadRequestWithMessage("can not set and disable password in same request")
}
+
+ if ut.MinRole != nil && !ut.MinRole.IsValidShareRole() {
+ return NewBadRequestWithMessage(fmt.Sprintf("invalid min role %s", *ut.MinRole))
+ }
return nil
}
@@ -82,6 +87,7 @@ type CollectionLinkRow struct {
EnableDownload bool
EnableCollect bool
EnableJoin bool
+ MinRole *CollectionParticipantRole
}
func (p CollectionLinkRow) CanJoin() error {
@@ -110,10 +116,11 @@ type PublicURL struct {
EnableCollect bool `json:"enableCollect"`
PasswordEnabled bool `json:"passwordEnabled"`
// Nonce contains the nonce value for the password if the link is password protected.
- Nonce *string `json:"nonce,omitempty"`
- MemLimit *int64 `json:"memLimit,omitempty"`
- OpsLimit *int64 `json:"opsLimit,omitempty"`
- EnableJoin bool `json:"enableJoin"`
+ Nonce *string `json:"nonce,omitempty"`
+ MemLimit *int64 `json:"memLimit,omitempty"`
+ OpsLimit *int64 `json:"opsLimit,omitempty"`
+ EnableJoin bool `json:"enableJoin"`
+ MinRole *CollectionParticipantRole `json:"minRole,omitempty"`
}
type PublicAccessContext struct {
@@ -123,6 +130,19 @@ type PublicAccessContext struct {
CollectionID int64
}
+func FilterPublicURLsForRole(urls []PublicURL, role CollectionParticipantRole) []PublicURL {
+ result := make([]PublicURL, 0, len(urls))
+ if role == UNKNOWN {
+ role = VIEWER
+ }
+ for _, url := range urls {
+ if role.Satisfies(url.MinRole) {
+ result = append(result, url)
+ }
+ }
+ return result
+}
+
// PublicCollectionSummary represents an information about a public collection
type PublicCollectionSummary struct {
ID int64
diff --git a/server/ente/public_collection_test.go b/server/ente/public_collection_test.go
new file mode 100644
index 0000000000..9b23424a03
--- /dev/null
+++ b/server/ente/public_collection_test.go
@@ -0,0 +1,50 @@
+package ente
+
+import "testing"
+
+func TestFilterPublicURLsForRole(t *testing.T) {
+ viewer := VIEWER
+ collaborator := COLLABORATOR
+
+ urls := []PublicURL{
+ {URL: "unrestricted"},
+ {URL: "viewer-only", MinRole: &viewer},
+ {URL: "collaborator-only", MinRole: &collaborator},
+ }
+
+ tests := []struct {
+ name string
+ role CollectionParticipantRole
+ expected []string
+ }{
+ {
+ name: "viewer gets unrestricted and viewer urls",
+ role: VIEWER,
+ expected: []string{"unrestricted", "viewer-only"},
+ },
+ {
+ name: "collaborator gets all urls",
+ role: COLLABORATOR,
+ expected: []string{"unrestricted", "viewer-only", "collaborator-only"},
+ },
+ {
+ name: "unknown treated as viewer",
+ role: UNKNOWN,
+ expected: []string{"unrestricted", "viewer-only"},
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ filtered := FilterPublicURLsForRole(urls, tc.role)
+ if len(filtered) != len(tc.expected) {
+ t.Fatalf("expected %d urls, got %d", len(tc.expected), len(filtered))
+ }
+ for i := range filtered {
+ if filtered[i].URL != tc.expected[i] {
+ t.Fatalf("expected url %s at index %d, got %s", tc.expected[i], i, filtered[i].URL)
+ }
+ }
+ })
+ }
+}
diff --git a/server/migrations/110_public_collection_min_role.down.sql b/server/migrations/110_public_collection_min_role.down.sql
new file mode 100644
index 0000000000..2ad8a7955e
--- /dev/null
+++ b/server/migrations/110_public_collection_min_role.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE public_collection_tokens
+ DROP COLUMN IF EXISTS min_role;
diff --git a/server/migrations/110_public_collection_min_role.up.sql b/server/migrations/110_public_collection_min_role.up.sql
new file mode 100644
index 0000000000..741dc483dd
--- /dev/null
+++ b/server/migrations/110_public_collection_min_role.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE public_collection_tokens
+ ADD COLUMN IF NOT EXISTS min_role role_enum;
diff --git a/server/pkg/controller/access/collection.go b/server/pkg/controller/access/collection.go
index 8f06307769..ecb1f8f8cb 100644
--- a/server/pkg/controller/access/collection.go
+++ b/server/pkg/controller/access/collection.go
@@ -42,8 +42,12 @@ func (c controllerImpl) GetCollection(ctx *gin.Context, req *GetCollectionParams
return nil, stacktrace.Propagate(err, "")
}
// Hide public URL info for non-collection owners
- collection.PublicURLs = nil
- role = *shareeRole
+ if shareeRole == nil {
+ return nil, stacktrace.Propagate(ente.ErrPermissionDenied, "")
+ }
+ roleValue := *shareeRole
+ collection.PublicURLs = ente.FilterPublicURLsForRole(collection.PublicURLs, roleValue)
+ role = roleValue
} else {
role = ente.OWNER
}
diff --git a/server/pkg/controller/public/collection_link.go b/server/pkg/controller/public/collection_link.go
index 5ce6072007..60411bb790 100644
--- a/server/pkg/controller/public/collection_link.go
+++ b/server/pkg/controller/public/collection_link.go
@@ -74,6 +74,7 @@ func (c *CollectionLinkController) CreateLink(ctx *gin.Context, req ente.CreateP
EnableDownload: true,
EnableCollect: req.EnableCollect,
PasswordEnabled: false,
+ MinRole: nil,
}
return response, nil
}
@@ -144,6 +145,11 @@ func (c *CollectionLinkController) UpdateSharedUrl(ctx *gin.Context, req ente.Up
if req.EnableJoin != nil {
publicCollectionToken.EnableJoin = *req.EnableJoin
}
+ if req.MinRole != nil {
+ role := *req.MinRole
+ rolePtr := role
+ publicCollectionToken.MinRole = &rolePtr
+ }
err = c.CollectionLinkRepo.UpdatePublicCollectionToken(ctx, publicCollectionToken)
if err != nil {
return ente.PublicURL{}, stacktrace.Propagate(err, "")
@@ -156,6 +162,7 @@ func (c *CollectionLinkController) UpdateSharedUrl(ctx *gin.Context, req ente.Up
EnableDownload: publicCollectionToken.EnableDownload,
EnableCollect: publicCollectionToken.EnableCollect,
EnableJoin: publicCollectionToken.EnableJoin,
+ MinRole: publicCollectionToken.MinRole,
PasswordEnabled: publicCollectionToken.PassHash != nil && *publicCollectionToken.PassHash != "",
Nonce: publicCollectionToken.Nonce,
MemLimit: publicCollectionToken.MemLimit,
diff --git a/server/pkg/repo/collection.go b/server/pkg/repo/collection.go
index 437f3981cf..be4a02e573 100644
--- a/server/pkg/repo/collection.go
+++ b/server/pkg/repo/collection.go
@@ -111,7 +111,7 @@ func (repo *CollectionRepository) GetCollectionsOwnedByUserV2(userID int64, upda
SELECT
c.collection_id, c.owner_id, c.encrypted_key,c.key_decryption_nonce, c.name, c.encrypted_name, c.name_decryption_nonce, c.type, c.app, c.attributes, c.updation_time, c.is_deleted, c.magic_metadata, c.pub_magic_metadata,
users.user_id, users.encrypted_email, users.email_decryption_nonce, cs.role_type,
-pct.access_token, pct.valid_till, pct.device_limit, pct.created_at, pct.updated_at, pct.pw_hash, pct.pw_nonce, pct.mem_limit, pct.ops_limit, pct.enable_download, pct.enable_collect, pct.enable_join
+pct.access_token, pct.valid_till, pct.device_limit, pct.created_at, pct.updated_at, pct.pw_hash, pct.pw_nonce, pct.mem_limit, pct.ops_limit, pct.enable_download, pct.enable_collect, pct.enable_join, pct.min_role
FROM collections c
LEFT JOIN collection_shares cs
ON (cs.collection_id = c.collection_id AND cs.is_deleted = false)
@@ -141,11 +141,11 @@ pct.access_token, pct.valid_till, pct.device_limit, pct.created_at, pct.updated_
var pctEnableDownload, pctEnableCollect, pctEnableJoin sql.NullBool
var shareUserID, pctValidTill, pctCreatedAt, pctUpdatedAt, pctMemLimit, pctOpsLimit sql.NullInt64
var encryptedEmail, nonce []byte
- var shareeRoleType, pctToken, pctPwHash, pctPwNonce sql.NullString
+ var shareeRoleType, pctToken, pctPwHash, pctPwNonce, pctMinRole sql.NullString
if err := rows.Scan(&c.ID, &c.Owner.ID, &c.EncryptedKey, &c.KeyDecryptionNonce, &name, &encryptedName, &nameDecryptionNonce, &c.Type, &c.App, &c.Attributes, &c.UpdationTime, &c.IsDeleted, &c.MagicMetadata, &c.PublicMagicMetadata,
&shareUserID, &encryptedEmail, &nonce, &shareeRoleType,
- &pctToken, &pctValidTill, &pctDeviceLimit, &pctCreatedAt, &pctUpdatedAt, &pctPwHash, &pctPwNonce, &pctMemLimit, &pctOpsLimit, &pctEnableDownload, &pctEnableCollect, &pctEnableJoin); err != nil {
+ &pctToken, &pctValidTill, &pctDeviceLimit, &pctCreatedAt, &pctUpdatedAt, &pctPwHash, &pctPwNonce, &pctMemLimit, &pctOpsLimit, &pctEnableDownload, &pctEnableCollect, &pctEnableJoin, &pctMinRole); err != nil {
return nil, stacktrace.Propagate(err, "")
}
@@ -192,6 +192,11 @@ pct.access_token, pct.valid_till, pct.device_limit, pct.created_at, pct.updated_
url.MemLimit = &pctMemLimit.Int64
url.OpsLimit = &pctOpsLimit.Int64
}
+ if pctMinRole.Valid {
+ role := ente.ConvertStringToCollectionParticipantRole(pctMinRole.String)
+ rolePtr := role
+ url.MinRole = &rolePtr
+ }
currentCollection.PublicURLs = append(currentCollection.PublicURLs, url)
}
}
@@ -206,7 +211,7 @@ pct.access_token, pct.valid_till, pct.device_limit, pct.created_at, pct.updated_
// with a user
func (repo *CollectionRepository) GetCollectionsSharedWithUser(userID int64, updationTime int64, app ente.App, limit *int64) ([]ente.Collection, error) {
query := `
- SELECT collections.collection_id, collections.owner_id, users.encrypted_email, users.email_decryption_nonce, collection_shares.encrypted_key, collections.name, collections.encrypted_name, collections.name_decryption_nonce, collections.type, collections.app, collections.pub_magic_metadata, collection_shares.magic_metadata, collections.updation_time, collection_shares.is_deleted
+ SELECT collections.collection_id, collections.owner_id, users.encrypted_email, users.email_decryption_nonce, collection_shares.encrypted_key, collections.name, collections.encrypted_name, collections.name_decryption_nonce, collections.type, collections.app, collections.pub_magic_metadata, collection_shares.magic_metadata, collections.updation_time, collection_shares.is_deleted, collection_shares.role_type
FROM collections
INNER JOIN users
ON collections.owner_id = users.user_id
@@ -225,11 +230,13 @@ func (repo *CollectionRepository) GetCollectionsSharedWithUser(userID int64, upd
defer rows.Close()
collections := make([]ente.Collection, 0)
+ shareeRoleByCollection := make(map[int64]ente.CollectionParticipantRole)
for rows.Next() {
var c ente.Collection
var collectionName, encryptedName, nameDecryptionNonce sql.NullString
var encryptedEmail, emailDecryptionNonce []byte
- if err := rows.Scan(&c.ID, &c.Owner.ID, &encryptedEmail, &emailDecryptionNonce, &c.EncryptedKey, &collectionName, &encryptedName, &nameDecryptionNonce, &c.Type, &c.App, &c.PublicMagicMetadata, &c.SharedMagicMetadata, &c.UpdationTime, &c.IsDeleted); err != nil {
+ var roleType sql.NullString
+ if err := rows.Scan(&c.ID, &c.Owner.ID, &encryptedEmail, &emailDecryptionNonce, &c.EncryptedKey, &collectionName, &encryptedName, &nameDecryptionNonce, &c.Type, &c.App, &c.PublicMagicMetadata, &c.SharedMagicMetadata, &c.UpdationTime, &c.IsDeleted, &roleType); err != nil {
return collections, stacktrace.Propagate(err, "")
}
if collectionName.Valid && len(collectionName.String) > 0 {
@@ -260,8 +267,39 @@ func (repo *CollectionRepository) GetCollectionsSharedWithUser(userID int64, upd
}
c.Sharees = sharees
}
+ role := ente.ConvertStringToCollectionParticipantRole(roleType.String)
+ if role == ente.UNKNOWN {
+ role = ente.VIEWER
+ }
+ shareeRoleByCollection[c.ID] = role
collections = append(collections, c)
}
+
+ collectionIDs := make([]int64, 0, len(collections))
+ for _, collection := range collections {
+ if collection.IsDeleted {
+ continue
+ }
+ collectionIDs = append(collectionIDs, collection.ID)
+ }
+ if len(collectionIDs) > 0 {
+ urlMap, err := repo.CollectionLinkRepo.GetCollectionToActivePublicURLMap(context.Background(), collectionIDs, app)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "failed to get public URLs")
+ }
+ for idx := range collections {
+ if collections[idx].IsDeleted {
+ collections[idx].PublicURLs = []ente.PublicURL{}
+ continue
+ }
+ role := shareeRoleByCollection[collections[idx].ID]
+ collections[idx].PublicURLs = ente.FilterPublicURLsForRole(urlMap[collections[idx].ID], role)
+ }
+ } else {
+ for idx := range collections {
+ collections[idx].PublicURLs = []ente.PublicURL{}
+ }
+ }
return collections, nil
}
diff --git a/server/pkg/repo/public/collection_link.go b/server/pkg/repo/public/collection_link.go
index 77e45d1c73..cda8afb817 100644
--- a/server/pkg/repo/public/collection_link.go
+++ b/server/pkg/repo/public/collection_link.go
@@ -85,7 +85,7 @@ func (pcr *CollectionLinkRepo) DisableSharing(ctx context.Context, cID int64) er
// GetCollectionToActivePublicURLMap will return map of collectionID to PublicURLs which are not disabled yet.
// Note: The url could be expired or deviceLimit is already reached
func (pcr *CollectionLinkRepo) GetCollectionToActivePublicURLMap(ctx context.Context, collectionIDs []int64, app ente.App) (map[int64][]ente.PublicURL, error) {
- rows, err := pcr.DB.QueryContext(ctx, `SELECT collection_id, access_token, valid_till, device_limit, enable_download, enable_collect, enable_join, pw_nonce, mem_limit, ops_limit FROM
+ rows, err := pcr.DB.QueryContext(ctx, `SELECT collection_id, access_token, valid_till, device_limit, enable_download, enable_collect, enable_join, min_role, pw_nonce, mem_limit, ops_limit FROM
public_collection_tokens WHERE collection_id = ANY($1) and is_disabled = FALSE`,
pq.Array(collectionIDs))
if err != nil {
@@ -102,10 +102,16 @@ func (pcr *CollectionLinkRepo) GetCollectionToActivePublicURLMap(ctx context.Con
var accessToken string
var nonce *string
var opsLimit, memLimit *int64
- if err = rows.Scan(&collectionID, &accessToken, &publicUrl.ValidTill, &publicUrl.DeviceLimit, &publicUrl.EnableDownload, &publicUrl.EnableCollect, &publicUrl.EnableJoin, &nonce, &memLimit, &opsLimit); err != nil {
+ var minRole sql.NullString
+ if err = rows.Scan(&collectionID, &accessToken, &publicUrl.ValidTill, &publicUrl.DeviceLimit, &publicUrl.EnableDownload, &publicUrl.EnableCollect, &publicUrl.EnableJoin, &minRole, &nonce, &memLimit, &opsLimit); err != nil {
return nil, stacktrace.Propagate(err, "")
}
publicUrl.URL = pcr.GetAlbumUrl(app, accessToken)
+ if minRole.Valid {
+ role := ente.ConvertStringToCollectionParticipantRole(minRole.String)
+ rolePtr := role
+ publicUrl.MinRole = &rolePtr
+ }
if nonce != nil {
publicUrl.Nonce = nonce
publicUrl.MemLimit = memLimit
@@ -121,26 +127,36 @@ func (pcr *CollectionLinkRepo) GetCollectionToActivePublicURLMap(ctx context.Con
// Note: The token could be expired or deviceLimit is already reached
func (pcr *CollectionLinkRepo) GetActiveCollectionLinkRow(ctx context.Context, collectionID int64) (ente.CollectionLinkRow, error) {
row := pcr.DB.QueryRowContext(ctx, `SELECT id, collection_id, access_token, valid_till, device_limit,
- is_disabled, pw_hash, pw_nonce, mem_limit, ops_limit, enable_download, enable_collect, enable_join FROM
+ is_disabled, pw_hash, pw_nonce, mem_limit, ops_limit, enable_download, enable_collect, enable_join, min_role FROM
public_collection_tokens WHERE collection_id = $1 and is_disabled = FALSE`,
collectionID)
//defer rows.Close()
ret := ente.CollectionLinkRow{}
+ var minRole sql.NullString
err := row.Scan(&ret.ID, &ret.CollectionID, &ret.Token, &ret.ValidTill, &ret.DeviceLimit,
- &ret.IsDisabled, &ret.PassHash, &ret.Nonce, &ret.MemLimit, &ret.OpsLimit, &ret.EnableDownload, &ret.EnableCollect, &ret.EnableJoin)
+ &ret.IsDisabled, &ret.PassHash, &ret.Nonce, &ret.MemLimit, &ret.OpsLimit, &ret.EnableDownload, &ret.EnableCollect, &ret.EnableJoin, &minRole)
if err != nil {
return ente.CollectionLinkRow{}, stacktrace.Propagate(err, "")
}
+ if minRole.Valid {
+ role := ente.ConvertStringToCollectionParticipantRole(minRole.String)
+ rolePtr := role
+ ret.MinRole = &rolePtr
+ }
return ret, nil
}
// UpdatePublicCollectionToken will update the row for corresponding public collection token
func (pcr *CollectionLinkRepo) UpdatePublicCollectionToken(ctx context.Context, pct ente.CollectionLinkRow) error {
+ var minRole interface{}
+ if pct.MinRole != nil {
+ minRole = string(*pct.MinRole)
+ }
_, err := pcr.DB.ExecContext(ctx, `UPDATE public_collection_tokens SET valid_till = $1, device_limit = $2,
- pw_hash = $3, pw_nonce = $4, mem_limit = $5, ops_limit = $6, enable_download = $7, enable_collect = $8, enable_join = $9
- where id = $10`,
- pct.ValidTill, pct.DeviceLimit, pct.PassHash, pct.Nonce, pct.MemLimit, pct.OpsLimit, pct.EnableDownload, pct.EnableCollect, pct.EnableJoin, pct.ID)
+ pw_hash = $3, pw_nonce = $4, mem_limit = $5, ops_limit = $6, enable_download = $7, enable_collect = $8, enable_join = $9, min_role = $10
+ where id = $11`,
+ pct.ValidTill, pct.DeviceLimit, pct.PassHash, pct.Nonce, pct.MemLimit, pct.OpsLimit, pct.EnableDownload, pct.EnableCollect, pct.EnableJoin, minRole, pct.ID)
return stacktrace.Propagate(err, "failed to update public collection token")
}
diff --git a/server/pkg/utils/handler/handler.go b/server/pkg/utils/handler/handler.go
index c264fb452d..0ee686b46e 100644
--- a/server/pkg/utils/handler/handler.go
+++ b/server/pkg/utils/handler/handler.go
@@ -53,7 +53,7 @@ func Error(c *gin.Context, err error) {
if isEnteApiErr {
c.AbortWithStatusJSON(enteApiErr.HttpStatusCode, enteApiErr)
} else if httpStatus := httpStatusCode(err); httpStatus != 0 {
- c.AbortWithStatus(httpStatus)
+ c.AbortWithStatusJSON(httpStatus, gin.H{})
} else {
if _, ok := stacktrace.RootCause(err).(validator.ValidationErrors); ok {
c.AbortWithStatus(http.StatusBadRequest)