π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Make SRP MFA check atomic with login issuance
Neeraj Gupta98331d8912c3
diff --git a/server/pkg/controller/user/userauth.go b/server/pkg/controller/user/userauth.goindex ac60a3f439..3746ac3ee7 100644--- a/server/pkg/controller/user/userauth.go+++ b/server/pkg/controller/user/userauth.go@@ -609,6 +609,7 @@ func emailOTT(app ente.App, to string, ott string, purpose string, mobile bool)}func (c *UserController) onVerificationSuccess(context *gin.Context, email string, source *string, srpAuth *ente.SRPAuthEntity) (ente.EmailAuthorizationResponse, error) {+ isSRPLogin := srpAuth != nilisTwoFactorEnabled := falseapp := auth.GetApp(context)@@ -664,7 +665,7 @@ func (c *UserController) onVerificationSuccess(context *gin.Context, email strintwoFactorSessionID = auth.GenerateURLSafeRandomString(TwoFactorSessionIDLength)}if hasPasskeys || isTwoFactorEnabled {- err = c.UserAuthRepo.AddLoginResult(context, userID, srpAuth, keyAttributes, app, "", "", "", passKeySessionID, twoFactorSessionID, time.Microseconds()+TwoFactorValidityDurationInMicroSeconds)+ err = c.UserAuthRepo.AddLoginResult(context, userID, srpAuth, keyAttributes, app, "", "", "", passKeySessionID, twoFactorSessionID, time.Microseconds()+TwoFactorValidityDurationInMicroSeconds, isSRPLogin)if err != nil {return ente.EmailAuthorizationResponse{}, stacktrace.Propagate(err, "")}@@ -685,7 +686,7 @@ func (c *UserController) onVerificationSuccess(context *gin.Context, email strinreturn ente.EmailAuthorizationResponse{}, err}err = c.UserAuthRepo.AddLoginResult(context, userID, srpAuth, nil, app, token,- network.GetClientIP(context), context.Request.UserAgent(), "", "", 0)+ network.GetClientIP(context), context.Request.UserAgent(), "", "", 0, isSRPLogin)if err != nil {return ente.EmailAuthorizationResponse{}, stacktrace.Propagate(err, "")}@@ -701,7 +702,7 @@ func (c *UserController) onVerificationSuccess(context *gin.Context, email strinif err = c.ensureStorageWarningDeletionLoginAllowed(userID, app); err != nil {return ente.EmailAuthorizationResponse{}, err}- err = c.UserAuthRepo.AddLoginResult(context, userID, srpAuth, keyAttributes, app, token, ip, userAgent, "", "", 0)+ err = c.UserAuthRepo.AddLoginResult(context, userID, srpAuth, keyAttributes, app, token, ip, userAgent, "", "", 0, isSRPLogin)if err == nil {err = c.notifyLogin(context, userID, app, ip, userAgent)}diff --git a/server/pkg/repo/userauth.go b/server/pkg/repo/userauth.goindex 09596fba5d..b276cf05d0 100644--- a/server/pkg/repo/userauth.go+++ b/server/pkg/repo/userauth.go@@ -3,6 +3,7 @@ package repoimport ("context""database/sql"+ "net/http""github.com/ente/museum/ente""github.com/ente/museum/pkg/utils/auth"@@ -175,7 +176,7 @@ func (repo *UserAuthRepository) AddToken(userID int64, app ente.App, token strin}func (repo *UserAuthRepository) AddLoginResult(ctx context.Context, userID int64, srpAuth *ente.SRPAuthEntity, expectedKeyAttributes *ente.KeyAttributes,- app ente.App, token, ip, userAgent, passkeySessionID, twoFactorSessionID string, expirationTime int64,+ app ente.App, token, ip, userAgent, passkeySessionID, twoFactorSessionID string, expirationTime int64, rejectEmailMFA bool,) error {tx, err := repo.DB.BeginTx(ctx, nil)if err != nil {@@ -185,6 +186,19 @@ func (repo *UserAuthRepository) AddLoginResult(ctx context.Context, userID int64if err = lockUserForLogin(ctx, tx, userID, srpAuth, expectedKeyAttributes); err != nil {return err}+ if rejectEmailMFA {+ var enabled bool+ if err = tx.QueryRowContext(ctx, `SELECT email_mfa FROM users WHERE user_id = $1`, userID).Scan(&enabled); err != nil {+ return stacktrace.Propagate(err, "")+ }+ if enabled {+ return stacktrace.Propagate(&ente.ApiError{+ Code: "EMAIL_MFA_ENABLED",+ Message: "Email MFA is enabled",+ HttpStatusCode: http.StatusConflict,+ }, "email mfa is enabled")+ }+ }now := time.Microseconds()if passkeySessionID != "" {if _, err = tx.ExecContext(ctx, `INSERT INTO passkey_login_sessions(user_id, session_id, creation_time, expiration_time) VALUES($1, $2, $3, $4)`, userID, passkeySessionID, now, expirationTime); err != nil {diff --git a/server/pkg/repo/userauth_test.go b/server/pkg/repo/userauth_test.goindex f67605c907..7e5b917d7c 100644--- a/server/pkg/repo/userauth_test.go+++ b/server/pkg/repo/userauth_test.go@@ -181,7 +181,7 @@ func TestAddLoginResultRejectsInvalidatedCredentials(t *testing.T) {t.Fatal(err)}- err = repo.AddLoginResult(context.Background(), userID, srpAuth, &keyAttributes, ente.Photos, "token", "", "", "", "", 0)+ err = repo.AddLoginResult(context.Background(), userID, srpAuth, &keyAttributes, ente.Photos, "token", "", "", "", "", 0, false)if !errors.Is(err, ente.ErrAuthenticationRequired) {t.Fatalf("stale key attributes returned %v", err)}@@ -191,7 +191,7 @@ func TestAddLoginResultRejectsInvalidatedCredentials(t *testing.T) {if _, err = db.Exec(`UPDATE srp_auth SET verifier = 'new-verifier' WHERE user_id = $1`, userID); err != nil {t.Fatal(err)}- err = repo.AddLoginResult(context.Background(), userID, srpAuth, &keyAttributes, ente.Photos, "token", "", "", "", "", 0)+ err = repo.AddLoginResult(context.Background(), userID, srpAuth, &keyAttributes, ente.Photos, "token", "", "", "", "", 0, false)if !errors.Is(err, ente.ErrInvalidPassword) {t.Fatalf("stale SRP returned %v", err)}@@ -200,10 +200,61 @@ func TestAddLoginResultRejectsInvalidatedCredentials(t *testing.T) {t.Fatalf("token count = %d, err = %v", tokenCount, err)}require.NoError(t, (&UserRepository{DB: db}).Delete(userID))- err = repo.AddLoginResult(context.Background(), userID, srpAuth, &keyAttributes, ente.Photos, "token", "", "", "", "", 0)+ err = repo.AddLoginResult(context.Background(), userID, srpAuth, &keyAttributes, ente.Photos, "token", "", "", "", "", 0, false)require.ErrorIs(t, err, ente.ErrUserDeleted)}+func TestAddLoginResultOrdersSRPLoginWithEmailMFAUpdate(t *testing.T) {+ 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{Email: "[email protected]", CreationTime: 1})+ _, err := db.Exec(`INSERT INTO srp_auth(user_id, srp_user_id, salt, verifier) VALUES($1, $2, 'salt', 'verifier')`, userID, uuid.New())+ require.NoError(t, err)+ repo := &UserAuthRepository{DB: db}+ srpAuth, err := repo.GetSRPAuthEntity(t.Context(), userID)+ require.NoError(t, err)++ update, err := db.BeginTx(t.Context(), nil)+ require.NoError(t, err)+ t.Cleanup(func() { _ = update.Rollback() })+ _, err = update.ExecContext(t.Context(), `UPDATE users SET email_mfa = true WHERE user_id = $1`, userID)+ require.NoError(t, err)+ var updatePID int+ require.NoError(t, update.QueryRowContext(t.Context(), `SELECT pg_backend_pid()`).Scan(&updatePID))+ loginResult := make(chan error, 1)+ go func() {+ loginResult <- repo.AddLoginResult(t.Context(), userID, srpAuth, nil, ente.Photos, "srp-token", "", "", "", "", 0, true)+ }()+ require.EventuallyWithT(t, func(collect *assert.CollectT) {+ var blocked bool+ require.NoError(collect, db.QueryRow(`SELECT EXISTS(SELECT 1 FROM pg_stat_activity+ WHERE datname = current_database() AND $1 = ANY(pg_blocking_pids(pid)))`, updatePID).Scan(&blocked))+ require.True(collect, blocked)+ }, 5*gotime.Second, 10*gotime.Millisecond)+ require.NoError(t, update.Commit())+ err = <-loginResult+ var apiError *ente.ApiError+ require.ErrorAs(t, err, &apiError)+ require.Equal(t, ente.ErrorCode("EMAIL_MFA_ENABLED"), apiError.Code)+ require.Equal(t, 409, apiError.HttpStatusCode)++ err = repo.AddLoginResult(t.Context(), userID, srpAuth, nil, ente.Photos, "", "", "", "", "srp-pending", time.Microseconds()+1000000, true)+ require.ErrorAs(t, err, &apiError)+ require.Equal(t, ente.ErrorCode("EMAIL_MFA_ENABLED"), apiError.Code)+ var issued int+ require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM tokens WHERE user_id = $1`, userID).Scan(&issued))+ require.Zero(t, issued)+ require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM two_factor_sessions WHERE user_id = $1`, userID).Scan(&issued))+ require.Zero(t, issued)++ require.NoError(t, repo.AddLoginResult(t.Context(), userID, srpAuth, nil, ente.Photos, "email-token", "", "", "", "", 0, false))+ require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM tokens WHERE user_id = $1`, userID).Scan(&issued))+ require.Equal(t, 1, issued)+}+func TestPasswordUpdateRollsBackRecoveryAuthorization(t *testing.T) {testutil.WithServerRoot(t)