From 4ffaa9343103fe692d26be8faa21d477abb9c7cf Mon Sep 17 00:00:00 2001 From: Nutomic Date: Tue, 21 May 2024 20:46:49 +0200 Subject: [PATCH] Dont allow reusing password reset token, use normal rate limit (#4719) * Dont allow reusing password reset token, use normal rate limit * fix --- .../local_user/change_password_after_reset.rs | 2 +- crates/api/src/local_user/reset_password.rs | 10 -- crates/api_common/src/utils.rs | 2 +- .../src/impls/password_reset_request.rs | 128 +++++++----------- crates/utils/src/error.rs | 1 - src/api_routes_http.rs | 6 +- 6 files changed, 54 insertions(+), 95 deletions(-) diff --git a/crates/api/src/local_user/change_password_after_reset.rs b/crates/api/src/local_user/change_password_after_reset.rs index 9d693a750..f86421796 100644 --- a/crates/api/src/local_user/change_password_after_reset.rs +++ b/crates/api/src/local_user/change_password_after_reset.rs @@ -19,7 +19,7 @@ pub async fn change_password_after_reset( ) -> LemmyResult> { // Fetch the user_id from the token let token = data.token.clone(); - let local_user_id = PasswordResetRequest::read_from_token(&mut context.pool(), &token) + let local_user_id = PasswordResetRequest::read_and_delete(&mut context.pool(), &token) .await? .ok_or(LemmyErrorType::TokenNotFound)? .local_user_id; diff --git a/crates/api/src/local_user/reset_password.rs b/crates/api/src/local_user/reset_password.rs index edb5adee6..b6b113c07 100644 --- a/crates/api/src/local_user/reset_password.rs +++ b/crates/api/src/local_user/reset_password.rs @@ -6,7 +6,6 @@ use lemmy_api_common::{ utils::send_password_reset_email, SuccessResponse, }; -use lemmy_db_schema::source::password_reset_request::PasswordResetRequest; use lemmy_db_views::structs::{LocalUserView, SiteView}; use lemmy_utils::error::{LemmyErrorType, LemmyResult}; @@ -21,15 +20,6 @@ pub async fn reset_password( .await? .ok_or(LemmyErrorType::IncorrectLogin)?; - // Check for too many attempts (to limit potential abuse) - let recent_resets_count = PasswordResetRequest::get_recent_password_resets_count( - &mut context.pool(), - local_user_view.local_user.id, - ) - .await?; - if recent_resets_count >= 3 { - Err(LemmyErrorType::PasswordResetLimitReached)? - } let site_view = SiteView::read_local(&mut context.pool()) .await? .ok_or(LemmyErrorType::LocalSiteNotSetup)?; diff --git a/crates/api_common/src/utils.rs b/crates/api_common/src/utils.rs index 4ab587928..7db4c56ea 100644 --- a/crates/api_common/src/utils.rs +++ b/crates/api_common/src/utils.rs @@ -440,7 +440,7 @@ pub async fn send_password_reset_email( // Insert the row after successful send, to avoid using daily reset limit while // email sending is broken. let local_user_id = user.local_user.id; - PasswordResetRequest::create_token(pool, local_user_id, token.clone()).await?; + PasswordResetRequest::create(pool, local_user_id, token.clone()).await?; Ok(()) } diff --git a/crates/db_schema/src/impls/password_reset_request.rs b/crates/db_schema/src/impls/password_reset_request.rs index 4fad632f5..c92cb0867 100644 --- a/crates/db_schema/src/impls/password_reset_request.rs +++ b/crates/db_schema/src/impls/password_reset_request.rs @@ -1,49 +1,22 @@ use crate::{ diesel::OptionalExtension, newtypes::LocalUserId, - schema::password_reset_request::dsl::{local_user_id, password_reset_request, published, token}, + schema::password_reset_request::dsl::{password_reset_request, published, token}, source::password_reset_request::{PasswordResetRequest, PasswordResetRequestForm}, - traits::Crud, utils::{get_conn, DbPool}, }; use diesel::{ + delete, dsl::{insert_into, now, IntervalDsl}, result::Error, sql_types::Timestamptz, ExpressionMethods, IntoSql, - QueryDsl, }; use diesel_async::RunQueryDsl; -#[async_trait] -impl Crud for PasswordResetRequest { - type InsertForm = PasswordResetRequestForm; - type UpdateForm = PasswordResetRequestForm; - type IdType = i32; - - async fn create(pool: &mut DbPool<'_>, form: &PasswordResetRequestForm) -> Result { - let conn = &mut get_conn(pool).await?; - insert_into(password_reset_request) - .values(form) - .get_result::(conn) - .await - } - async fn update( - pool: &mut DbPool<'_>, - password_reset_request_id: i32, - form: &PasswordResetRequestForm, - ) -> Result { - let conn = &mut get_conn(pool).await?; - diesel::update(password_reset_request.find(password_reset_request_id)) - .set(form) - .get_result::(conn) - .await - } -} - impl PasswordResetRequest { - pub async fn create_token( + pub async fn create( pool: &mut DbPool<'_>, from_local_user_id: LocalUserId, token_: String, @@ -52,30 +25,21 @@ impl PasswordResetRequest { local_user_id: from_local_user_id, token: token_.into(), }; - - Self::create(pool, &form).await - } - pub async fn read_from_token(pool: &mut DbPool<'_>, token_: &str) -> Result, Error> { let conn = &mut get_conn(pool).await?; - password_reset_request + insert_into(password_reset_request) + .values(form) + .get_result::(conn) + .await + } + + pub async fn read_and_delete(pool: &mut DbPool<'_>, token_: &str) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + delete(password_reset_request) .filter(token.eq(token_)) .filter(published.gt(now.into_sql::() - 1.days())) - .first(conn) - .await - .optional() - } - - pub async fn get_recent_password_resets_count( - pool: &mut DbPool<'_>, - user_id: LocalUserId, - ) -> Result { - let conn = &mut get_conn(pool).await?; - password_reset_request - .filter(local_user_id.eq(user_id)) - .filter(published.gt(now.into_sql::() - 1.days())) - .count() .get_result(conn) .await + .optional() } } @@ -94,62 +58,64 @@ mod tests { traits::Crud, utils::build_db_pool_for_tests, }; + use lemmy_utils::error::LemmyResult; use pretty_assertions::assert_eq; use serial_test::serial; #[tokio::test] #[serial] - async fn test_crud() { + async fn test_password_reset() -> LemmyResult<()> { let pool = &build_db_pool_for_tests().await; let pool = &mut pool.into(); - let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) - .await - .unwrap(); - + // Setup + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?; let new_person = PersonInsertForm::builder() .name("thommy prw".into()) .public_key("pubkey".to_string()) .instance_id(inserted_instance.id) .build(); - - let inserted_person = Person::create(pool, &new_person).await.unwrap(); - + let inserted_person = Person::create(pool, &new_person).await?; let new_local_user = LocalUserInsertForm::builder() .person_id(inserted_person.id) .password_encrypted("pass".to_string()) .build(); + let inserted_local_user = LocalUser::create(pool, &new_local_user, vec![]).await?; - let inserted_local_user = LocalUser::create(pool, &new_local_user, vec![]) - .await - .unwrap(); - + // Create password reset token let token = "nope"; - let inserted_password_reset_request = - PasswordResetRequest::create_token(pool, inserted_local_user.id, token.to_string()) - .await - .unwrap(); + PasswordResetRequest::create(pool, inserted_local_user.id, token.to_string()).await?; - let expected_password_reset_request = PasswordResetRequest { - id: inserted_password_reset_request.id, - local_user_id: inserted_local_user.id, - token: token.to_string().into(), - published: inserted_password_reset_request.published, - }; - - let read_password_reset_request = PasswordResetRequest::read_from_token(pool, token) - .await - .unwrap() + // Read it and verify + let read_password_reset_request = PasswordResetRequest::read_and_delete(pool, token) + .await? .unwrap(); - let num_deleted = Person::delete(pool, inserted_person.id).await.unwrap(); - Instance::delete(pool, inserted_instance.id).await.unwrap(); - - assert_eq!(expected_password_reset_request, read_password_reset_request); assert_eq!( - expected_password_reset_request, - inserted_password_reset_request + inserted_password_reset_request.id, + read_password_reset_request.id ); + assert_eq!( + inserted_password_reset_request.local_user_id, + read_password_reset_request.local_user_id + ); + assert_eq!( + inserted_password_reset_request.token, + read_password_reset_request.token + ); + assert_eq!( + inserted_password_reset_request.published, + read_password_reset_request.published + ); + + // Cannot reuse same token again + let read_password_reset_request = PasswordResetRequest::read_and_delete(pool, token).await?; + assert!(read_password_reset_request.is_none()); + + // Cleanup + let num_deleted = Person::delete(pool, inserted_person.id).await?; + Instance::delete(pool, inserted_instance.id).await?; assert_eq!(1, num_deleted); + Ok(()) } } diff --git a/crates/utils/src/error.rs b/crates/utils/src/error.rs index 79d37cd08..53fba7c9e 100644 --- a/crates/utils/src/error.rs +++ b/crates/utils/src/error.rs @@ -161,7 +161,6 @@ pub enum LemmyErrorType { PermissiveRegex, InvalidRegex, CaptchaIncorrect, - PasswordResetLimitReached, CouldntCreateAudioCaptcha, InvalidUrlScheme, CouldntSendWebmention, diff --git a/src/api_routes_http.rs b/src/api_routes_http.rs index 6bfe0d727..1702ceb2a 100644 --- a/src/api_routes_http.rs +++ b/src/api_routes_http.rs @@ -278,6 +278,11 @@ pub fn config(cfg: &mut web::ServiceConfig, rate_limit: &RateLimitCell) { .wrap(rate_limit.register()) .route(web::post().to(login)), ) + .service( + web::resource("/user/password_reset") + .wrap(rate_limit.register()) + .route(web::post().to(reset_password)), + ) .service( // Handle captcha separately web::resource("/user/get_captcha") @@ -318,7 +323,6 @@ pub fn config(cfg: &mut web::ServiceConfig, rate_limit: &RateLimitCell) { // TODO Account actions. I don't like that they're in /user maybe /accounts .route("/logout", web::post().to(logout)) .route("/delete_account", web::post().to(delete_account)) - .route("/password_reset", web::post().to(reset_password)) .route( "/password_change", web::post().to(change_password_after_reset),