Skip to content

armgit / ente

Public Imported from GitHub
0

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

Restrict Auth tokens from storage routes

Neeraj Gupta9c864d97484b
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index 8b9ff2b001..978efc1024 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -529,6 +529,8 @@ func main() {
privateAPI := server.Group("/")
privateAPI.Use(rateLimiter.GlobalRateLimiter(), authMiddleware.TokenAuthMiddleware(nil), rateLimiter.APIRateLimitForUserMiddleware(urlSanitizer))
+ storageAPI := privateAPI.Group("/")
+ storageAPI.Use(middleware.RejectAuthApp())
adminAPI := server.Group("/admin")
adminAPI.Use(rateLimiter.GlobalRateLimiter(), authMiddleware.TokenAuthMiddleware(nil), authMiddleware.AdminAuthMiddleware())
@@ -587,40 +589,40 @@ func main() {
FileUrlCtrl: fileLinkCtrl,
}
pasteHandler := &api.PasteHandler{Controller: pasteCtrl}
- privateAPI.GET("/files/upload-eligibility", fileHandler.ValidateUploadEligibility)
- privateAPI.GET("/files/upload-urls", fileHandler.GetUploadURLs)
- privateAPI.GET("/files/multipart-upload-urls", fileHandler.GetMultipartUploadURLs)
- privateAPI.POST("/files/upload-url", fileHandler.GetUploadURLV2)
- privateAPI.POST("/files/multipart-upload-url", fileHandler.GetMultipartUploadURLV2)
- privateAPI.GET("/files/download/:fileID", fileHandler.Get)
- privateAPI.GET("/files/preview/:fileID", fileHandler.GetThumbnail)
-
- privateAPI.POST("/files/share-url", fileHandler.ShareUrl)
- privateAPI.GET("/files/share-url", fileHandler.GetUrls)
- privateAPI.PUT("/files/share-url", fileHandler.UpdateFileURL)
- privateAPI.DELETE("/files/share-url/:fileID", fileHandler.DisableUrl)
- privateAPI.GET("/files/share-urls/", fileHandler.GetUrls)
-
- privateAPI.PUT("/files/data", fileHandler.PutFileData)
- privateAPI.PUT("/files/video-data", fileHandler.PutVideoData)
- privateAPI.POST("/files/data/status-diff", fileHandler.FileDataStatusDiff)
- privateAPI.POST("/files/data/fetch", fileHandler.GetFilesData)
- privateAPI.GET("/files/data/fetch", fileHandler.GetFileData)
- privateAPI.GET("/files/data/preview-upload-url", fileHandler.GetPreviewUploadURL)
- privateAPI.GET("/files/data/preview", fileHandler.GetPreviewURL)
-
- privateAPI.POST("/files", fileHandler.CreateOrUpdate)
- privateAPI.POST("/files/meta", fileHandler.CreateMetaFile)
- privateAPI.POST("/files/copy", fileHandler.CopyFiles)
- privateAPI.PUT("/files/update", fileHandler.Update)
- privateAPI.POST("/files/trash", fileHandler.Trash)
- privateAPI.POST("/files/size", fileHandler.GetSize)
- privateAPI.POST("/files/info", fileHandler.GetInfo)
- privateAPI.GET("/files/duplicates", fileHandler.GetDuplicates)
- privateAPI.GET("/files/large-thumbnails", fileHandler.GetLargeThumbnailFiles)
- privateAPI.PUT("/files/thumbnail", fileHandler.UpdateThumbnail)
- privateAPI.PUT("/files/magic-metadata", fileHandler.UpdateMagicMetadata)
- privateAPI.PUT("/files/public-magic-metadata", fileHandler.UpdatePublicMagicMetadata)
+ storageAPI.GET("/files/upload-eligibility", fileHandler.ValidateUploadEligibility)
+ storageAPI.GET("/files/upload-urls", fileHandler.GetUploadURLs)
+ storageAPI.GET("/files/multipart-upload-urls", fileHandler.GetMultipartUploadURLs)
+ storageAPI.POST("/files/upload-url", fileHandler.GetUploadURLV2)
+ storageAPI.POST("/files/multipart-upload-url", fileHandler.GetMultipartUploadURLV2)
+ storageAPI.GET("/files/download/:fileID", fileHandler.Get)
+ storageAPI.GET("/files/preview/:fileID", fileHandler.GetThumbnail)
+
+ storageAPI.POST("/files/share-url", fileHandler.ShareUrl)
+ storageAPI.GET("/files/share-url", fileHandler.GetUrls)
+ storageAPI.PUT("/files/share-url", fileHandler.UpdateFileURL)
+ storageAPI.DELETE("/files/share-url/:fileID", fileHandler.DisableUrl)
+ storageAPI.GET("/files/share-urls/", fileHandler.GetUrls)
+
+ storageAPI.PUT("/files/data", fileHandler.PutFileData)
+ storageAPI.PUT("/files/video-data", fileHandler.PutVideoData)
+ storageAPI.POST("/files/data/status-diff", fileHandler.FileDataStatusDiff)
+ storageAPI.POST("/files/data/fetch", fileHandler.GetFilesData)
+ storageAPI.GET("/files/data/fetch", fileHandler.GetFileData)
+ storageAPI.GET("/files/data/preview-upload-url", fileHandler.GetPreviewUploadURL)
+ storageAPI.GET("/files/data/preview", fileHandler.GetPreviewURL)
+
+ storageAPI.POST("/files", fileHandler.CreateOrUpdate)
+ storageAPI.POST("/files/meta", fileHandler.CreateMetaFile)
+ storageAPI.POST("/files/copy", fileHandler.CopyFiles)
+ storageAPI.PUT("/files/update", fileHandler.Update)
+ storageAPI.POST("/files/trash", fileHandler.Trash)
+ storageAPI.POST("/files/size", fileHandler.GetSize)
+ storageAPI.POST("/files/info", fileHandler.GetInfo)
+ storageAPI.GET("/files/duplicates", fileHandler.GetDuplicates)
+ storageAPI.GET("/files/large-thumbnails", fileHandler.GetLargeThumbnailFiles)
+ storageAPI.PUT("/files/thumbnail", fileHandler.UpdateThumbnail)
+ storageAPI.PUT("/files/magic-metadata", fileHandler.UpdateMagicMetadata)
+ storageAPI.PUT("/files/public-magic-metadata", fileHandler.UpdatePublicMagicMetadata)
publicAPI.GET("/files/count", fileHandler.GetTotalFileCount)
publicAPI.POST("/paste/create", pasteHandler.Create)
publicAPI.POST("/paste/guard", pasteHandler.Guard)
@@ -629,10 +631,10 @@ func main() {
trashHandler := &api.TrashHandler{
Controller: trashController,
}
- privateAPI.GET("/trash/diff", trashHandler.GetDiff)
- privateAPI.GET("/trash/v2/diff", trashHandler.GetDiffV2)
- privateAPI.POST("/trash/delete", trashHandler.Delete)
- privateAPI.POST("/trash/empty", trashHandler.Empty)
+ storageAPI.GET("/trash/diff", trashHandler.GetDiff)
+ storageAPI.GET("/trash/v2/diff", trashHandler.GetDiffV2)
+ storageAPI.POST("/trash/delete", trashHandler.Delete)
+ storageAPI.POST("/trash/empty", trashHandler.Empty)
commentsHandler := &api.CommentsHandler{Controller: commentsController}
reactionsHandler := &api.ReactionsHandler{Controller: reactionsController}
socialHandler := &api.SocialHandler{Controller: socialController}
@@ -641,19 +643,19 @@ func main() {
ReactionsCtrl: publicReactionsCtrl,
AnonIdentityCtrl: anonIdentityCtrl,
}
- privateAPI.GET("/comments/diff", commentsHandler.Diff)
- privateAPI.POST("/comments", commentsHandler.Create)
- privateAPI.PUT("/comments/:commentID", commentsHandler.Update)
- privateAPI.DELETE("/comments/:commentID", commentsHandler.Delete)
+ storageAPI.GET("/comments/diff", commentsHandler.Diff)
+ storageAPI.POST("/comments", commentsHandler.Create)
+ storageAPI.PUT("/comments/:commentID", commentsHandler.Update)
+ storageAPI.DELETE("/comments/:commentID", commentsHandler.Delete)
- privateAPI.GET("/reactions/diff", reactionsHandler.Diff)
- privateAPI.PUT("/reactions", reactionsHandler.Upsert)
- privateAPI.DELETE("/reactions/:reactionID", reactionsHandler.Delete)
+ storageAPI.GET("/reactions/diff", reactionsHandler.Diff)
+ storageAPI.PUT("/reactions", reactionsHandler.Upsert)
+ storageAPI.DELETE("/reactions/:reactionID", reactionsHandler.Delete)
- privateAPI.GET("/social/diff", socialHandler.UnifiedDiff)
- privateAPI.GET("/social/anon-profiles", socialHandler.AnonProfiles)
- privateAPI.GET("/comments-reactions/counts", socialHandler.Counts)
- privateAPI.GET("/comments-reactions/updated-at", socialHandler.LatestUpdates)
+ storageAPI.GET("/social/diff", socialHandler.UnifiedDiff)
+ storageAPI.GET("/social/anon-profiles", socialHandler.AnonProfiles)
+ storageAPI.GET("/comments-reactions/counts", socialHandler.Counts)
+ storageAPI.GET("/comments-reactions/updated-at", socialHandler.LatestUpdates)
emergencyCtrl := &emergency.Controller{
Repo: emergencyContactRepository,
@@ -697,7 +699,7 @@ func main() {
privateAPI.GET("/users/families-token", userHandler.GetFamiliesToken)
privateAPI.GET("/users/accounts-token", userHandler.GetAccountsToken)
privateAPI.GET("/users/details/v2", userHandler.GetDetailsV2)
- privateAPI.GET("/users/locker-usage", userHandler.GetLockerUsage)
+ storageAPI.GET("/users/locker-usage", userHandler.GetLockerUsage)
privateAPI.POST("/users/change-email", userHandler.ChangeEmail)
privateAPI.GET("/users/sessions", userHandler.GetActiveSessions)
privateAPI.DELETE("/users/session", userHandler.TerminateSession)
@@ -719,38 +721,38 @@ func main() {
collectionHandler := &api.CollectionHandler{
Controller: collectionController,
}
- privateAPI.POST("/collections", collectionHandler.Create)
+ storageAPI.POST("/collections", collectionHandler.Create)
// Collection actions (exposed for clients to fetch suggestions/removals)
- privateAPI.GET("/collection-actions/pending-remove", collectionActionsHandler.ListPendingRemove)
- privateAPI.GET("/collection-actions/delete-suggestions", collectionActionsHandler.ListDeleteSuggestions)
- privateAPI.POST("/collection-actions/reject-delete-suggestions", collectionActionsHandler.RejectDeleteSuggestions)
+ storageAPI.GET("/collection-actions/pending-remove", collectionActionsHandler.ListPendingRemove)
+ storageAPI.GET("/collection-actions/delete-suggestions", collectionActionsHandler.ListDeleteSuggestions)
+ storageAPI.POST("/collection-actions/reject-delete-suggestions", collectionActionsHandler.RejectDeleteSuggestions)
- privateAPI.GET("/collections/:collectionID", collectionHandler.GetCollectionByID)
+ storageAPI.GET("/collections/:collectionID", collectionHandler.GetCollectionByID)
//lint:ignore SA1019 Deprecated API will be removed in the future
- privateAPI.GET("/collections", collectionHandler.Get)
- privateAPI.GET("/collections/v2", collectionHandler.GetV2)
- privateAPI.GET("/collections/v3", collectionHandler.GetWithLimit)
- privateAPI.POST("/collections/share", collectionHandler.Share)
- privateAPI.POST("/collections/join-link", collectionHandler.JoinLink)
- privateAPI.POST("/collections/share-url", collectionHandler.ShareURL)
- privateAPI.PUT("/collections/share-url", collectionHandler.UpdateShareURL)
- privateAPI.DELETE("/collections/share-url/:collectionID", collectionHandler.UnShareURL)
- privateAPI.POST("/collections/unshare", collectionHandler.UnShare)
- privateAPI.POST("/collections/leave/:collectionID", collectionHandler.Leave)
- privateAPI.POST("/collections/add-files", collectionHandler.AddFiles)
- privateAPI.POST("/collections/move-files", collectionHandler.MoveFiles)
- privateAPI.POST("/collections/restore-files", collectionHandler.RestoreFiles)
-
- privateAPI.POST("/collections/v3/remove-files", collectionHandler.RemoveFilesV3)
- privateAPI.POST("/collections/suggest-delete", collectionHandler.SuggestDeleteInSharedCollection)
- privateAPI.GET("/collections/v2/diff", collectionHandler.GetDiffV2)
- privateAPI.GET("/collections/file", collectionHandler.GetFile)
- privateAPI.GET("/collections/sharees", collectionHandler.GetSharees)
- privateAPI.DELETE("/collections/v3/:collectionID", collectionHandler.TrashV3)
- privateAPI.POST("/collections/rename", collectionHandler.Rename)
- privateAPI.PUT("/collections/magic-metadata", collectionHandler.PrivateMagicMetadataUpdate)
- privateAPI.PUT("/collections/public-magic-metadata", collectionHandler.PublicMagicMetadataUpdate)
- privateAPI.PUT("/collections/sharee-magic-metadata", collectionHandler.ShareeMagicMetadataUpdate)
+ storageAPI.GET("/collections", collectionHandler.Get)
+ storageAPI.GET("/collections/v2", collectionHandler.GetV2)
+ storageAPI.GET("/collections/v3", collectionHandler.GetWithLimit)
+ storageAPI.POST("/collections/share", collectionHandler.Share)
+ 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/leave/:collectionID", collectionHandler.Leave)
+ storageAPI.POST("/collections/add-files", collectionHandler.AddFiles)
+ storageAPI.POST("/collections/move-files", collectionHandler.MoveFiles)
+ storageAPI.POST("/collections/restore-files", collectionHandler.RestoreFiles)
+
+ storageAPI.POST("/collections/v3/remove-files", collectionHandler.RemoveFilesV3)
+ storageAPI.POST("/collections/suggest-delete", collectionHandler.SuggestDeleteInSharedCollection)
+ storageAPI.GET("/collections/v2/diff", collectionHandler.GetDiffV2)
+ storageAPI.GET("/collections/file", collectionHandler.GetFile)
+ storageAPI.GET("/collections/sharees", collectionHandler.GetSharees)
+ storageAPI.DELETE("/collections/v3/:collectionID", collectionHandler.TrashV3)
+ storageAPI.POST("/collections/rename", collectionHandler.Rename)
+ storageAPI.PUT("/collections/magic-metadata", collectionHandler.PrivateMagicMetadataUpdate)
+ storageAPI.PUT("/collections/public-magic-metadata", collectionHandler.PublicMagicMetadataUpdate)
+ storageAPI.PUT("/collections/sharee-magic-metadata", collectionHandler.ShareeMagicMetadataUpdate)
publicCollectionHandler := &api.PublicCollectionHandler{
Controller: collectionLinkCtrl,
@@ -797,10 +799,10 @@ func main() {
FileDataCtrl: fileDataCtrl,
}
- privateAPI.POST("/memory-share", memoryShareHandler.Create)
- privateAPI.GET("/memory-share", memoryShareHandler.List)
- privateAPI.GET("/memory-share/:shareID", memoryShareHandler.GetByID)
- privateAPI.DELETE("/memory-share/:shareID", memoryShareHandler.Delete)
+ storageAPI.POST("/memory-share", memoryShareHandler.Create)
+ storageAPI.GET("/memory-share", memoryShareHandler.List)
+ storageAPI.GET("/memory-share/:shareID", memoryShareHandler.GetByID)
+ storageAPI.DELETE("/memory-share/:shareID", memoryShareHandler.Delete)
publicMemoryAPI.GET("/info", publicMemoryShareHandler.GetInfo)
publicMemoryAPI.GET("/files", publicMemoryShareHandler.GetFiles)
@@ -822,8 +824,8 @@ func main() {
}
publicAPI.POST("/cast/device-info", castHandler.RegisterDevice)
- privateAPI.GET("/cast/device-info", castHandler.GetAllDevices)
- privateAPI.DELETE("/cast/device-info/:deviceID", castHandler.DeleteDevice)
+ storageAPI.GET("/cast/device-info", castHandler.GetAllDevices)
+ storageAPI.DELETE("/cast/device-info/:deviceID", castHandler.DeleteDevice)
// Deprecated Nov 2024. Remove in a few months.
//
// This (and below) are deprecated copy of endpoints with a trailing slash.
@@ -831,14 +833,14 @@ func main() {
// redirect because of CORS headers missing on the 307. Can be safely
// removed in a few months after the desktop apps have updated.
publicAPI.POST("/cast/device-info/", castHandler.RegisterDevice)
- privateAPI.GET("/cast/device-info/:deviceCode", castHandler.GetDeviceInfo)
+ storageAPI.GET("/cast/device-info/:deviceCode", castHandler.GetDeviceInfo)
publicAPI.GET("/cast/cast-data/:deviceCode", castHandler.GetCastData)
- privateAPI.POST("/cast/cast-data", castHandler.InsertCastData)
+ storageAPI.POST("/cast/cast-data", castHandler.InsertCastData)
// Deprecated Nov 2024. Remove in a few months.
- privateAPI.POST("/cast/cast-data/", castHandler.InsertCastData)
- privateAPI.DELETE("/cast/revoke-all-tokens", castHandler.RevokeAllToken)
+ storageAPI.POST("/cast/cast-data/", castHandler.InsertCastData)
+ storageAPI.DELETE("/cast/revoke-all-tokens", castHandler.RevokeAllToken)
// Deprecated Nov 2024. Remove in a few months.
- privateAPI.DELETE("/cast/revoke-all-tokens/", castHandler.RevokeAllToken)
+ storageAPI.DELETE("/cast/revoke-all-tokens/", castHandler.RevokeAllToken)
castAPI.GET("/files/preview/:fileID", castHandler.GetThumbnail)
castAPI.GET("/files/download/:fileID", castHandler.GetFile)
diff --git a/server/pkg/controller/user/userauth_storage_warning_test.go b/server/pkg/controller/user/userauth_storage_warning_test.go
index b7be7f92e3..cccc8c47a7 100644
--- a/server/pkg/controller/user/userauth_storage_warning_test.go
+++ b/server/pkg/controller/user/userauth_storage_warning_test.go
@@ -66,6 +66,33 @@ func TestEnsureStorageWarningDeletionLoginAllowedHonorsActiveLoginGrace(t *testi
}
}
+func TestEnsureStorageWarningDeletionLoginAllowedDoesNotBlockAuthApp(t *testing.T) {
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ const userID int64 = 12347
+ testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: userID,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{
+ UserID: userID,
+ TemplateID: repo.StorageWarningExpiredScheduledDeletionTemplateID,
+ SentTime: 100,
+ })
+
+ err := (&UserController{
+ NotificationHistoryRepo: &repo.NotificationHistoryRepository{DB: db},
+ }).ensureStorageWarningDeletionLoginAllowed(userID, ente.Auth)
+ if err != nil {
+ t.Fatalf("expected auth app login to remain allowed, got %v", err)
+ }
+}
+
func TestEnsureStorageWarningDeletionLoginAllowedBlocksAfterLoginGraceExpires(t *testing.T) {
db := testutil.RequireTestDB(t)
testutil.ResetTables(t, db)
diff --git a/server/pkg/middleware/auth.go b/server/pkg/middleware/auth.go
index ef814e2f85..c743a9c532 100644
--- a/server/pkg/middleware/auth.go
+++ b/server/pkg/middleware/auth.go
@@ -4,12 +4,13 @@ import (
"database/sql"
"errors"
"fmt"
- "github.com/sirupsen/logrus"
"net/http"
"strconv"
+ "github.com/ente/museum/ente"
"github.com/ente/museum/ente/jwt"
"github.com/ente/museum/pkg/utils/network"
+ "github.com/sirupsen/logrus"
"github.com/ente/museum/pkg/controller/user"
"github.com/ente/museum/pkg/repo"
@@ -85,6 +86,22 @@ func (m *AuthMiddleware) TokenAuthMiddleware(jwtClaimScope *jwt.ClaimScope) gin.
m.Cache.Set(cacheKey, userID, cache.DefaultExpiration)
}
c.Request.Header.Set("X-Auth-User-ID", strconv.FormatInt(userID.(int64), 10))
+ c.Set(auth.AppContextKey, app)
+ c.Next()
+ }
+}
+
+func RejectAuthApp() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ app, ok := auth.GetAuthenticatedApp(c)
+ if !ok {
+ c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing authenticated app"})
+ return
+ }
+ if app == ente.Auth {
+ c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "invalid app for endpoint"})
+ return
+ }
c.Next()
}
}
diff --git a/server/pkg/middleware/auth_test.go b/server/pkg/middleware/auth_test.go
new file mode 100644
index 0000000000..205c39ab93
--- /dev/null
+++ b/server/pkg/middleware/auth_test.go
@@ -0,0 +1,155 @@
+package middleware
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/ente/museum/ente"
+ "github.com/ente/museum/internal/testutil"
+ "github.com/ente/museum/pkg/repo"
+ "github.com/gin-gonic/gin"
+ "github.com/patrickmn/go-cache"
+)
+
+type authRouteTestTokens struct {
+ auth string
+ photos string
+ locker string
+}
+
+func TestRejectAuthAppKeepsAuthRoutesAndBlocksStorageRoutes(t *testing.T) {
+ router, tokens := setupAuthRouteTest(t)
+
+ tests := []struct {
+ name string
+ path string
+ token string
+ clientPkg string
+ wantStatus int
+ }{
+ {
+ name: "auth token can access auth route",
+ path: "/authenticator/entity/diff?sinceTime=0&limit=1",
+ token: tokens.auth,
+ clientPkg: "io.ente.auth",
+ wantStatus: http.StatusNoContent,
+ },
+ {
+ name: "auth token cannot access storage route",
+ path: "/collections/v2",
+ token: tokens.auth,
+ clientPkg: "io.ente.auth",
+ wantStatus: http.StatusForbidden,
+ },
+ {
+ name: "photos token can access storage route",
+ path: "/collections/v2",
+ token: tokens.photos,
+ clientPkg: "io.ente.photos",
+ wantStatus: http.StatusNoContent,
+ },
+ {
+ name: "locker token can access storage route",
+ path: "/collections/v2",
+ token: tokens.locker,
+ clientPkg: "io.ente.locker",
+ wantStatus: http.StatusNoContent,
+ },
+ {
+ name: "auth token with photos header remains invalid",
+ path: "/collections/v2",
+ token: tokens.auth,
+ clientPkg: "io.ente.photos",
+ wantStatus: http.StatusUnauthorized,
+ },
+ {
+ name: "auth token still blocked when header changes after token auth",
+ path: "/files/download/123",
+ token: tokens.auth,
+ clientPkg: "io.ente.auth",
+ wantStatus: http.StatusForbidden,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ recorder := performAuthRouteRequest(router, tt.path, tt.token, tt.clientPkg)
+ if recorder.Code != tt.wantStatus {
+ t.Fatalf("status = %d, want %d; body=%s", recorder.Code, tt.wantStatus, recorder.Body.String())
+ }
+ })
+ }
+}
+
+func setupAuthRouteTest(t *testing.T) (*gin.Engine, authRouteTestTokens) {
+ t.Helper()
+
+ testutil.WithServerRoot(t)
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ userID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 91001,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ userAuthRepo := &repo.UserAuthRepository{DB: db}
+ tokens := authRouteTestTokens{
+ auth: "auth-route-test-auth-token",
+ photos: "auth-route-test-photos-token",
+ locker: "auth-route-test-locker-token",
+ }
+ addTokenForTest(t, userAuthRepo, userID, ente.Auth, tokens.auth)
+ addTokenForTest(t, userAuthRepo, userID, ente.Photos, tokens.photos)
+ addTokenForTest(t, userAuthRepo, userID, ente.Locker, tokens.locker)
+
+ gin.SetMode(gin.TestMode)
+ router := gin.New()
+ authMiddleware := &AuthMiddleware{
+ UserAuthRepo: userAuthRepo,
+ Cache: cache.New(time.Minute, time.Minute),
+ }
+ privateAPI := router.Group("/")
+ privateAPI.Use(authMiddleware.TokenAuthMiddleware(nil))
+ privateAPI.GET("/authenticator/entity/diff", func(c *gin.Context) {
+ c.Status(http.StatusNoContent)
+ })
+
+ storageAPI := privateAPI.Group("/")
+ storageAPI.Use(RejectAuthApp())
+ storageAPI.GET("/collections/v2", func(c *gin.Context) {
+ c.Status(http.StatusNoContent)
+ })
+
+ headerMutatingStorageAPI := privateAPI.Group("/")
+ headerMutatingStorageAPI.Use(func(c *gin.Context) {
+ c.Request.Header.Set("X-Client-Package", "io.ente.photos")
+ c.Next()
+ }, RejectAuthApp())
+ headerMutatingStorageAPI.GET("/files/download/:fileID", func(c *gin.Context) {
+ c.Status(http.StatusNoContent)
+ })
+
+ return router, tokens
+}
+
+func addTokenForTest(t *testing.T, userAuthRepo *repo.UserAuthRepository, userID int64, app ente.App, token string) {
+ t.Helper()
+ if err := userAuthRepo.AddToken(userID, app, token, "127.0.0.1", "auth-route-test"); err != nil {
+ t.Fatalf("failed to add %s token: %v", app, err)
+ }
+}
+
+func performAuthRouteRequest(router *gin.Engine, path string, token string, clientPkg string) *httptest.ResponseRecorder {
+ recorder := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, path, nil)
+ req.Header.Set("X-Auth-Token", token)
+ req.Header.Set("X-Client-Package", clientPkg)
+ router.ServeHTTP(recorder, req)
+ return recorder
+}
diff --git a/server/pkg/utils/auth/auth.go b/server/pkg/utils/auth/auth.go
index b6685fd7be..16be3fdc7b 100644
--- a/server/pkg/utils/auth/auth.go
+++ b/server/pkg/utils/auth/auth.go
@@ -23,6 +23,7 @@ const (
FileLinkAccessKey = "X-Public-FileLink-Access-ID"
CastContext = "X-Cast-Context"
MemoryShareAccessKey = "X-Memory-Share-Access-ID"
+ AppContextKey = "auth.app"
LinkDeviceTokenHeader = "X-Auth-Link-Device-Token"
LinkDeviceTokenResponseHeader = "X-Ente-Link-Device-Token"
@@ -92,6 +93,15 @@ func GetApp(c *gin.Context) ente.App {
return ente.Photos
}
+func GetAuthenticatedApp(c *gin.Context) (ente.App, bool) {
+ app, ok := c.Get(AppContextKey)
+ if !ok {
+ return "", false
+ }
+ enteApp, ok := app.(ente.App)
+ return enteApp, ok
+}
+
func GetToken(c *gin.Context) string {
token := c.GetHeader("X-Auth-Token")
if token == "" {