Skip to content

armgit / ente

Public Imported from GitHub
0

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

Merge branch 'main' into single_file_link

Neeraj Gupta47f0722687d1
diff --cc server/migrations/102_single_file_url.down.sql
index 0000000000,0000000000..2efd3e0053
new file mode 100644
--- /dev/null
+++ b/server/migrations/102_single_file_url.down.sql
@@@ -1,0 -1,0 +1,3 @@@
++
++DROP TABLE IF EXISTS public_file_tokens_access_history;
++DROP TABLE IF EXISTS public_file_tokens;
diff --cc server/migrations/102_single_file_url.up.sql
index 7b1729e9d8,0000000000..3feae46c7f
mode 100644,000000..100644
--- a/server/migrations/102_single_file_url.up.sql
+++ b/server/migrations/102_single_file_url.up.sql
@@@ -1,69 -1,0 +1,42 @@@
+
+
+CREATE TABLE IF NOT EXISTS public_file_tokens
+(
+ id text primary key,
+ file_id bigint NOT NULL,
+ owner_id bigint NOT NULL,
+ access_token text not null,
+ valid_till bigint not null DEFAULT 0,
+ device_limit int not null DEFAULT 0,
+ is_disabled bool not null DEFAULT FALSE,
+ enable_download bool not null DEFAULT TRUE,
+ password_info JSONB,
+ created_at bigint NOT NULL DEFAULT now_utc_micro_seconds(),
+ updated_at bigint NOT NULL DEFAULT now_utc_micro_seconds()
+);
+
+
+CREATE OR REPLACE TRIGGER update_public_file_tokens_updated_at
+ BEFORE UPDATE
+ ON public_file_tokens
+ FOR EACH ROW
+EXECUTE PROCEDURE
+ trigger_updated_at_microseconds_column();
+
+
+CREATE TABLE IF NOT EXISTS public_file_tokens_access_history
+(
+ id text NOT NULL,
+ ip text not null,
+ user_agent text not null,
+ created_at bigint NOT NULL DEFAULT now_utc_micro_seconds(),
+ CONSTRAINT unique_access_id_ip_ua UNIQUE (id, ip, user_agent),
+ CONSTRAINT fk_public_file_history_token_id
+ FOREIGN KEY (id)
+ REFERENCES public_file_tokens (id)
+ ON DELETE CASCADE
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS public_access_token_unique_idx ON public_file_tokens (access_token) WHERE is_disabled = FALSE;
+CREATE INDEX IF NOT EXISTS public_file_tokens_owner_id_updated_at_idx ON public_file_tokens (owner_id, updated_at);
+
-
-
- ALTER TABLE public_abuse_report DROP CONSTRAINT IF EXISTS unique_report_sid_ip_ua;
- DROP INDEX IF EXISTS public_abuse_share_id_idx;
-
- ALTER TABLE public_abuse_report ADD COLUMN IF NOT EXISTS file_share_id text;
- ALTER TABLE public_abuse_report
- ADD CONSTRAINT fk_public_abuse_report_file_token_id
- FOREIGN KEY (file_share_id)
- REFERENCES public_file_tokens (id)
- ON DELETE CASCADE;
-
- ALTER TABLE public_abuse_report
- ADD CONSTRAINT check_share_id_xor_file_share_id
- CHECK (
- (share_id IS NULL AND file_share_id IS NOT NULL) OR
- (share_id IS NOT NULL AND file_share_id IS NULL)
- );
-
-
- CREATE UNIQUE INDEX unique_report_public_collection_id_ip_ua
- ON public_abuse_report (share_id, ip, user_agent)
- WHERE share_id IS NOT NULL;
-
- CREATE UNIQUE INDEX unique_report_public_file_id_ip_ua
- ON public_abuse_report (file_share_id, ip, user_agent)
- WHERE file_share_id IS NOT NULL;
diff --cc server/pkg/api/file.go
index 2e15ade325,2e15ade325..66147224a5
--- a/server/pkg/api/file.go
+++ b/server/pkg/api/file.go
@@@ -24,6 -24,6 +24,7 @@@ import
// FileHandler exposes request handlers for all encrypted file related requests
type FileHandler struct {
Controller *controller.FileController
++ FileUrlCtrl *controller.PublicFileController
FileCopyCtrl *file_copy.FileCopyController
FileDataCtrl *filedata.Controller
}
diff --cc server/pkg/api/file_url.go
index 7032478dfc,0000000000..2e9da338dc
mode 100644,000000..100644
--- a/server/pkg/api/file_url.go
+++ b/server/pkg/api/file_url.go
@@@ -1,28 -1,0 +1,25 @@@
+package api
+
+import (
+ "github.com/ente-io/museum/ente"
- "github.com/ente-io/museum/pkg/utils/auth"
+ "github.com/ente-io/museum/pkg/utils/handler"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+ "net/http"
+)
+
- // Update updates already existing file
++// ShareUrl a sharable url for the file
+func (h *FileHandler) ShareUrl(c *gin.Context) {
- enteApp := auth.GetApp(c)
- userID := auth.GetUserID(c.Request.Header)
+ var file ente.CreateFileUrl
+ if err := c.ShouldBindJSON(&file); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+
- response, err := h.Controller.Update(c, userID, file, enteApp)
++ response, err := h.FileUrlCtrl.CreateFileUrl(c, file)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, response)
+}
diff --cc server/pkg/controller/public_collection.go
index d2b2f39dcd,022a08812e..7f51a46330
--- a/server/pkg/controller/public_collection.go
+++ b/server/pkg/controller/public_collection.go
@@@ -4,8 -4,6 +4,7 @@@ import
"context"
"errors"
"fmt"
- "github.com/ente-io/museum/pkg/controller/access"
+ "github.com/ente-io/museum/pkg/repo/public"
"github.com/ente-io/museum/ente"
enteJWT "github.com/ente-io/museum/ente/jwt"
@@@ -55,8 -53,7 +54,7 @@@ const
type PublicCollectionController struct {
FileController *FileController
EmailNotificationCtrl *emailCtrl.EmailNotificationController
- PublicCollectionRepo *repo.PublicCollectionRepository
+ PublicCollectionRepo *public.PublicCollectionRepository
- PublicFileRepo *public.PublicFileRepository
CollectionRepo *repo.CollectionRepository
UserRepo *repo.UserRepository
JwtSecret []byte
diff --cc server/pkg/controller/public_file.go
index b48aee3384,0000000000..ee8148743b
mode 100644,000000..100644
--- a/server/pkg/controller/public_file.go
+++ b/server/pkg/controller/public_file.go
@@@ -1,236 -1,0 +1,36 @@@
+package controller
+
+import (
- "context"
- "errors"
- "fmt"
+ "github.com/ente-io/museum/ente"
- enteJWT "github.com/ente-io/museum/ente/jwt"
++ emailCtrl "github.com/ente-io/museum/pkg/controller/email"
++ "github.com/ente-io/museum/pkg/repo"
++ "github.com/ente-io/museum/pkg/repo/public"
+ "github.com/ente-io/museum/pkg/utils/auth"
- "github.com/ente-io/museum/pkg/utils/time"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
- "github.com/golang-jwt/jwt"
+ "github.com/lithammer/shortuuid/v3"
- "github.com/sirupsen/logrus"
+)
+
- func (c *PublicCollectionController) CreateAccessToken(ctx context.Context, req ente.CreatePublicAccessTokenRequest) (ente.PublicURL, error) {
- accessToken := shortuuid.New()[0:AccessTokenLength]
- err := c.PublicCollectionRepo.
- Insert(ctx, req.CollectionID, accessToken, req.ValidTill, req.DeviceLimit, req.EnableCollect, req.EnableJoin)
- if err != nil {
- if errors.Is(err, ente.ErrActiveLinkAlreadyExists) {
- collectionToPubUrlMap, err2 := c.PublicCollectionRepo.GetCollectionToActivePublicURLMap(ctx, []int64{req.CollectionID})
- if err2 != nil {
- return ente.PublicURL{}, stacktrace.Propagate(err2, "")
- }
- if publicUrls, ok := collectionToPubUrlMap[req.CollectionID]; ok {
- if len(publicUrls) > 0 {
- return publicUrls[0], nil
- }
- }
- // ideally we should never reach here
- return ente.PublicURL{}, stacktrace.NewError("Unexpected state")
- } else {
- return ente.PublicURL{}, stacktrace.Propagate(err, "")
- }
- }
- response := ente.PublicURL{
- URL: c.PublicCollectionRepo.GetAlbumUrl(accessToken),
- ValidTill: req.ValidTill,
- DeviceLimit: req.DeviceLimit,
- EnableDownload: true,
- EnableCollect: req.EnableCollect,
- PasswordEnabled: false,
- }
- return response, nil
- }
-
- func (c *PublicCollectionController) GetActivePublicCollectionToken(ctx context.Context, collectionID int64) (ente.PublicCollectionToken, error) {
- return c.PublicCollectionRepo.GetActivePublicCollectionToken(ctx, collectionID)
- }
-
- func (c *PublicCollectionController) CreateFile(ctx *gin.Context, file ente.File, app ente.App) (ente.File, error) {
- collection, err := c.GetPublicCollection(ctx, true)
- if err != nil {
- return ente.File{}, stacktrace.Propagate(err, "")
- }
- collectionOwnerID := collection.Owner.ID
- // Do not let any update happen via public Url
- file.ID = 0
- file.OwnerID = collectionOwnerID
- file.UpdationTime = time.Microseconds()
- file.IsDeleted = false
- createdFile, err := c.FileController.Create(ctx, collectionOwnerID, file, ctx.Request.UserAgent(), app)
- if err != nil {
- return ente.File{}, stacktrace.Propagate(err, "")
- }
-
- // Note: Stop sending email notification for public collection till
- // we add in-app setting to enable/disable email notifications
- //go c.EmailNotificationCtrl.OnFilesCollected(file.OwnerID)
- return createdFile, nil
- }
-
- // Disable all public accessTokens generated for the given cID till date.
- func (c *PublicCollectionController) Disable(ctx context.Context, cID int64) error {
- err := c.PublicCollectionRepo.DisableSharing(ctx, cID)
- return stacktrace.Propagate(err, "")
- }
-
- func (c *PublicCollectionController) UpdateSharedUrl(ctx context.Context, req ente.UpdatePublicAccessTokenRequest) (ente.PublicURL, error) {
- publicCollectionToken, err := c.PublicCollectionRepo.GetActivePublicCollectionToken(ctx, req.CollectionID)
- if err != nil {
- return ente.PublicURL{}, err
- }
- if req.ValidTill != nil {
- publicCollectionToken.ValidTill = *req.ValidTill
- }
- if req.DeviceLimit != nil {
- publicCollectionToken.DeviceLimit = *req.DeviceLimit
- }
- if req.PassHash != nil && req.Nonce != nil && req.OpsLimit != nil && req.MemLimit != nil {
- publicCollectionToken.PassHash = req.PassHash
- publicCollectionToken.Nonce = req.Nonce
- publicCollectionToken.OpsLimit = req.OpsLimit
- publicCollectionToken.MemLimit = req.MemLimit
- } else if req.DisablePassword != nil && *req.DisablePassword {
- publicCollectionToken.PassHash = nil
- publicCollectionToken.Nonce = nil
- publicCollectionToken.OpsLimit = nil
- publicCollectionToken.MemLimit = nil
- }
- if req.EnableDownload != nil {
- publicCollectionToken.EnableDownload = *req.EnableDownload
- }
- if req.EnableCollect != nil {
- publicCollectionToken.EnableCollect = *req.EnableCollect
- }
- if req.EnableJoin != nil {
- publicCollectionToken.EnableJoin = *req.EnableJoin
- }
- err = c.PublicCollectionRepo.UpdatePublicCollectionToken(ctx, publicCollectionToken)
- if err != nil {
- return ente.PublicURL{}, stacktrace.Propagate(err, "")
- }
- return ente.PublicURL{
- URL: c.PublicCollectionRepo.GetAlbumUrl(publicCollectionToken.Token),
- DeviceLimit: publicCollectionToken.DeviceLimit,
- ValidTill: publicCollectionToken.ValidTill,
- EnableDownload: publicCollectionToken.EnableDownload,
- EnableCollect: publicCollectionToken.EnableCollect,
- EnableJoin: publicCollectionToken.EnableJoin,
- PasswordEnabled: publicCollectionToken.PassHash != nil && *publicCollectionToken.PassHash != "",
- Nonce: publicCollectionToken.Nonce,
- MemLimit: publicCollectionToken.MemLimit,
- OpsLimit: publicCollectionToken.OpsLimit,
- }, nil
++// PublicFileController controls share collection operations
++type PublicFileController struct {
++ FileController *FileController
++ EmailNotificationCtrl *emailCtrl.EmailNotificationController
++ PublicCollectionRepo *public.PublicCollectionRepository
++ PublicFileRepo *public.PublicFileRepository
++ CollectionRepo *repo.CollectionRepository
++ UserRepo *repo.UserRepository
++ JwtSecret []byte
+}
+
- // VerifyPassword verifies if the user has provided correct pw hash. If yes, it returns a signed jwt token which can be
- // used by the client to pass in other requests for public collection.
- // Having a separate endpoint for password validation allows us to easily rate-limit the attempts for brute-force
- // attack for guessing password.
- func (c *PublicCollectionController) VerifyPassword(ctx *gin.Context, req ente.VerifyPasswordRequest) (*ente.VerifyPasswordResponse, error) {
- accessContext := auth.MustGetPublicAccessContext(ctx)
- publicCollectionToken, err := c.PublicCollectionRepo.GetActivePublicCollectionToken(ctx, accessContext.CollectionID)
- if err != nil {
- return nil, stacktrace.Propagate(err, "failed to get public collection info")
- }
- if publicCollectionToken.PassHash == nil || *publicCollectionToken.PassHash == "" {
- return nil, stacktrace.Propagate(ente.ErrBadRequest, "password is not configured for the link")
- }
- if req.PassHash != *publicCollectionToken.PassHash {
- return nil, stacktrace.Propagate(ente.ErrInvalidPassword, "incorrect password for link")
- }
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, &enteJWT.PublicAlbumPasswordClaim{
- PassHash: req.PassHash,
- ExpiryTime: time.NDaysFromNow(365),
- })
- // Sign and get the complete encoded token as a string using the secret
- tokenString, err := token.SignedString(c.JwtSecret)
-
- if err != nil {
- return nil, stacktrace.Propagate(err, "")
- }
- return &ente.VerifyPasswordResponse{
- JWTToken: tokenString,
- }, nil
- }
-
- func (c *PublicCollectionController) ValidateJWTToken(ctx *gin.Context, jwtToken string, passwordHash string) error {
- token, err := jwt.ParseWithClaims(jwtToken, &enteJWT.PublicAlbumPasswordClaim{}, func(token *jwt.Token) (interface{}, error) {
- if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
- return stacktrace.Propagate(fmt.Errorf("unexpected signing method: %v", token.Header["alg"]), ""), nil
- }
- return c.JwtSecret, nil
- })
- if err != nil {
- return stacktrace.Propagate(err, "JWT parsed failed")
- }
- claims, ok := token.Claims.(*enteJWT.PublicAlbumPasswordClaim)
-
- if !ok {
- return stacktrace.Propagate(errors.New("no claim in jwt token"), "")
- }
- if token.Valid && claims.PassHash == passwordHash {
- return nil
- }
- return ente.ErrInvalidPassword
- }
-
- func (c *PublicCollectionController) HandleAccountDeletion(ctx context.Context, userID int64, logger *logrus.Entry) error {
- logger.Info("updating public collection on account deletion")
- collectionIDs, err := c.PublicCollectionRepo.GetActivePublicTokenForUser(ctx, userID)
- if err != nil {
- return stacktrace.Propagate(err, "")
- }
- logger.WithField("cIDs", collectionIDs).Info("disable public tokens due to account deletion")
- for _, collectionID := range collectionIDs {
- err = c.Disable(ctx, collectionID)
- if err != nil {
- return stacktrace.Propagate(err, "")
- }
- }
- return nil
- }
-
- // GetPublicCollection will return collection info for a public url.
- // is mustAllowCollect is set to true but the underlying collection doesn't allow uploading
- func (c *PublicCollectionController) GetPublicCollection(ctx *gin.Context, mustAllowCollect bool) (ente.Collection, error) {
- accessContext := auth.MustGetPublicAccessContext(ctx)
- collection, err := c.CollectionRepo.Get(accessContext.CollectionID)
- if err != nil {
- return ente.Collection{}, stacktrace.Propagate(err, "")
- }
- if collection.IsDeleted {
- return ente.Collection{}, stacktrace.Propagate(ente.ErrNotFound, "collection is deleted")
- }
- // hide redundant/private information
- collection.Sharees = nil
- collection.MagicMetadata = nil
- publicURLsWithLimitedInfo := make([]ente.PublicURL, 0)
- for _, publicUrl := range collection.PublicURLs {
- publicURLsWithLimitedInfo = append(publicURLsWithLimitedInfo, ente.PublicURL{
- EnableDownload: publicUrl.EnableDownload,
- EnableCollect: publicUrl.EnableCollect,
- PasswordEnabled: publicUrl.PasswordEnabled,
- Nonce: publicUrl.Nonce,
- MemLimit: publicUrl.MemLimit,
- OpsLimit: publicUrl.OpsLimit,
- EnableJoin: publicUrl.EnableJoin,
- })
- }
- collection.PublicURLs = publicURLsWithLimitedInfo
- if mustAllowCollect {
- if len(publicURLsWithLimitedInfo) != 1 {
- errorMsg := fmt.Sprintf("Unexpected number of public urls: %d", len(publicURLsWithLimitedInfo))
- return ente.Collection{}, stacktrace.Propagate(ente.NewInternalError(errorMsg), "")
- }
- if !publicURLsWithLimitedInfo[0].EnableCollect {
- return ente.Collection{}, stacktrace.Propagate(&ente.ErrPublicCollectDisabled, "")
- }
- }
- return collection, nil
++func (c *PublicFileController) CreateFileUrl(ctx *gin.Context, req ente.CreateFileUrl) (*ente.FileUrl, error) {
++ actorUserID := auth.GetUserID(ctx.Request.Header)
++ accessToken := shortuuid.New()[0:AccessTokenLength]
++ err := c.PublicFileRepo.Insert(ctx, req.FileID, actorUserID, accessToken)
++ if err == nil {
++ return &ente.FileUrl{
++ LinkID: accessToken,
++ FileID: req.FileID,
++ }, nil
++ }
++ return nil, stacktrace.NewError("This endpoint is deprecated. Please use CreatePublicCollectionToken instead")
+}