Skip to content

armgit / ente

Public Imported from GitHub
0

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

Limit authenticated user lookups

Neeraj Guptafd746680f763
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index 3af9e716cd..7d55bb09d7 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -219,6 +219,7 @@ func main() {
authCache := cache.New(1*time.Minute, 15*time.Minute)
accessTokenCache := cache.New(1*time.Minute, 15*time.Minute)
discordController := discord.NewDiscordController(userRepo, hostName, environment)
+ userLookupController := controller.NewUserLookupController(userRepo, discordController)
rateLimiter := middleware.NewRateLimitMiddleware(discordController, 1000, 1*time.Second)
defer rateLimiter.Stop()
@@ -354,6 +355,7 @@ func main() {
familyController := &family.Controller{
FamilyRepo: familyRepo,
BillingCtrl: billingController,
+ UserLookup: userLookupController,
UserRepo: userRepo,
UserCacheCtrl: userCacheCtrl,
UsageRepo: usageRepo,
@@ -400,6 +402,7 @@ func main() {
TrashRepo: trashRepo,
CastRepo: &castDb,
BillingCtrl: billingController,
+ UserLookup: userLookupController,
QueueRepo: queueRepo,
TaskRepo: taskLockingRepo,
CollectionActionsRepo: collectionActionRepo,
@@ -437,6 +440,7 @@ func main() {
billingController,
familyController,
discordController,
+ userLookupController,
mailingListsController,
pushController,
userCache,
@@ -664,6 +668,7 @@ func main() {
emergencyCtrl := &emergency.Controller{
Repo: emergencyContactRepository,
UserRepo: userRepo,
+ UserLookup: userLookupController,
UserCtrl: userController,
PasskeyController: passkeyCtrl,
LockCtrl: lockController,
diff --git a/server/pkg/api/family_test.go b/server/pkg/api/family_test.go
index 8cbde26029..697e38aa21 100644
--- a/server/pkg/api/family_test.go
+++ b/server/pkg/api/family_test.go
@@ -84,6 +84,7 @@ func setupFullFamilyTest(t *testing.T) (http.Handler, int64, string, string) {
handler := &FamilyHandler{Controller: &familycontroller.Controller{
BillingCtrl: billingController,
+ UserLookup: museumcontroller.NewUserLookupController(userRepo, nil),
UserRepo: userRepo,
FamilyRepo: familyRepo,
}}
diff --git a/server/pkg/api/user.go b/server/pkg/api/user.go
index 1acedd5a21..14b0355654 100644
--- a/server/pkg/api/user.go
+++ b/server/pkg/api/user.go
@@ -149,8 +149,7 @@ func (h *UserHandler) SetRecoveryKey(c *gin.Context) {
// GetPublicKey returns the public key of a user
func (h *UserHandler) GetPublicKey(c *gin.Context) {
- email := emailUtil.NormalizeEmail(c.Query("email"))
- publicKey, err := h.UserController.GetPublicKey(email)
+ publicKey, err := h.UserController.GetPublicKey(auth.GetUserID(c.Request.Header), c.Query("email"))
if err != nil {
handler.Error(c, stacktrace.Propagate(err, ""))
return
diff --git a/server/pkg/controller/collections/collection.go b/server/pkg/controller/collections/collection.go
index 96ac84ae41..74eaac5f36 100644
--- a/server/pkg/controller/collections/collection.go
+++ b/server/pkg/controller/collections/collection.go
@@ -31,6 +31,7 @@ type CollectionController struct {
EmailCtrl *email.EmailNotificationController
AccessCtrl access.Controller
BillingCtrl *controller.BillingController
+ UserLookup controller.UserLookup
CollectionRepo *repo.CollectionRepository
UserRepo *repo.UserRepository
FileRepo *repo.FileRepository
diff --git a/server/pkg/controller/collections/share.go b/server/pkg/controller/collections/share.go
index af2738dae9..e30283d0f7 100644
--- a/server/pkg/controller/collections/share.go
+++ b/server/pkg/controller/collections/share.go
@@ -25,27 +25,16 @@ func (c *CollectionController) Share(ctx *gin.Context, req ente.AlterShareReques
if err := validateSealedCollectionKey(encryptedKey); err != nil {
return nil, err
}
- toUserEmail := emailUtil.NormalizeEmail(req.Email)
// default role type
role := ente.VIEWER
if req.Role != nil {
role = *req.Role
}
- toUserID, err := c.UserRepo.GetUserIDWithEmail(toUserEmail)
- if err != nil {
- return nil, stacktrace.Propagate(err, "")
- }
- if toUserID == fromUserID {
- return nil, stacktrace.Propagate(ente.ErrBadRequest, "Can not share collection with self")
- }
collection, err := c.CollectionRepo.Get(cID)
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
- if !collection.AllowSharing() {
- return nil, stacktrace.Propagate(ente.ErrBadRequest, "sharing %s is not allowed", collection.Type)
- }
shareActorID := collection.Owner.ID
if fromUserID != collection.Owner.ID {
shareeRole, err := c.CollectionRepo.GetCollectionShareeRole(cID, fromUserID)
@@ -59,6 +48,20 @@ func (c *CollectionController) Share(ctx *gin.Context, req ente.AlterShareReques
return nil, stacktrace.Propagate(ente.ErrPermissionDenied, "")
}
}
+ if !collection.AllowSharing() {
+ return nil, stacktrace.Propagate(ente.ErrBadRequest, "sharing %s is not allowed", collection.Type)
+ }
+
+ toUserID, err := c.UserLookup.LookupUserID(fromUserID, req.Email)
+ if 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")
+ }
err = c.CollectionRepo.Share(cID, shareActorID, toUserID, encryptedKey, role, time.Microseconds())
if err != nil {
return nil, stacktrace.Propagate(err, "")
@@ -123,17 +126,10 @@ func (c *CollectionController) JoinViaLink(ctx *gin.Context, req ente.JoinCollec
// UnShare unshares a collection with a user
func (c *CollectionController) UnShare(ctx *gin.Context, cID int64, fromUserID int64, toUserEmail string) ([]ente.CollectionUser, error) {
- toUserID, err := c.UserRepo.GetUserIDWithEmail(toUserEmail)
- if err != nil {
- return nil, stacktrace.Propagate(ente.ErrNotFound, "")
- }
collection, err := c.CollectionRepo.Get(cID)
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
- if toUserID == fromUserID {
- return nil, stacktrace.Propagate(ente.ErrPermissionDenied, "")
- }
if fromUserID != collection.Owner.ID {
shareeRole, err := c.CollectionRepo.GetCollectionShareeRole(cID, fromUserID)
if err != nil {
@@ -146,9 +142,20 @@ func (c *CollectionController) UnShare(ctx *gin.Context, cID int64, fromUserID i
return nil, stacktrace.Propagate(ente.ErrPermissionDenied, "")
}
}
- if toUserID == collection.Owner.ID {
+
+ sharees, err := c.CollectionRepo.GetSharees(cID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ toUserIndex := shareeIndexForEmail(sharees, toUserEmail)
+ if toUserIndex == -1 {
+ return nil, stacktrace.Propagate(ente.ErrNotFound, "")
+ }
+ toUserID := sharees[toUserIndex].ID
+ if toUserID == fromUserID || toUserID == collection.Owner.ID {
return nil, stacktrace.Propagate(ente.ErrPermissionDenied, "")
}
+
err = c.CollectionRepo.UnShare(cID, toUserID)
if err != nil {
return nil, stacktrace.Propagate(err, "")
@@ -160,11 +167,14 @@ func (c *CollectionController) UnShare(ctx *gin.Context, cID int64, fromUserID i
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
- sharees, err := c.GetSharees(ctx, cID, fromUserID)
- if err != nil {
- return nil, stacktrace.Propagate(err, "")
- }
- return sharees, nil
+ return slices.Delete(sharees, toUserIndex, toUserIndex+1), nil
+}
+
+func shareeIndexForEmail(sharees []ente.CollectionUser, targetEmail string) int {
+ targetEmail = emailUtil.NormalizeEmail(targetEmail)
+ return slices.IndexFunc(sharees, func(sharee ente.CollectionUser) bool {
+ return emailUtil.NormalizeEmail(sharee.Email) == targetEmail
+ })
}
// Leave leaves the collection owned by someone else,
diff --git a/server/pkg/controller/collections/share_test.go b/server/pkg/controller/collections/share_test.go
new file mode 100644
index 0000000000..fd42dee889
--- /dev/null
+++ b/server/pkg/controller/collections/share_test.go
@@ -0,0 +1,252 @@
+package collections
+
+import (
+ "database/sql"
+ "errors"
+ "net/http/httptest"
+ "strconv"
+ "testing"
+
+ "github.com/ente/museum/ente"
+ "github.com/ente/museum/internal/testutil"
+ "github.com/ente/museum/pkg/repo"
+ castRepo "github.com/ente/museum/pkg/repo/cast"
+ publicRepo "github.com/ente/museum/pkg/repo/public"
+ "github.com/gin-gonic/gin"
+)
+
+type panicUserLookup struct{}
+
+func (panicUserLookup) LookupUserID(int64, string) (int64, error) {
+ panic("user lookup must not be called while revoking collection access")
+}
+
+type fixedUserLookup struct {
+ userID int64
+}
+
+func (l fixedUserLookup) LookupUserID(int64, string) (int64, error) {
+ return l.userID, nil
+}
+
+func newShareTestCollectionRepo(db *sql.DB) *repo.CollectionRepository {
+ return &repo.CollectionRepository{
+ DB: db,
+ CollectionLinkRepo: publicRepo.NewCollectionLinkRepository(db, ""),
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ }
+}
+
+func createShareTestCollection(t *testing.T, collectionRepo *repo.CollectionRepository, ownerID int64) 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",
+ Attributes: ente.CollectionAttributes{},
+ UpdationTime: 1,
+ App: string(ente.Photos),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return collection.ID
+}
+
+func addShareTestShare(
+ t *testing.T,
+ collectionRepo *repo.CollectionRepository,
+ collectionID, ownerID, shareeID int64,
+ role ente.CollectionParticipantRole,
+) {
+ t.Helper()
+ if err := collectionRepo.Share(collectionID, ownerID, shareeID, "share-key", role, 1); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func addShareTestOwnerFile(t *testing.T, db *sql.DB, collectionID, ownerID int64) int64 {
+ t.Helper()
+ var fileID int64
+ err := db.QueryRow(
+ `WITH inserted_file AS (
+ INSERT INTO files(owner_id, file_decryption_header, thumbnail_decryption_header, metadata_decryption_header, encrypted_metadata, updation_time, info)
+ VALUES($1, 'file-header', 'thumbnail-header', 'metadata-header', 'encrypted-metadata', 1, '{}'::jsonb)
+ RETURNING file_id
+ )
+ INSERT INTO collection_files(collection_id, file_id, encrypted_key, key_decryption_nonce, updation_time, c_owner_id, f_owner_id)
+ SELECT $2, file_id, 'collection-file-key', 'collection-file-nonce', 1, $1, $1 FROM inserted_file
+ RETURNING file_id`,
+ ownerID,
+ collectionID,
+ ).Scan(&fileID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return fileID
+}
+
+func TestShareeIndexForEmail(t *testing.T) {
+ sharees := []ente.CollectionUser{
+ {ID: 1, Email: "[email protected]"},
+ {ID: 2, Email: "[email protected]"},
+ }
+
+ if got := shareeIndexForEmail(sharees, " [email protected] "); got != 1 {
+ t.Fatalf("sharee index = %d, want 1", got)
+ }
+ if got := shareeIndexForEmail(sharees, "[email protected]"); got != -1 {
+ t.Fatalf("missing sharee index = %d, want -1", got)
+ }
+}
+
+func TestUnShareResolvesTargetFromCurrentSharees(t *testing.T) {
+ 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,
+ })
+
+ collectionRepo := newShareTestCollectionRepo(db)
+ collectionID := createShareTestCollection(t, collectionRepo, ownerID)
+ addShareTestShare(t, collectionRepo, collectionID, ownerID, shareeID, ente.VIEWER)
+ controller := &CollectionController{
+ CollectionRepo: collectionRepo,
+ CastRepo: &castRepo.Repository{DB: db},
+ UserLookup: panicUserLookup{},
+ }
+ gin.SetMode(gin.TestMode)
+ ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
+
+ sharees, err := controller.UnShare(ctx, collectionID, ownerID, " [email protected] ")
+ if err != nil {
+ t.Fatalf("unshare returned error: %v", err)
+ }
+ if len(sharees) != 0 {
+ t.Fatalf("sharees after unshare = %+v, want none", sharees)
+ }
+
+ var isDeleted bool
+ err = db.QueryRow(
+ `SELECT is_deleted FROM collection_shares WHERE collection_id = $1 AND to_user_id = $2`,
+ collectionID,
+ shareeID,
+ ).Scan(&isDeleted)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !isDeleted {
+ t.Fatal("collection share remains active after unshare")
+ }
+
+ _, err = controller.UnShare(ctx, collectionID, ownerID, "[email protected]")
+ if !errors.Is(err, ente.ErrNotFound) {
+ t.Fatalf("missing sharee error = %v, want %v", err, ente.ErrNotFound)
+ }
+}
+
+func TestShareAuthorizesBeforeUserLookup(t *testing.T) {
+ 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,
+ })
+ collectionRepo := newShareTestCollectionRepo(db)
+ controller := &CollectionController{
+ CollectionRepo: collectionRepo,
+ UserLookup: panicUserLookup{},
+ }
+ ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
+ ctx.Request = httptest.NewRequest("POST", "/collections/share", nil)
+ ctx.Request.Header.Set("X-Auth-User-ID", "2")
+
+ _, err := controller.Share(ctx, ente.AlterShareRequest{
+ CollectionID: createShareTestCollection(t, collectionRepo, ownerID),
+ Email: "[email protected]",
+ EncryptedKey: b64OfLen(sealedCollectionKeyLen),
+ })
+ if !errors.Is(err, ente.ErrPermissionDenied) {
+ t.Fatalf("share error = %v, want %v", err, ente.ErrPermissionDenied)
+ }
+}
+
+func TestCollectionOwnerCannotBecomeShareeOrBeUnshared(t *testing.T) {
+ 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,
+ })
+ adminID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 2,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+
+ collectionRepo := newShareTestCollectionRepo(db)
+ collectionID := createShareTestCollection(t, collectionRepo, ownerID)
+ addShareTestShare(t, collectionRepo, collectionID, ownerID, adminID, ente.ADMIN)
+ controller := &CollectionController{
+ CollectionRepo: collectionRepo,
+ UserLookup: fixedUserLookup{userID: ownerID},
+ }
+ gin.SetMode(gin.TestMode)
+ ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
+ ctx.Request = httptest.NewRequest("POST", "/collections/share", nil)
+ ctx.Request.Header.Set("X-Auth-User-ID", strconv.FormatInt(adminID, 10))
+
+ _, err := controller.Share(ctx, ente.AlterShareRequest{
+ CollectionID: collectionID,
+ Email: "[email protected]",
+ EncryptedKey: b64OfLen(sealedCollectionKeyLen),
+ })
+ if !errors.Is(err, ente.ErrBadRequest) {
+ t.Fatalf("sharing to owner error = %v, want %v", err, ente.ErrBadRequest)
+ }
+
+ addShareTestShare(t, collectionRepo, collectionID, ownerID, ownerID, ente.VIEWER)
+ fileID := addShareTestOwnerFile(t, db, collectionID, ownerID)
+
+ _, err = controller.UnShare(ctx, collectionID, adminID, "[email protected]")
+ if !errors.Is(err, ente.ErrPermissionDenied) {
+ t.Fatalf("unsharing owner error = %v, want %v", err, ente.ErrPermissionDenied)
+ }
+
+ var ownerShareDeleted, ownerFileDeleted bool
+ err = db.QueryRow(
+ `SELECT cs.is_deleted, cf.is_deleted
+ FROM collection_shares cs
+ JOIN collection_files cf ON cf.collection_id = cs.collection_id
+ WHERE cs.collection_id = $1 AND cs.to_user_id = $2 AND cf.file_id = $3`,
+ collectionID,
+ ownerID,
+ fileID,
+ ).Scan(&ownerShareDeleted, &ownerFileDeleted)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ownerShareDeleted || ownerFileDeleted {
+ t.Fatalf("owner state changed: share deleted=%t, file deleted=%t", ownerShareDeleted, ownerFileDeleted)
+ }
+}
diff --git a/server/pkg/controller/discountcoupon/controller.go b/server/pkg/controller/discountcoupon/controller.go
index 664f129227..2576e58d68 100644
--- a/server/pkg/controller/discountcoupon/controller.go
+++ b/server/pkg/controller/discountcoupon/controller.go
@@ -62,7 +62,7 @@ func (c *Controller) processClaimRequest(ctx *gin.Context, req ClaimCouponReques
WithField("email", sanitizedEmail).
WithField("req_id", requestid.Get(ctx))
- userID, err := c.UserRepo.GetUserIDWithEmail(sanitizedEmail)
+ userID, err := c.UserRepo.GetUserIDWithEmailUnrestricted(sanitizedEmail)
if err != nil {
logger.WithError(err).Info("User not found for discount coupon claim")
return
diff --git a/server/pkg/controller/emergency/account_owner.go b/server/pkg/controller/emergency/account_owner.go
index 6260c4ec72..c5c889fcc2 100644
--- a/server/pkg/controller/emergency/account_owner.go
+++ b/server/pkg/controller/emergency/account_owner.go
@@ -10,7 +10,7 @@ import (
)
func (c *Controller) AddContact(ctx *gin.Context, userID int64, request ente.AddContact) error {
- emergencyContactID, err := c.UserRepo.GetUserIDWithEmail(request.Email)
+ emergencyContactID, err := c.UserLookup.LookupUserID(userID, request.Email)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return stacktrace.Propagate(ente.ErrNotFound, "invited member is not on ente")
diff --git a/server/pkg/controller/emergency/controller.go b/server/pkg/controller/emergency/controller.go
index f11852adc1..484a9b0c7c 100644
--- a/server/pkg/controller/emergency/controller.go
+++ b/server/pkg/controller/emergency/controller.go
@@ -17,6 +17,7 @@ import (
type Controller struct {
Repo *emergency.Repository
UserRepo *repo.UserRepository
+ UserLookup controller.UserLookup
UserCtrl *user.UserController
PasskeyController *controller.PasskeyController
LockCtrl *lock.LockController
diff --git a/server/pkg/controller/family/admin.go b/server/pkg/controller/family/admin.go
index 312c377d82..ba80cf0536 100644
--- a/server/pkg/controller/family/admin.go
+++ b/server/pkg/controller/family/admin.go
@@ -78,7 +78,7 @@ func (c *Controller) InviteMember(ctx *gin.Context, adminUserID int64, email str
return stacktrace.Propagate(err, "")
}
- potentialMemberID, err := c.UserRepo.GetUserIDWithEmail(email)
+ potentialMemberID, err := c.UserLookup.LookupUserID(adminUserID, email)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return stacktrace.Propagate(ente.ErrNotFound, "invited member is not on ente")
diff --git a/server/pkg/controller/family/family.go b/server/pkg/controller/family/family.go
index 22c913c9cd..62ad9428be 100644
--- a/server/pkg/controller/family/family.go
+++ b/server/pkg/controller/family/family.go
@@ -25,6 +25,7 @@ const (
// Controller exposes functions to interact with family module
type Controller struct {
BillingCtrl *controller.BillingController
+ UserLookup controller.UserLookup
UserRepo *repo.UserRepository
FamilyRepo *repo.FamilyRepository
UserCacheCtrl *usercache.Controller
diff --git a/server/pkg/controller/offer/offer.go b/server/pkg/controller/offer/offer.go
index 9511a0de25..ca3f5bb8e8 100644
--- a/server/pkg/controller/offer/offer.go
+++ b/server/pkg/controller/offer/offer.go
@@ -99,7 +99,7 @@ func (c *OfferController) ApplyOffer(email string, productID string) error {
return stacktrace.Propagate(ente.ErrNotFound, "Could not find a valid time period for %s", productID)
}
- userID, err := c.UserRepo.GetUserIDWithEmail(email)
+ userID, err := c.UserRepo.GetUserIDWithEmailUnrestricted(email)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
log.Error("Product purchased with unknown email: " + email)
diff --git a/server/pkg/controller/user/srp.go b/server/pkg/controller/user/srp.go
index 274ce67187..5893b5161e 100644
--- a/server/pkg/controller/user/srp.go
+++ b/server/pkg/controller/user/srp.go
@@ -101,7 +101,7 @@ func (c *UserController) UpdateSrpAndKeyAttributes(context *gin.Context,
}
func (c *UserController) GetSRPAttributes(context *gin.Context, email string) (*ente.GetSRPAttributesResponse, error) {
- userID, err := c.UserRepo.GetUserIDWithEmail(email)
+ userID, err := c.UserRepo.GetUserIDWithEmailUnrestricted(email)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) {
return nil, stacktrace.Propagate(err, "failed to get user id")
diff --git a/server/pkg/controller/user/user.go b/server/pkg/controller/user/user.go
index a327808044..310348f731 100644
--- a/server/pkg/controller/user/user.go
+++ b/server/pkg/controller/user/user.go
@@ -41,6 +41,7 @@ type UserController struct {
TwoFactorRecoveryRepo *two_factor_recovery.Repository
UsageRepo *repo.UsageRepository
UserAuthRepo *repo.UserAuthRepository
+ UserLookup controller.UserLookup
TwoFactorRepo *repo.TwoFactorRepository
PasskeyRepo *passkey.Repository
StorageBonusRepo *storageBonusRepo.Repository
@@ -131,6 +132,7 @@ func NewUserController(
billingController *controller.BillingController,
familyController *family.Controller,
discordController *discord.DiscordController,
+ userLookup controller.UserLookup,
mailingListsController *controller.MailingListsController,
pushController *controller.PushController,
userCache *cache2.UserCache,
@@ -145,6 +147,7 @@ func NewUserController(
UsageRepo: usageRepo,
TwoFactorRecoveryRepo: twoFactorRecoveryRepo,
UserAuthRepo: userAuthRepo,
+ UserLookup: userLookup,
StorageBonusRepo: storageBonusRepo,
TwoFactorRepo: twoFactorRepo,
AuthenticatorRepo: authenticatorRepo,
@@ -230,8 +233,8 @@ func (c *UserController) SetRecoveryKey(userID int64, request ente.SetRecoveryKe
}
// GetPublicKey returns the public key of a user
-func (c *UserController) GetPublicKey(email string) (string, error) {
- userID, err := c.UserRepo.GetUserIDWithEmail(email)
+func (c *UserController) GetPublicKey(requesterUserID int64, email string) (string, error) {
+ userID, err := c.UserLookup.LookupUserID(requesterUserID, email)
if err != nil {
return "", stacktrace.Propagate(err, "")
}
diff --git a/server/pkg/controller/user/userauth.go b/server/pkg/controller/user/userauth.go
index f47dd7f9b2..e7fac87cf8 100644
--- a/server/pkg/controller/user/userauth.go
+++ b/server/pkg/controller/user/userauth.go
@@ -162,7 +162,7 @@ func (c *UserController) SendEmailOTT(context *gin.Context, email string, purpos
}
func (c *UserController) isEmailAlreadyUsed(email string) error {
- _, err := c.UserRepo.GetUserIDWithEmail(email)
+ _, err := c.UserRepo.GetUserIDWithEmailUnrestricted(email)
if err == nil {
// email already owned by a user
return stacktrace.Propagate(ente.ErrPermissionDenied, "email already belongs to a user")
@@ -234,7 +234,7 @@ func (c *UserController) shouldSwallowSendOTTDisclosureError(ctx *gin.Context) b
// getSignUpState returns the signup state for an email.
// Signup is complete only when both email and key attributes exist.
func (c *UserController) getSignUpState(email string) (signUpState, error) {
- userID, err := c.UserRepo.GetUserIDWithEmail(email)
+ userID, err := c.UserRepo.GetUserIDWithEmailUnrestricted(email)
if err != nil && errors.Is(err, sql.ErrNoRows) {
return signUpStateNoAccount, nil
}
@@ -340,7 +340,7 @@ func (c *UserController) ChangeEmail(ctx *gin.Context, request ente.EmailVerific
func (c *UserController) UpdateEmail(ctx *gin.Context, userID int64, email string) error {
email = emailUtil.NormalizeEmail(email)
- _, err := c.UserRepo.GetUserIDWithEmail(email)
+ _, err := c.UserRepo.GetUserIDWithEmailUnrestricted(email)
if err == nil {
// email already owned by a user
return stacktrace.Propagate(ente.ErrPermissionDenied, "")
@@ -643,7 +643,7 @@ func (c *UserController) onVerificationSuccess(context *gin.Context, email strin
isTwoFactorEnabled := false
app := auth.GetApp(context)
- userID, err := c.UserRepo.GetUserIDWithEmail(email)
+ userID, err := c.UserRepo.GetUserIDWithEmailUnrestricted(email)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
if viper.GetBool("internal.disable-registration") {
diff --git a/server/pkg/controller/user_lookup.go b/server/pkg/controller/user_lookup.go
new file mode 100644
index 0000000000..42ea8ba5de
--- /dev/null
+++ b/server/pkg/controller/user_lookup.go
@@ -0,0 +1,75 @@
+package controller
+
+import (
+ "database/sql"
+ "errors"
+
+ "github.com/ente/museum/ente"
+ "github.com/ente/museum/pkg/repo"
+ "github.com/ente/museum/pkg/utils/crypto"
+ emailUtil "github.com/ente/museum/pkg/utils/email"
+ "github.com/ente/stacktrace"
+)
+
+type userLookupRepository interface {
+ GetUserIDWithEmailUnrestricted(email string) (int64, error)
+}
+
+type potentialAbuseNotifier interface {
+ NotifyPotentialAbuse(message string)
+}
+
+// UserLookup applies the shared authenticated email-discovery policy.
+type UserLookup interface {
+ LookupUserID(requesterUserID int64, email string) (int64, error)
+}
+
+// UserLookupController limits email discovery before querying the user repository.
+type UserLookupController struct {
+ userRepo userLookupRepository
+ notifier potentialAbuseNotifier
+ hashingKey []byte
+ lookupLimit *userLookupLimiter
+}
+
+func NewUserLookupController(userRepo *repo.UserRepository, notifier potentialAbuseNotifier) *UserLookupController {
+ return &UserLookupController{
+ userRepo: userRepo,
+ notifier: notifier,
+ hashingKey: userRepo.HashingKey,
+ lookupLimit: newUserLookupLimiter(defaultUserLookupLimits()),
+ }
+}
+
+func (c *UserLookupController) LookupUserID(requesterUserID int64, email string) (int64, error) {
+ if requesterUserID <= 0 {
+ return -1, stacktrace.Propagate(ente.ErrAuthenticationRequired, "")
+ }
+
+ normalizedEmail := emailUtil.NormalizeEmail(email)
+ targetHash, err := crypto.GetHash(normalizedEmail, c.hashingKey)
+ if err != nil {
+ return -1, stacktrace.Propagate(err, "")
+ }
+
+ attempt, decision := c.lookupLimit.Start(requesterUserID, targetHash)
+ if !decision.allowed {
+ return -1, c.limitExceeded(decision)
+ }
+
+ userID, err := c.userRepo.GetUserIDWithEmailUnrestricted(normalizedEmail)
+ decision = c.lookupLimit.Finish(attempt, errors.Is(err, sql.ErrNoRows))
+ if !decision.allowed {
+ return -1, c.limitExceeded(decision)
+ }
+ return userID, err
+}
+
+func (c *UserLookupController) limitExceeded(decision userLookupLimitDecision) error {
+ if decision.notify && c.notifier != nil {
+ go c.notifier.NotifyPotentialAbuse(
+ "user lookup limit exceeded (" + string(decision.window) + " window)",
+ )
+ }
+ return stacktrace.Propagate(ente.ErrTooManyBadRequest, "too many user lookups")
+}
diff --git a/server/pkg/controller/user_lookup_limiter.go b/server/pkg/controller/user_lookup_limiter.go
new file mode 100644
index 0000000000..87701003bf
--- /dev/null
+++ b/server/pkg/controller/user_lookup_limiter.go
@@ -0,0 +1,226 @@
+package controller
+
+import (
+ "sync"
+ "time"
+)
+
+const (
+ defaultUserLookupMinuteLimit = 50
+ defaultUserLookupDayLimit = 50
+ defaultUserLookupNotFoundMinuteLimit = 5
+ defaultUserLookupNotFoundDayLimit = 10
+
+ userLookupMinuteWindowDuration = time.Minute
+ userLookupDayWindowDuration = 24 * time.Hour
+ userLookupNotificationInterval = time.Minute
+ userLookupPruneInterval = time.Hour
+)
+
+type userLookupWindowLimits struct {
+ total int
+ notFound int
+}
+
+type userLookupLimits struct {
+ minute userLookupWindowLimits
+ day userLookupWindowLimits
+}
+
+func defaultUserLookupLimits() userLookupLimits {
+ return userLookupLimits{
+ minute: userLookupWindowLimits{
+ total: defaultUserLookupMinuteLimit,
+ notFound: defaultUserLookupNotFoundMinuteLimit,
+ },
+ day: userLookupWindowLimits{
+ total: defaultUserLookupDayLimit,
+ notFound: defaultUserLookupNotFoundDayLimit,
+ },
+ }
+}
+
+type userLookupLimitWindow string
+
+const (
+ userLookupMinuteWindow userLookupLimitWindow = "minute"
+ userLookupDayWindow userLookupLimitWindow = "day"
+ userLookupNotFoundMinuteWindow userLookupLimitWindow = "not-found minute"
+ userLookupNotFoundDayWindow userLookupLimitWindow = "not-found day"
+)
+
+type userLookupLimitDecision struct {
+ allowed bool
+ notify bool
+ window userLookupLimitWindow
+}
+
+type userLookupWindow struct {
+ startedAt time.Time
+ targets map[string]struct{}
+ notFound map[string]struct{}
+ pending map[string]struct{}
+}
+
+type userLookupActorState struct {
+ lastSeen time.Time
+ minute userLookupWindow
+ day userLookupWindow
+}
+
+type userLookupAttempt struct {
+ requesterUserID int64
+ targetHash string
+ minuteStartedAt time.Time
+ dayStartedAt time.Time
+}
+
+type userLookupLimiter struct {
+ mu sync.Mutex
+
+ now func() time.Time
+ limits userLookupLimits
+ lastPruned time.Time
+ actors map[int64]*userLookupActorState
+ lastNotify map[userLookupLimitWindow]time.Time
+}
+
+func newUserLookupLimiter(limits userLookupLimits) *userLookupLimiter {
+ return newUserLookupLimiterWithClock(limits, time.Now)
+}
+
+func newUserLookupLimiterWithClock(limits userLookupLimits, now func() time.Time) *userLookupLimiter {
+ currentTime := now()
+ return &userLookupLimiter{
+ now: now,
+ limits: limits,
+ lastPruned: currentTime,
+ actors: make(map[int64]*userLookupActorState),
+ lastNotify: make(map[userLookupLimitWindow]time.Time),
+ }
+}
+
+func (l *userLookupLimiter) Start(requesterUserID int64, targetHash string) (userLookupAttempt, userLookupLimitDecision) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ now := l.now()
+ l.prune(now)
+
+ state, ok := l.actors[requesterUserID]
+ if !ok {
+ state = &userLookupActorState{}
+ l.actors[requesterUserID] = state
+ }
+ state.lastSeen = now
+ state.minute.resetIfExpired(now, userLookupMinuteWindowDuration)
+ state.day.resetIfExpired(now, userLookupDayWindowDuration)
+
+ minuteNew := !state.minute.contains(targetHash)
+ dayNew := !state.day.contains(targetHash)
+ if minuteNew && len(state.minute.targets) >= l.limits.minute.total {
+ return userLookupAttempt{}, l.denied(now, userLookupMinuteWindow)
+ }
+ if dayNew && len(state.day.targets) >= l.limits.day.total {
+ return userLookupAttempt{}, l.denied(now, userLookupDayWindow)
+ }
+ if minuteNew && len(state.minute.notFound)+len(state.minute.pending) >= l.limits.minute.notFound {
+ return userLookupAttempt{}, l.denied(now, userLookupNotFoundMinuteWindow)
+ }
+ if dayNew && len(state.day.notFound)+len(state.day.pending) >= l.limits.day.notFound {
+ return userLookupAttempt{}, l.denied(now, userLookupNotFoundDayWindow)
+ }
+
+ state.minute.targets[targetHash] = struct{}{}
+ state.day.targets[targetHash] = struct{}{}
+ if minuteNew {
+ state.minute.pending[targetHash] = struct{}{}
+ }
+ if dayNew {
+ state.day.pending[targetHash] = struct{}{}
+ }
+ attempt := userLookupAttempt{
+ requesterUserID: requesterUserID,
+ targetHash: targetHash,
+ minuteStartedAt: state.minute.startedAt,
+ dayStartedAt: state.day.startedAt,
+ }
+ return attempt, userLookupLimitDecision{allowed: true}
+}
+
+func (l *userLookupLimiter) Finish(attempt userLookupAttempt, notFound bool) userLookupLimitDecision {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ state, ok := l.actors[attempt.requesterUserID]
+ if !ok {
+ return userLookupLimitDecision{allowed: true}
+ }
+ minuteActive := state.minute.startedAt.Equal(attempt.minuteStartedAt)
+ dayActive := state.day.startedAt.Equal(attempt.dayStartedAt)
+ if minuteActive {
+ delete(state.minute.pending, attempt.targetHash)
+ }
+ if dayActive {
+ delete(state.day.pending, attempt.targetHash)
+ }
+ if !notFound {
+ return userLookupLimitDecision{allowed: true}
+ }
+ if minuteActive && !state.minute.isNotFound(attempt.targetHash) && len(state.minute.notFound) >= l.limits.minute.notFound {
+ return l.denied(l.now(), userLookupNotFoundMinuteWindow)
+ }
+ if dayActive && !state.day.isNotFound(attempt.targetHash) && len(state.day.notFound) >= l.limits.day.notFound {
+ return l.denied(l.now(), userLookupNotFoundDayWindow)
+ }
+ if minuteActive {
+ state.minute.notFound[attempt.targetHash] = struct{}{}
+ }
+ if dayActive {
+ state.day.notFound[attempt.targetHash] = struct{}{}
+ }
+ return userLookupLimitDecision{allowed: true}
+}
+
+func (l *userLookupLimiter) denied(now time.Time, window userLookupLimitWindow) userLookupLimitDecision {
+ decision := userLookupLimitDecision{window: window}
+ lastNotify := l.lastNotify[window]
+ if lastNotify.IsZero() || now.Sub(lastNotify) >= userLookupNotificationInterval {
+ l.lastNotify[window] = now
+ decision.notify = true
+ }
+ return decision
+}
+
+func (l *userLookupLimiter) prune(now time.Time) {
+ if now.Sub(l.lastPruned) < userLookupPruneInterval {
+ return
+ }
+ cutoff := now.Add(-userLookupDayWindowDuration)
+ for requesterUserID, state := range l.actors {
+ if !state.lastSeen.After(cutoff) {
+ delete(l.actors, requesterUserID)
+ }
+ }
+ l.lastPruned = now
+}
+
+func (w *userLookupWindow) resetIfExpired(now time.Time, duration time.Duration) {
+ if w.targets != nil && now.Sub(w.startedAt) < duration {
+ return
+ }
+ w.startedAt = now
+ w.targets = make(map[string]struct{})
+ w.notFound = make(map[string]struct{})
+ w.pending = make(map[string]struct{})
+}
+
+func (w *userLookupWindow) contains(targetHash string) bool {
+ _, ok := w.targets[targetHash]
+ return ok
+}
+
+func (w *userLookupWindow) isNotFound(targetHash string) bool {
+ _, ok := w.notFound[targetHash]
+ return ok
+}
diff --git a/server/pkg/controller/user_lookup_limiter_test.go b/server/pkg/controller/user_lookup_limiter_test.go
new file mode 100644
index 0000000000..fdd4a583e0
--- /dev/null
+++ b/server/pkg/controller/user_lookup_limiter_test.go
@@ -0,0 +1,267 @@
+package controller
+
+import (
+ "fmt"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func userLookupDecision(
+ limiter *userLookupLimiter,
+ requesterUserID int64,
+ targetHash string,
+ notFound bool,
+) userLookupLimitDecision {
+ attempt, decision := limiter.Start(requesterUserID, targetHash)
+ if decision.allowed {
+ decision = limiter.Finish(attempt, notFound)
+ }
+ return decision
+}
+
+func newMinuteLookupLimiter(now func() time.Time) *userLookupLimiter {
+ limits := defaultUserLookupLimits()
+ limits.day.total = limits.minute.total + 1
+ return newUserLookupLimiterWithClock(limits, now)
+}
+
+func TestUserLookupLimiterCountsUniqueTargetsPerMinute(t *testing.T) {
+ now := time.Unix(1000, 0)
+ limiter := newMinuteLookupLimiter(func() time.Time { return now })
+
+ for i := 0; i < defaultUserLookupMinuteLimit; i++ {
+ if decision := userLookupDecision(limiter, 1, fmt.Sprintf("target-%d", i), false); !decision.allowed {
+ t.Fatalf("target %d decision = %+v, want allowed", i, decision)
+ }
+ }
+ if decision := userLookupDecision(limiter, 1, "target-0", false); !decision.allowed {
+ t.Fatalf("repeated target decision = %+v, want allowed", decision)
+ }
+ if decision := userLookupDecision(limiter, 1, "new-target", false); decision.allowed || decision.window != userLookupMinuteWindow {
+ t.Fatalf("extra target decision = %+v, want minute-window denial", decision)
+ } else if !decision.notify {
+ t.Fatalf("first minute-window denial decision = %+v, want notification", decision)
+ }
+ if decision := userLookupDecision(limiter, 1, "another-target", false); decision.allowed || decision.notify {
+ t.Fatalf("repeated minute-window denial decision = %+v, want silent denial", decision)
+ }
+ if decision := userLookupDecision(limiter, 2, "new-target", false); !decision.allowed {
+ t.Fatalf("independent requester decision = %+v, want allowed", decision)
+ }
+}
+
+func TestUserLookupLimiterCountsUniqueTargetsPerDay(t *testing.T) {
+ now := time.Unix(1000, 0)
+ limiter := newUserLookupLimiterWithClock(defaultUserLookupLimits(), func() time.Time { return now })
+
+ for i := 0; i < defaultUserLookupDayLimit; i++ {
+ if i > 0 && i%defaultUserLookupMinuteLimit == 0 {
+ now = now.Add(userLookupMinuteWindowDuration)
+ }
+ if decision := userLookupDecision(limiter, 1, fmt.Sprintf("target-%d", i), false); !decision.allowed {
+ t.Fatalf("target %d decision = %+v, want allowed", i, decision)
+ }
+ }
+
+ now = now.Add(userLookupMinuteWindowDuration)
+ if decision := userLookupDecision(limiter, 1, "target-0", false); !decision.allowed {
+ t.Fatalf("existing daily target decision = %+v, want allowed", decision)
+ }
+ if decision := userLookupDecision(limiter, 1, "new-target", false); decision.allowed || decision.window != userLookupDayWindow {
+ t.Fatalf("extra target decision = %+v, want day-window denial", decision)
+ } else if !decision.notify {
+ t.Fatalf("first day-window denial decision = %+v, want notification", decision)
+ }
+ if decision := userLookupDecision(limiter, 1, "another-target", false); decision.allowed || decision.notify {
+ t.Fatalf("repeated day-window denial decision = %+v, want silent denial", decision)
+ }
+
+ now = time.Unix(1000, 0).Add(userLookupDayWindowDuration)
+ if decision := userLookupDecision(limiter, 1, "new-target", false); !decision.allowed {
+ t.Fatalf("target after daily reset decision = %+v, want allowed", decision)
+ }
+}
+
+func TestUserLookupLimiterStopsNewTargetsAfterNotFoundLimit(t *testing.T) {
+ now := time.Unix(1000, 0)
+ limiter := newUserLookupLimiterWithClock(defaultUserLookupLimits(), func() time.Time { return now })
+
+ for i := 0; i < defaultUserLookupNotFoundMinuteLimit; i++ {
+ if decision := userLookupDecision(limiter, 1, fmt.Sprintf("missing-%d", i), true); !decision.allowed {
+ t.Fatalf("missing target %d decision = %+v, want allowed", i, decision)
+ }
+ }
+ if decision := userLookupDecision(limiter, 1, "missing-0", true); !decision.allowed {
+ t.Fatalf("repeated missing target decision = %+v, want allowed", decision)
+ }
+ if decision := userLookupDecision(limiter, 1, "existing-user", false); decision.allowed || decision.window != userLookupNotFoundMinuteWindow {
+ t.Fatalf("new target decision = %+v, want not-found minute-window denial", decision)
+ }
+}
+
+func TestUserLookupLimiterCountsNotFoundTargetsPerDay(t *testing.T) {
+ now := time.Unix(1000, 0)
+ limiter := newUserLookupLimiterWithClock(defaultUserLookupLimits(), func() time.Time { return now })
+
+ for i := 0; i < defaultUserLookupNotFoundDayLimit; i++ {
+ if i > 0 && i%defaultUserLookupNotFoundMinuteLimit == 0 {
+ now = now.Add(userLookupMinuteWindowDuration)
+ }
+ if decision := userLookupDecision(limiter, 1, fmt.Sprintf("missing-%d", i), true); !decision.allowed {
+ t.Fatalf("missing target %d decision = %+v, want allowed", i, decision)
+ }
+ }
+
+ now = now.Add(userLookupMinuteWindowDuration)
+ if decision := userLookupDecision(limiter, 1, "new-target", false); decision.allowed || decision.window != userLookupNotFoundDayWindow {
+ t.Fatalf("new target decision = %+v, want not-found day-window denial", decision)
+ }
+}
+
+func TestUserLookupLimiterEnforcesConcurrentRequestsAtomically(t *testing.T) {
+ now := time.Unix(1000, 0)
+ limits := defaultUserLookupLimits()
+ limits.minute.notFound = limits.minute.total
+ limits.day.total = limits.minute.total + 1
+ limits.day.notFound = limits.day.total
+ limiter := newUserLookupLimiterWithClock(limits, func() time.Time { return now })
+
+ var allowed atomic.Int64
+ var notifications atomic.Int64
+ var wg sync.WaitGroup
+ for i := 0; i < defaultUserLookupMinuteLimit*2; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ decision := userLookupDecision(limiter, 1, fmt.Sprintf("target-%d", i), false)
+ if decision.allowed {
+ allowed.Add(1)
+ }
+ if decision.notify {
+ notifications.Add(1)
+ }
+ }(i)
+ }
+ wg.Wait()
+
+ if got := allowed.Load(); got != defaultUserLookupMinuteLimit {
+ t.Fatalf("allowed concurrent requests = %d, want %d", got, defaultUserLookupMinuteLimit)
+ }
+ if got := notifications.Load(); got != 1 {
+ t.Fatalf("concurrent notifications = %d, want 1", got)
+ }
+}
+
+func TestUserLookupLimiterReservesNotFoundCapacityForConcurrentRequests(t *testing.T) {
+ now := time.Unix(1000, 0)
+ limiter := newMinuteLookupLimiter(func() time.Time { return now })
+
+ var allowed atomic.Int64
+ var admitted atomic.Int64
+ var notifications atomic.Int64
+ var started sync.WaitGroup
+ var finished sync.WaitGroup
+ release := make(chan struct{})
+ for i := 0; i < defaultUserLookupMinuteLimit; i++ {
+ started.Add(1)
+ finished.Add(1)
+ go func(i int) {
+ defer finished.Done()
+ attempt, decision := limiter.Start(1, fmt.Sprintf("target-%d", i))
+ started.Done()
+ if decision.notify {
+ notifications.Add(1)
+ }
+ if !decision.allowed {
+ return
+ }
+ admitted.Add(1)
+ <-release
+ decision = limiter.Finish(attempt, true)
+ if decision.allowed {
+ allowed.Add(1)
+ }
+ }(i)
+ }
+ started.Wait()
+ if got := admitted.Load(); got != defaultUserLookupNotFoundMinuteLimit {
+ t.Fatalf("admitted concurrent lookups = %d, want %d", got, defaultUserLookupNotFoundMinuteLimit)
+ }
+ close(release)
+ finished.Wait()
+
+ if got := allowed.Load(); got != defaultUserLookupNotFoundMinuteLimit {
+ t.Fatalf("allowed concurrent requests = %d, want %d", got, defaultUserLookupNotFoundMinuteLimit)
+ }
+ if got := notifications.Load(); got != 1 {
+ t.Fatalf("concurrent notifications = %d, want 1", got)
+ }
+}
+
+func TestUserLookupLimiterCoalescesNotificationsAcrossRequesters(t *testing.T) {
+ now := time.Unix(1000, 0)
+ limiter := newMinuteLookupLimiter(func() time.Time { return now })
+
+ for requesterUserID := int64(1); requesterUserID <= 2; requesterUserID++ {
+ for i := 0; i < defaultUserLookupMinuteLimit; i++ {
+ userLookupDecision(limiter, requesterUserID, fmt.Sprintf("target-%d", i), false)
+ }
+ decision := userLookupDecision(limiter, requesterUserID, "blocked-target", false)
+ if requesterUserID == 1 && !decision.notify {
+ t.Fatalf("first requester decision = %+v, want notification", decision)
+ }
+ if requesterUserID == 2 && decision.notify {
+ t.Fatalf("second requester decision = %+v, want coalesced notification", decision)
+ }
+ }
+}
+
+func TestUserLookupLimiterRenotifiesDayDenialsAfterNotificationInterval(t *testing.T) {
+ now := time.Unix(1000, 0)
+ limiter := newUserLookupLimiterWithClock(defaultUserLookupLimits(), func() time.Time { return now })
+
+ for i := 0; i < defaultUserLookupDayLimit; i++ {
+ if i > 0 && i%defaultUserLookupMinuteLimit == 0 {
+ now = now.Add(userLookupMinuteWindowDuration)
+ }
+ for requesterUserID := int64(1); requesterUserID <= 2; requesterUserID++ {
+ if decision := userLookupDecision(limiter, requesterUserID, fmt.Sprintf("target-%d", i), false); !decision.allowed {
+ t.Fatalf("requester %d target %d decision = %+v, want allowed", requesterUserID, i, decision)
+ }
+ }
+ }
+
+ now = now.Add(userLookupMinuteWindowDuration)
+ first := userLookupDecision(limiter, 1, "blocked-target", false)
+ if first.allowed || first.window != userLookupDayWindow || !first.notify {
+ t.Fatalf("first day-window denial = %+v, want notifying denial", first)
+ }
+ second := userLookupDecision(limiter, 2, "blocked-target", false)
+ if second.allowed || second.window != userLookupDayWindow || second.notify {
+ t.Fatalf("coalesced day-window denial = %+v, want silent denial", second)
+ }
+
+ now = now.Add(userLookupNotificationInterval)
+ third := userLookupDecision(limiter, 2, "another-blocked-target", false)
+ if third.allowed || third.window != userLookupDayWindow || !third.notify {
+ t.Fatalf("later day-window denial = %+v, want notifying denial", third)
+ }
+}
+
+func TestUserLookupLimiterPrunesInactiveRequesters(t *testing.T) {
+ now := time.Unix(1000, 0)
+ limiter := newUserLookupLimiterWithClock(defaultUserLookupLimits(), func() time.Time { return now })
+ userLookupDecision(limiter, 1, "target", false)
+
+ now = now.Add(userLookupDayWindowDuration)
+ userLookupDecision(limiter, 2, "target", false)
+
+ if _, ok := limiter.actors[1]; ok {
+ t.Fatal("inactive requester was not pruned")
+ }
+ if _, ok := limiter.actors[2]; !ok {
+ t.Fatal("active requester was pruned")
+ }
+}
diff --git a/server/pkg/controller/user_lookup_test.go b/server/pkg/controller/user_lookup_test.go
new file mode 100644
index 0000000000..b6124dd377
--- /dev/null
+++ b/server/pkg/controller/user_lookup_test.go
@@ -0,0 +1,168 @@
+package controller
+
+import (
+ "bytes"
+ "database/sql"
+ "errors"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/ente/museum/ente"
+)
+
+type userLookupRepositoryStub struct {
+ mu sync.Mutex
+ emails []string
+ userID int64
+ err error
+}
+
+func (r *userLookupRepositoryStub) GetUserIDWithEmailUnrestricted(email string) (int64, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.emails = append(r.emails, email)
+ return r.userID, r.err
+}
+
+func (r *userLookupRepositoryStub) callCount() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return len(r.emails)
+}
+
+func (r *userLookupRepositoryStub) setResult(userID int64, err error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.userID = userID
+ r.err = err
+}
+
+type userLookupNotifierStub struct {
+ messages chan string
+}
+
+func (n *userLookupNotifierStub) NotifyPotentialAbuse(message string) {
+ n.messages <- message
+}
+
+func newUserLookupControllerForTest(
+ repository userLookupRepository,
+ notifier potentialAbuseNotifier,
+ now func() time.Time,
+) *UserLookupController {
+ return &UserLookupController{
+ userRepo: repository,
+ notifier: notifier,
+ hashingKey: bytes.Repeat([]byte{1}, 32),
+ lookupLimit: newUserLookupLimiterWithClock(defaultUserLookupLimits(), now),
+ }
+}
+
+func TestUserLookupNormalizesAndAlwaysQueriesRepository(t *testing.T) {
+ now := time.Unix(1000, 0)
+ repository := &userLookupRepositoryStub{userID: 42}
+ controller := newUserLookupControllerForTest(repository, nil, func() time.Time { return now })
+
+ for i := 0; i < 100; i++ {
+ userID, err := controller.LookupUserID(1, " [email protected] ")
+ if err != nil {
+ t.Fatalf("lookup %d returned error: %v", i, err)
+ }
+ if userID != 42 {
+ t.Fatalf("lookup %d user ID = %d, want 42", i, userID)
+ }
+ }
+
+ if got := repository.callCount(); got != 100 {
+ t.Fatalf("repository calls = %d, want 100", got)
+ }
+ for _, email := range repository.emails {
+ if email != "[email protected]" {
+ t.Fatalf("repository email = %q, want normalized email", email)
+ }
+ }
+
+ for targetHash := range controller.lookupLimit.actors[1].day.targets {
+ if targetHash == "[email protected]" {
+ t.Fatal("limiter stored a plaintext email")
+ }
+ }
+}
+
+func TestUserLookupRejectsUnauthenticatedRequesterBeforeRepository(t *testing.T) {
+ now := time.Unix(1000, 0)
+ repository := &userLookupRepositoryStub{}
+ controller := newUserLookupControllerForTest(repository, nil, func() time.Time { return now })
+
+ _, err := controller.LookupUserID(0, "[email protected]")
+ if !errors.Is(err, ente.ErrAuthenticationRequired) {
+ t.Fatalf("error = %v, want %v", err, ente.ErrAuthenticationRequired)
+ }
+ if got := repository.callCount(); got != 0 {
+ t.Fatalf("repository calls = %d, want 0", got)
+ }
+}
+
+func TestUserLookupDeniesBeforeRepositoryAndNotifiesWithoutTarget(t *testing.T) {
+ now := time.Unix(1000, 0)
+ repository := &userLookupRepositoryStub{userID: 42}
+ notifier := &userLookupNotifierStub{messages: make(chan string, 1)}
+ controller := newUserLookupControllerForTest(repository, notifier, func() time.Time { return now })
+
+ for i := 0; i < defaultUserLookupDayLimit; i++ {
+ if _, err := controller.LookupUserID(7, fmt.Sprintf("target-%[email protected]", i)); err != nil {
+ t.Fatalf("seed lookup %d returned error: %v", i, err)
+ }
+ }
+ now = now.Add(userLookupMinuteWindowDuration)
+ _, err := controller.LookupUserID(7, "[email protected]")
+ if !errors.Is(err, ente.ErrTooManyBadRequest) {
+ t.Fatalf("error = %v, want %v", err, ente.ErrTooManyBadRequest)
+ }
+ if got := repository.callCount(); got != defaultUserLookupDayLimit {
+ t.Fatalf("repository calls = %d, want %d", got, defaultUserLookupDayLimit)
+ }
+
+ select {
+ case message := <-notifier.messages:
+ const want = "user lookup limit exceeded (day window)"
+ if message != want {
+ t.Fatalf("notification = %q, want %q", message, want)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for abuse notification")
+ }
+
+ if _, err := controller.LookupUserID(7, "[email protected]"); !errors.Is(err, ente.ErrTooManyBadRequest) {
+ t.Fatalf("repeated denial error = %v, want %v", err, ente.ErrTooManyBadRequest)
+ }
+ select {
+ case message := <-notifier.messages:
+ t.Fatalf("unexpected repeated abuse notification: %q", message)
+ default:
+ }
+}
+
+func TestUserLookupNotFoundLimitBlocksNewExistingUserBeforeRepository(t *testing.T) {
+ now := time.Unix(1000, 0)
+ repository := &userLookupRepositoryStub{err: sql.ErrNoRows}
+ controller := newUserLookupControllerForTest(repository, nil, func() time.Time { return now })
+
+ for i := 0; i < defaultUserLookupNotFoundMinuteLimit; i++ {
+ _, err := controller.LookupUserID(7, fmt.Sprintf("missing-%[email protected]", i))
+ if !errors.Is(err, sql.ErrNoRows) {
+ t.Fatalf("missing lookup %d error = %v, want %v", i, err, sql.ErrNoRows)
+ }
+ }
+
+ repository.setResult(42, nil)
+ _, err := controller.LookupUserID(7, "[email protected]")
+ if !errors.Is(err, ente.ErrTooManyBadRequest) {
+ t.Fatalf("existing-user lookup error = %v, want %v", err, ente.ErrTooManyBadRequest)
+ }
+ if got := repository.callCount(); got != defaultUserLookupNotFoundMinuteLimit {
+ t.Fatalf("repository calls = %d, want %d", got, defaultUserLookupNotFoundMinuteLimit)
+ }
+}
diff --git a/server/pkg/repo/user.go b/server/pkg/repo/user.go
index 3b41ea8650..ffe8dcd527 100644
--- a/server/pkg/repo/user.go
+++ b/server/pkg/repo/user.go
@@ -328,8 +328,10 @@ func (repo *UserRepository) UpdateEmail(userID int64, encryptedEmail ente.Encryp
return stacktrace.Propagate(err, "")
}
-// GetUserIDWithEmail returns the userID associated with a provided email
-func (repo *UserRepository) GetUserIDWithEmail(email string) (int64, error) {
+// GetUserIDWithEmailUnrestricted returns the user ID associated with an email.
+// It bypasses authenticated discovery limits and is only for trusted,
+// non-disclosing flows. User-facing discovery must use controller.UserLookup.
+func (repo *UserRepository) GetUserIDWithEmailUnrestricted(email string) (int64, error) {
sanitizedEmail := emailUtil.NormalizeEmail(email)
emailHash, err := crypto.GetHash(sanitizedEmail, repo.HashingKey)
if err != nil {