Skip to content

armgit / ente

Public Imported from GitHub
0

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

Harden recipient identity lookup

Neeraj Guptad4786b0b43a5
diff --git a/server/ente/collection.go b/server/ente/collection.go
index d738c03a41..1e0f67d77a 100644
--- a/server/ente/collection.go
+++ b/server/ente/collection.go
@@ -137,6 +137,7 @@ type BulkCollectionShareItem struct {
type BulkCollectionShareRequest struct {
RecipientUserID int64 `json:"recipientUserID" binding:"required"`
+ RecipientEmail string `json:"recipientEmail" binding:"required"`
Source CollectionShareSource `json:"source" binding:"required"`
Collections []BulkCollectionShareItem `json:"collections" binding:"required"`
}
diff --git a/server/ente/errors.go b/server/ente/errors.go
index 649f111e58..d39fa618e5 100644
--- a/server/ente/errors.go
+++ b/server/ente/errors.go
@@ -202,6 +202,12 @@ var ErrUserNotFound = &ApiError{
HttpStatusCode: http.StatusNotFound,
}
+var ErrRecipientIdentityMismatch = &ApiError{
+ Code: "RECIPIENT_IDENTITY_MISMATCH",
+ Message: "Recipient identity does not match",
+ HttpStatusCode: http.StatusConflict,
+}
+
var ErrMaxPasskeysReached = ApiError{
Code: MaxPasskeysReached,
Message: "Max passkeys limit reached",
diff --git a/server/pkg/api/user.go b/server/pkg/api/user.go
index 21cdcd28f1..5658720da6 100644
--- a/server/pkg/api/user.go
+++ b/server/pkg/api/user.go
@@ -149,18 +149,10 @@ func (h *UserHandler) SetRecoveryKey(c *gin.Context) {
// GetPublicKey returns the public key of a user
func (h *UserHandler) GetPublicKey(c *gin.Context) {
- var publicKey string
- var err error
- if userID := c.Query("userID"); userID != "" {
- targetUserID, parseErr := strconv.ParseInt(userID, 10, 64)
- if parseErr != nil || targetUserID <= 0 {
- handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "invalid userID"))
- return
- }
- publicKey, err = h.UserController.GetPublicKeyByUserID(targetUserID)
- } else {
- publicKey, err = h.UserController.GetPublicKey(auth.GetUserID(c.Request.Header), c.Query("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/api/user_test.go b/server/pkg/api/user_test.go
index 26d0a30d0f..c0d897682a 100644
--- a/server/pkg/api/user_test.go
+++ b/server/pkg/api/user_test.go
@@ -11,6 +11,7 @@ import (
"github.com/ente/museum/ente"
"github.com/ente/museum/internal/testutil"
+ museumcontroller "github.com/ente/museum/pkg/controller"
usercontroller "github.com/ente/museum/pkg/controller/user"
"github.com/ente/museum/pkg/repo"
"github.com/gin-gonic/gin"
@@ -52,33 +53,31 @@ func TestSetAttributesHandlerRejectsLowMemoryLimit(t *testing.T) {
assertAPIErrorResponse(t, recorder, http.StatusBadRequest, ente.BadRequest, "memory limit must be at least 128MB")
}
-func TestGetPublicKeyHandlerLooksUpUserByID(t *testing.T) {
+func TestGetPublicKeyHandlerUsesEmailLookup(t *testing.T) {
handler, db := setupUserHandlerTest(t)
+ requesterUserID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 102,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
targetUserID := testutil.InsertUser(t, db, testutil.UserFixture{
UserID: 103,
CreationTime: 1,
})
- keyAttributes := ente.KeyAttributes{
- KEKSalt: "kek-salt",
- KEKHash: "kek-hash",
- EncryptedKey: "encrypted-key",
- KeyDecryptionNonce: "key-decryption-nonce",
- PublicKey: "target-public-key",
- EncryptedSecretKey: "encrypted-secret-key",
- SecretKeyDecryptionNonce: "secret-key-decryption-nonce",
- MemLimit: 128 * 1024 * 1024,
- OpsLimit: 32,
- }
- if err := handler.UserController.UserRepo.SetKeyAttributes(targetUserID, keyAttributes); err != nil {
- t.Fatalf("failed to set key attributes: %v", err)
- }
+ keyAttributes := setPublicKeyTestAttributes(t, handler, targetUserID)
- recorder := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "/users/public-key?userID="+strconv.FormatInt(targetUserID, 10), nil)
router := gin.New()
router.GET("/users/public-key", handler.GetPublicKey)
+
+ recorder := httptest.NewRecorder()
+ req := httptest.NewRequest(
+ http.MethodGet,
+ "/users/public-key?email=public-key-target%40ente.com",
+ nil,
+ )
+ req.Header.Set("X-Auth-User-ID", strconv.FormatInt(requesterUserID, 10))
router.ServeHTTP(recorder, req)
if recorder.Code != http.StatusOK {
@@ -95,6 +94,51 @@ func TestGetPublicKeyHandlerLooksUpUserByID(t *testing.T) {
}
}
+func TestGetPublicKeyHandlerDoesNotLookupByUserID(t *testing.T) {
+ handler, db := setupUserHandlerTest(t)
+ requesterUserID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 101,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ targetUserID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 102,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ setPublicKeyTestAttributes(t, handler, targetUserID)
+
+ recorder := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/users/public-key?userID=102", nil)
+ req.Header.Set("X-Auth-User-ID", strconv.FormatInt(requesterUserID, 10))
+ router := gin.New()
+ router.GET("/users/public-key", handler.GetPublicKey)
+ router.ServeHTTP(recorder, req)
+
+ if recorder.Code != http.StatusNotFound {
+ t.Fatalf("unexpected status code: got %d want %d; body=%s", recorder.Code, http.StatusNotFound, recorder.Body.String())
+ }
+}
+
+func setPublicKeyTestAttributes(t *testing.T, handler *UserHandler, userID int64) ente.KeyAttributes {
+ t.Helper()
+ keyAttributes := ente.KeyAttributes{
+ KEKSalt: "kek-salt",
+ KEKHash: "kek-hash",
+ EncryptedKey: "encrypted-key",
+ KeyDecryptionNonce: "key-decryption-nonce",
+ PublicKey: "target-public-key",
+ EncryptedSecretKey: "encrypted-secret-key",
+ SecretKeyDecryptionNonce: "secret-key-decryption-nonce",
+ MemLimit: 128 * 1024 * 1024,
+ OpsLimit: 32,
+ }
+ if err := handler.UserController.UserRepo.SetKeyAttributes(userID, keyAttributes); err != nil {
+ t.Fatalf("failed to set key attributes: %v", err)
+ }
+ return keyAttributes
+}
+
func setupUserHandlerTest(t *testing.T) (*UserHandler, *sql.DB) {
t.Helper()
@@ -114,7 +158,8 @@ func setupUserHandlerTest(t *testing.T) (*UserHandler, *sql.DB) {
return &UserHandler{
UserController: &usercontroller.UserController{
- UserRepo: userRepo,
+ UserRepo: userRepo,
+ UserLookup: museumcontroller.NewUserLookupController(userRepo, nil),
},
}, db
}
diff --git a/server/pkg/controller/collections/share.go b/server/pkg/controller/collections/share.go
index 3549fd56b0..c6d2b9edf2 100644
--- a/server/pkg/controller/collections/share.go
+++ b/server/pkg/controller/collections/share.go
@@ -72,6 +72,13 @@ func (c *CollectionController) BulkShare(
if err := validateBulkShareRecipient(fromUserID, req.RecipientUserID); err != nil {
return nil, err
}
+ if err := c.UserLookup.VerifyUserID(
+ fromUserID,
+ req.RecipientEmail,
+ req.RecipientUserID,
+ ); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
results := make([]ente.BulkCollectionShareResult, 0, len(req.Collections))
for _, item := range req.Collections {
diff --git a/server/pkg/controller/collections/share_test.go b/server/pkg/controller/collections/share_test.go
index 0159d6093d..a7f27886ab 100644
--- a/server/pkg/controller/collections/share_test.go
+++ b/server/pkg/controller/collections/share_test.go
@@ -10,6 +10,7 @@ import (
"github.com/ente/museum/ente"
"github.com/ente/museum/internal/testutil"
+ museumcontroller "github.com/ente/museum/pkg/controller"
"github.com/ente/museum/pkg/repo"
castRepo "github.com/ente/museum/pkg/repo/cast"
publicRepo "github.com/ente/museum/pkg/repo/public"
@@ -22,6 +23,10 @@ func (panicUserLookup) LookupUserID(int64, string) (int64, error) {
panic("user lookup must not be called while revoking collection access")
}
+func (panicUserLookup) VerifyUserID(int64, string, int64) error {
+ panic("user lookup must not be called while revoking collection access")
+}
+
type fixedUserLookup struct {
userID int64
}
@@ -30,6 +35,10 @@ func (l fixedUserLookup) LookupUserID(int64, string) (int64, error) {
return l.userID, nil
}
+func (fixedUserLookup) VerifyUserID(int64, string, int64) error {
+ return nil
+}
+
func newShareTestCollectionRepo(db *sql.DB) *repo.CollectionRepository {
return &repo.CollectionRepository{
DB: db,
@@ -38,6 +47,13 @@ func newShareTestCollectionRepo(db *sql.DB) *repo.CollectionRepository {
}
}
+func newShareTestUserLookup(db *sql.DB) *museumcontroller.UserLookupController {
+ return museumcontroller.NewUserLookupController(&repo.UserRepository{
+ DB: db,
+ HashingKey: testutil.HashingKey(),
+ }, nil)
+}
+
func createShareTestCollection(t *testing.T, collectionRepo *repo.CollectionRepository, ownerID int64) int64 {
return createShareTestCollectionOfType(t, collectionRepo, ownerID, "album")
}
@@ -463,6 +479,7 @@ func TestBulkShareAndUnshareReturnPerCollectionStatuses(t *testing.T) {
controller := &CollectionController{
CollectionRepo: collectionRepo,
CastRepo: &castRepo.Repository{DB: db},
+ UserLookup: newShareTestUserLookup(db),
}
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
ctx.Request = httptest.NewRequest("POST", "/collections/share/bulk", nil)
@@ -470,6 +487,7 @@ func TestBulkShareAndUnshareReturnPerCollectionStatuses(t *testing.T) {
results, err := controller.BulkShare(ctx, ente.BulkCollectionShareRequest{
RecipientUserID: shareeID,
+ RecipientEmail: "[email protected]",
Source: ente.AutomaticShare,
Collections: []ente.BulkCollectionShareItem{
{
@@ -492,6 +510,7 @@ func TestBulkShareAndUnshareReturnPerCollectionStatuses(t *testing.T) {
t.Fatalf("bulk share results = %+v", results)
}
+ controller.UserLookup = panicUserLookup{}
unshareResults, err := controller.BulkUnShare(ctx, ente.BulkCollectionUnshareRequest{
RecipientUserID: shareeID,
Source: ente.AutomaticShare,
@@ -506,6 +525,43 @@ func TestBulkShareAndUnshareReturnPerCollectionStatuses(t *testing.T) {
}
}
+func TestBulkShareRejectsRecipientIdentityMismatchBeforeMutation(t *testing.T) {
+ db, collectionRepo, ownerID, shareeID := setupCollectionShareTest(t)
+ collectionID := createShareTestCollection(t, collectionRepo, ownerID)
+ controller := &CollectionController{
+ CollectionRepo: collectionRepo,
+ UserLookup: newShareTestUserLookup(db),
+ }
+ ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
+ ctx.Request = httptest.NewRequest("POST", "/collections/share/bulk", nil)
+ ctx.Request.Header.Set("X-Auth-User-ID", strconv.FormatInt(ownerID, 10))
+
+ _, err := controller.BulkShare(ctx, ente.BulkCollectionShareRequest{
+ RecipientUserID: shareeID + 1,
+ RecipientEmail: "[email protected]",
+ Source: ente.AutomaticShare,
+ Collections: []ente.BulkCollectionShareItem{{
+ CollectionID: collectionID,
+ EncryptedKey: b64OfLen(sealedCollectionKeyLen),
+ Role: ente.VIEWER,
+ }},
+ })
+ if !errors.Is(err, ente.ErrRecipientIdentityMismatch) {
+ t.Fatalf("bulk share error = %v, want %v", err, ente.ErrRecipientIdentityMismatch)
+ }
+
+ var shareCount int
+ if err := db.QueryRow(
+ `SELECT count(*) FROM collection_shares WHERE collection_id = $1`,
+ collectionID,
+ ).Scan(&shareCount); err != nil {
+ t.Fatal(err)
+ }
+ if shareCount != 0 {
+ t.Fatalf("collection shares after rejected request = %d, want 0", shareCount)
+ }
+}
+
func TestBulkShareRejectsOversizedBatch(t *testing.T) {
items := make([]ente.BulkCollectionShareItem, ente.MaxCollectionShareBatchSize+1)
for index := range items {
diff --git a/server/pkg/controller/user/user.go b/server/pkg/controller/user/user.go
index 8b5a63bc94..b31a7f8090 100644
--- a/server/pkg/controller/user/user.go
+++ b/server/pkg/controller/user/user.go
@@ -242,11 +242,6 @@ func (c *UserController) GetPublicKey(requesterUserID int64, email string) (stri
if err != nil {
return "", stacktrace.Propagate(err, "")
}
- return c.GetPublicKeyByUserID(userID)
-}
-
-// GetPublicKeyByUserID returns the public key of a user.
-func (c *UserController) GetPublicKeyByUserID(userID int64) (string, error) {
key, err := c.UserRepo.GetPublicKey(userID)
if err != nil {
return "", stacktrace.Propagate(err, "")
diff --git a/server/pkg/controller/user_lookup.go b/server/pkg/controller/user_lookup.go
index 42ea8ba5de..02fa51e78d 100644
--- a/server/pkg/controller/user_lookup.go
+++ b/server/pkg/controller/user_lookup.go
@@ -3,6 +3,7 @@ package controller
import (
"database/sql"
"errors"
+ "strconv"
"github.com/ente/museum/ente"
"github.com/ente/museum/pkg/repo"
@@ -22,6 +23,7 @@ type potentialAbuseNotifier interface {
// UserLookup applies the shared authenticated email-discovery policy.
type UserLookup interface {
LookupUserID(requesterUserID int64, email string) (int64, error)
+ VerifyUserID(requesterUserID int64, email string, expectedUserID int64) error
}
// UserLookupController limits email discovery before querying the user repository.
@@ -42,12 +44,38 @@ func NewUserLookupController(userRepo *repo.UserRepository, notifier potentialAb
}
func (c *UserLookupController) LookupUserID(requesterUserID int64, email string) (int64, error) {
+ return c.lookupUserID(requesterUserID, email, nil)
+}
+
+// VerifyUserID applies the shared lookup policy and verifies that email still
+// identifies expectedUserID.
+func (c *UserLookupController) VerifyUserID(
+ requesterUserID int64,
+ email string,
+ expectedUserID int64,
+) error {
+ _, err := c.lookupUserID(requesterUserID, email, &expectedUserID)
+ return err
+}
+
+func (c *UserLookupController) lookupUserID(
+ requesterUserID int64,
+ email string,
+ expectedUserID *int64,
+) (int64, error) {
if requesterUserID <= 0 {
return -1, stacktrace.Propagate(ente.ErrAuthenticationRequired, "")
}
+ if expectedUserID != nil && *expectedUserID <= 0 {
+ return -1, stacktrace.Propagate(ente.ErrBadRequest, "invalid expected user ID")
+ }
normalizedEmail := emailUtil.NormalizeEmail(email)
- targetHash, err := crypto.GetHash(normalizedEmail, c.hashingKey)
+ limitTarget := normalizedEmail
+ if expectedUserID != nil {
+ limitTarget = "email-user-id\x00" + normalizedEmail + "\x00" + strconv.FormatInt(*expectedUserID, 10)
+ }
+ targetHash, err := crypto.GetHash(limitTarget, c.hashingKey)
if err != nil {
return -1, stacktrace.Propagate(err, "")
}
@@ -58,10 +86,15 @@ func (c *UserLookupController) LookupUserID(requesterUserID int64, email string)
}
userID, err := c.userRepo.GetUserIDWithEmailUnrestricted(normalizedEmail)
- decision = c.lookupLimit.Finish(attempt, errors.Is(err, sql.ErrNoRows))
+ identityMismatch := errors.Is(err, sql.ErrNoRows) ||
+ (err == nil && expectedUserID != nil && userID != *expectedUserID)
+ decision = c.lookupLimit.Finish(attempt, identityMismatch)
if !decision.allowed {
return -1, c.limitExceeded(decision)
}
+ if expectedUserID != nil && identityMismatch {
+ return -1, stacktrace.Propagate(ente.ErrRecipientIdentityMismatch, "")
+ }
return userID, err
}
diff --git a/server/pkg/controller/user_lookup_test.go b/server/pkg/controller/user_lookup_test.go
index b6124dd377..7d070846e3 100644
--- a/server/pkg/controller/user_lookup_test.go
+++ b/server/pkg/controller/user_lookup_test.go
@@ -91,6 +91,58 @@ func TestUserLookupNormalizesAndAlwaysQueriesRepository(t *testing.T) {
}
}
+func TestUserLookupVerifiesNormalizedEmailAndExpectedUserID(t *testing.T) {
+ now := time.Unix(1000, 0)
+ repository := &userLookupRepositoryStub{userID: 42}
+ controller := newUserLookupControllerForTest(repository, nil, func() time.Time { return now })
+
+ err := controller.VerifyUserID(1, " [email protected] ", 42)
+ if err != nil {
+ t.Fatalf("verify returned error: %v", err)
+ }
+ if got := repository.emails[0]; got != "[email protected]" {
+ t.Fatalf("repository email = %q, want normalized email", got)
+ }
+}
+
+func TestUserLookupVerifyReturnsSameErrorForMissingEmailAndMismatchedUserID(t *testing.T) {
+ now := time.Unix(1000, 0)
+ repository := &userLookupRepositoryStub{userID: 42}
+ controller := newUserLookupControllerForTest(repository, nil, func() time.Time { return now })
+
+ mismatchErr := controller.VerifyUserID(1, "[email protected]", 43)
+ if !errors.Is(mismatchErr, ente.ErrRecipientIdentityMismatch) {
+ t.Fatalf("mismatch error = %v, want %v", mismatchErr, ente.ErrRecipientIdentityMismatch)
+ }
+
+ repository.setResult(-1, sql.ErrNoRows)
+ missingErr := controller.VerifyUserID(1, "[email protected]", 44)
+ if !errors.Is(missingErr, ente.ErrRecipientIdentityMismatch) {
+ t.Fatalf("missing email error = %v, want %v", missingErr, ente.ErrRecipientIdentityMismatch)
+ }
+}
+
+func TestUserLookupVerifyLimitsDistinctIDsForSameEmailAsMissingTargets(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 < defaultUserLookupNotFoundMinuteLimit; i++ {
+ err := controller.VerifyUserID(7, "[email protected]", int64(100+i))
+ if !errors.Is(err, ente.ErrRecipientIdentityMismatch) {
+ t.Fatalf("mismatch %d error = %v, want %v", i, err, ente.ErrRecipientIdentityMismatch)
+ }
+ }
+
+ err := controller.VerifyUserID(7, "[email protected]", 999)
+ if !errors.Is(err, ente.ErrTooManyBadRequest) {
+ t.Fatalf("next mismatch error = %v, want %v", err, ente.ErrTooManyBadRequest)
+ }
+ if got := repository.callCount(); got != defaultUserLookupNotFoundMinuteLimit {
+ t.Fatalf("repository calls = %d, want %d", got, defaultUserLookupNotFoundMinuteLimit)
+ }
+}
+
func TestUserLookupRejectsUnauthenticatedRequesterBeforeRepository(t *testing.T) {
now := time.Unix(1000, 0)
repository := &userLookupRepositoryStub{}