Skip to content

armgit / ente

Public Imported from GitHub
0

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

Fix err handling

Neeraj Gupta52a918897e1a
diff --git a/server/pkg/controller/user/userauth.go b/server/pkg/controller/user/userauth.go
index 53fba45b7c..350c1514cf 100644
--- a/server/pkg/controller/user/userauth.go
+++ b/server/pkg/controller/user/userauth.go
@@ -93,9 +93,13 @@ func hardcodedOTTForEmail(hardCodedOTT HardCodedOTT, email string) string {
// SendEmailOTT generates and sends an OTT to the provided email address
func (c *UserController) SendEmailOTT(context *gin.Context, email string, purpose string, mobile bool) error {
- if err := c.validateSendOTT(context, email, purpose); err != nil {
+ shouldSend, err := c.validateSendOTT(context, email, purpose)
+ if err != nil {
return err
}
+ if !shouldSend {
+ return nil
+ }
ott, err := random.GenerateSixDigitOtp()
if err != nil {
return stacktrace.Propagate(err, "")
@@ -118,7 +122,7 @@ func (c *UserController) SendEmailOTT(context *gin.Context, email string, purpos
app := auth.GetApp(context)
otts, _ := c.UserAuthRepo.GetValidOTTs(emailHash, app)
if len(otts) >= OTTActiveCodeLimit {
- const msg = "Too many ott requests in a short duration"
+ const msg = "Too many requests in a short duration"
go c.DiscordController.NotifyPotentialAbuse(msg)
return stacktrace.Propagate(ente.ErrTooManyBadRequest, msg)
}
@@ -152,43 +156,61 @@ func (c *UserController) isEmailAlreadyUsed(email string) error {
return nil
}
-func (c *UserController) validateSendOTT(ctx *gin.Context, email string, purpose string) error {
+func (c *UserController) validateSendOTT(ctx *gin.Context, email string, purpose string) (bool, error) {
+ var disclosureErr error
if purpose == ente.ChangeEmailOTTPurpose {
if err := c.isEmailAlreadyUsed(email); err != nil {
- return err
+ if !errors.Is(err, ente.ErrPermissionDenied) {
+ return false, err
+ }
+ disclosureErr = err
}
}
- signupState, err := c.getSignUpState(email)
- if err != nil {
- return stacktrace.Propagate(err, "")
+ if purpose != ente.ChangeEmailOTTPurpose {
+ signupState, err := c.getSignUpState(email)
+ if err != nil {
+ return false, stacktrace.Propagate(err, "")
+ }
+ if purpose == ente.SignUpOTTPurpose && viper.GetBool("internal.disable-registration") && signupState != signUpStateComplete {
+ return false, stacktrace.Propagate(ente.ErrPermissionDenied, "registration is disabled")
+ }
+ if purpose == ente.SignUpOTTPurpose && signupState == signUpStateComplete {
+ disclosureErr = stacktrace.Propagate(ente.ErrUserAlreadyRegistered, "user has already completed sign up process")
+ }
+ if purpose == ente.LoginOTTPurpose && signupState == signUpStateNoAccount {
+ disclosureErr = stacktrace.Propagate(ente.ErrUserNotRegistered, "user account does not exist")
+ }
+ if purpose == ente.LoginOTTPurpose && signupState == signUpStateIncomplete {
+ disclosureErr = stacktrace.Propagate(ente.ErrUserSignupIncomplete, "user has not completed sign up process")
+ }
}
- if purpose == ente.SignUpOTTPurpose && viper.GetBool("internal.disable-registration") && signupState != signUpStateComplete {
- return stacktrace.Propagate(ente.ErrPermissionDenied, "registration is disabled")
+ // If there is no state-disclosing error, allow the OTT request.
+ if disclosureErr == nil {
+ return true, nil
}
- //
- var registrationErr error
- if purpose == ente.SignUpOTTPurpose && signupState == signUpStateComplete {
- registrationErr = stacktrace.Propagate(ente.ErrUserAlreadyRegistered, "user has already completed sign up process")
+
+ if c.shouldSwallowSendOTTDisclosureError(ctx) {
+ return false, nil
}
- if purpose == ente.LoginOTTPurpose && signupState == signUpStateNoAccount {
- registrationErr = stacktrace.Propagate(ente.ErrUserNotRegistered, "user account does not exist")
+ return false, disclosureErr
+}
+
+func (c *UserController) shouldSwallowSendOTTDisclosureError(ctx *gin.Context) bool {
+ if c.OTTLimiter == nil {
+ return false
}
- if purpose == ente.LoginOTTPurpose && signupState == signUpStateIncomplete {
- registrationErr = stacktrace.Propagate(ente.ErrUserSignupIncomplete, "user has not completed sign up process")
+ limitContext, limitErr := c.OTTLimiter.Get(ctx, "send-ott")
+ if limitErr != nil {
+ log.WithError(limitErr).Warn("Failed to check send-ott disclosure rate limit")
+ return false
}
- // if no registration error, return
- if registrationErr == nil {
- return registrationErr
+ if !limitContext.Reached {
+ return false
}
- // check & swallow registration information error if too many such
- // errors are generated in a short time
- if limiter, limitErr := c.OTTLimiter.Get(ctx, "send-ott"); limitErr != nil {
- if limiter.Reached {
- go c.DiscordController.NotifyPotentialAbuse("swallowing send-ott registration error")
- return nil
- }
+ if c.DiscordController != nil {
+ go c.DiscordController.NotifyPotentialAbuse("swallowing send-ott disclosure error")
}
- return registrationErr
+ return true
}
// getSignUpState returns the signup state for an email.
diff --git a/server/pkg/controller/user/userauth_send_ott_test.go b/server/pkg/controller/user/userauth_send_ott_test.go
new file mode 100644
index 0000000000..e3f33917c8
--- /dev/null
+++ b/server/pkg/controller/user/userauth_send_ott_test.go
@@ -0,0 +1,234 @@
+package user
+
+import (
+ "database/sql"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/ente/museum/ente"
+ "github.com/ente/museum/internal/testutil"
+ "github.com/ente/museum/pkg/repo"
+ util "github.com/ente/museum/pkg/utils"
+ "github.com/ente/museum/pkg/utils/crypto"
+ "github.com/gin-gonic/gin"
+)
+
+func TestShouldSwallowSendOTTDisclosureErrorAfterLimiter(t *testing.T) {
+ controller := &UserController{
+ OTTLimiter: util.NewRateLimiter("1-H"),
+ }
+
+ if controller.shouldSwallowSendOTTDisclosureError(newSendOTTTestContext()) {
+ t.Fatal("first disclosure error should not be swallowed")
+ }
+ if !controller.shouldSwallowSendOTTDisclosureError(newSendOTTTestContext()) {
+ t.Fatal("second disclosure error should be swallowed")
+ }
+}
+
+func TestValidateSendOTTSwallowsDisclosureErrorsAfterLimiter(t *testing.T) {
+ testutil.WithServerRoot(t)
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ userRepo := &repo.UserRepository{
+ DB: db,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ HashingKey: testutil.HashingKey(),
+ }
+
+ tests := []struct {
+ name string
+ email string
+ purpose string
+ setup func(t *testing.T)
+ wantErr error
+ }{
+ {
+ name: "signup existing complete account",
+ email: "[email protected]",
+ purpose: ente.SignUpOTTPurpose,
+ setup: func(t *testing.T) {
+ insertCompleteSendOTTTestUser(t, db, userRepo, 101, "[email protected]")
+ },
+ wantErr: ente.ErrUserAlreadyRegistered,
+ },
+ {
+ name: "login missing account",
+ email: "[email protected]",
+ purpose: ente.LoginOTTPurpose,
+ wantErr: ente.ErrUserNotRegistered,
+ },
+ {
+ name: "login incomplete account",
+ email: "[email protected]",
+ purpose: ente.LoginOTTPurpose,
+ setup: func(t *testing.T) {
+ testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 102,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ },
+ wantErr: ente.ErrUserSignupIncomplete,
+ },
+ {
+ name: "change email existing account",
+ email: "[email protected]",
+ purpose: ente.ChangeEmailOTTPurpose,
+ setup: func(t *testing.T) {
+ testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 103,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ },
+ wantErr: ente.ErrPermissionDenied,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ testutil.ResetTables(t, db)
+ controller := &UserController{
+ UserRepo: userRepo,
+ OTTLimiter: util.NewRateLimiter("1-H"),
+ }
+ if tt.setup != nil {
+ tt.setup(t)
+ }
+
+ shouldSend, err := controller.validateSendOTT(newSendOTTTestContext(), tt.email, tt.purpose)
+ if !errors.Is(err, tt.wantErr) {
+ t.Fatalf("first validateSendOTT error = %v, want %v", err, tt.wantErr)
+ }
+ if shouldSend {
+ t.Fatal("first validateSendOTT should not allow sending for disclosure error")
+ }
+
+ shouldSend, err = controller.validateSendOTT(newSendOTTTestContext(), tt.email, tt.purpose)
+ if err != nil {
+ t.Fatalf("second validateSendOTT should swallow disclosure error, got %v", err)
+ }
+ if shouldSend {
+ t.Fatal("second validateSendOTT should swallow disclosure error without sending")
+ }
+ })
+ }
+}
+
+func TestValidateSendOTTAllowsUnusedChangeEmailWithoutLimiter(t *testing.T) {
+ testutil.WithServerRoot(t)
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ controller := &UserController{
+ UserRepo: &repo.UserRepository{
+ DB: db,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ HashingKey: testutil.HashingKey(),
+ },
+ }
+
+ shouldSend, err := controller.validateSendOTT(newSendOTTTestContext(), "[email protected]", ente.ChangeEmailOTTPurpose)
+ if err != nil {
+ t.Fatalf("unused change email should be allowed, got %v", err)
+ }
+ if !shouldSend {
+ t.Fatal("unused change email should allow sending")
+ }
+}
+
+func TestSendEmailOTTDoesNotStoreOTTWhenDisclosureErrorSwallowed(t *testing.T) {
+ testutil.WithServerRoot(t)
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ const email = "[email protected]"
+ userAuthRepo := &repo.UserAuthRepository{DB: db}
+ controller := &UserController{
+ UserRepo: &repo.UserRepository{
+ DB: db,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ HashingKey: testutil.HashingKey(),
+ },
+ UserAuthRepo: userAuthRepo,
+ HashingKey: testutil.HashingKey(),
+ OTTLimiter: util.NewRateLimiter("1-H"),
+ HardCodedOTT: HardCodedOTT{
+ Emails: []HardCodedOTTEmail{
+ {
+ Email: email,
+ Value: "123456",
+ },
+ },
+ },
+ }
+
+ err := controller.SendEmailOTT(newSendOTTTestContext(), email, ente.LoginOTTPurpose, false)
+ if !errors.Is(err, ente.ErrUserNotRegistered) {
+ t.Fatalf("first SendEmailOTT error = %v, want %v", err, ente.ErrUserNotRegistered)
+ }
+
+ err = controller.SendEmailOTT(newSendOTTTestContext(), email, ente.LoginOTTPurpose, false)
+ if err != nil {
+ t.Fatalf("second SendEmailOTT should swallow disclosure error, got %v", err)
+ }
+
+ emailHash, err := crypto.GetHash(email, testutil.HashingKey())
+ if err != nil {
+ t.Fatalf("failed to hash email: %v", err)
+ }
+ otts, err := userAuthRepo.GetValidOTTs(emailHash, ente.Photos)
+ if err != nil {
+ t.Fatalf("failed to get valid otts: %v", err)
+ }
+ if len(otts) != 0 {
+ t.Fatalf("swallowed disclosure error should not store ott, got %v", otts)
+ }
+}
+
+func newSendOTTTestContext() *gin.Context {
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(http.MethodPost, "/users/ott", nil)
+ return ctx
+}
+
+func insertCompleteSendOTTTestUser(t *testing.T, db *sql.DB, userRepo *repo.UserRepository, userID int64, email string) {
+ t.Helper()
+ insertedUserID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: userID,
+ Email: email,
+ CreationTime: 1,
+ })
+ if err := userRepo.SetKeyAttributes(insertedUserID, sendOTTTestKeyAttributes()); err != nil {
+ t.Fatalf("failed to set key attributes: %v", err)
+ }
+}
+
+func sendOTTTestKeyAttributes() ente.KeyAttributes {
+ return ente.KeyAttributes{
+ KEKSalt: "kek-salt",
+ KEKHash: "kek-hash",
+ EncryptedKey: "encrypted-key",
+ KeyDecryptionNonce: "key-decryption-nonce",
+ PublicKey: "public-key",
+ EncryptedSecretKey: "encrypted-secret-key",
+ SecretKeyDecryptionNonce: "secret-key-decryption-nonce",
+ MemLimit: 128 * 1024 * 1024,
+ OpsLimit: 32,
+ }
+}