From e0de13bab6c6e5bc4a5f79fe34160a0dc1381ccc Mon Sep 17 00:00:00 2001 From: Muharem Hrnjadovic Date: Wed, 25 Nov 2026 10:37:03 +0300 Subject: [PATCH 1/2] Add database-backed password-reset guess and email limits (#1486) Password-reset email codes previously had no durable guess budget, and reset initiation had no per-account email cap that survives restarts or holds across enclave processes: the process-local limiters in web/rate_limit.rs reset on restart and each replica kept its own allowance. Both limits now live in PostgreSQL, coordinated through the reset request rows themselves: - Guess budget: a failed_attempts counter on every reset request (user and platform). A wrong code charges the durable budget of the unconsumed requests carrying the submitted reset-secret hash, so a random secret cannot burn anyone else's budget; a correct code with the matching secret never charges. The budget is checked before the code is examined, so an exhausted request stays closed even to the correct code, mirroring the process-local limiter. - Email cap: creation counts the account's request rows inside a rolling hour under the user-row lock (the same serialization the credential-mutation flows use), and past the cap creates no request row and sends no email. Every response stays byte-identical to the ordinary generic initiation answer, preserving account-enumeration protections for unknown, OAuth-only, throttled and valid accounts. Both apply to legacy user confirmation, Transport V2 options and completion through the shared proof verifier, and platform/developer reset initiation and verification. The process-local limiters remain as cheap first-line guardrails. Coverage adds cross-process sharing across separate app states, concurrent wrong guesses and concurrent initiation over separate pooled connections, and the rolling-window boundary. --- .../down.sql | 8 + .../up.sql | 20 ++ .../opensecret/src/aead_db_tamper_tests.rs | 290 ++++++++++++++++++ services/opensecret/src/db.rs | 123 +++++++- services/opensecret/src/main.rs | 176 ++++++++--- .../opensecret/src/models/password_reset.rs | 139 +++++++++ .../src/models/platform_password_reset.rs | 93 ++++++ services/opensecret/src/models/schema.rs | 2 + services/opensecret/src/web/rate_limit.rs | 7 + 9 files changed, 820 insertions(+), 38 deletions(-) create mode 100644 services/opensecret/migrations/2026-11-25-000000_password_reset_durable_limits/down.sql create mode 100644 services/opensecret/migrations/2026-11-25-000000_password_reset_durable_limits/up.sql diff --git a/services/opensecret/migrations/2026-11-25-000000_password_reset_durable_limits/down.sql b/services/opensecret/migrations/2026-11-25-000000_password_reset_durable_limits/down.sql new file mode 100644 index 000000000..181dc80b4 --- /dev/null +++ b/services/opensecret/migrations/2026-11-25-000000_password_reset_durable_limits/down.sql @@ -0,0 +1,8 @@ +DROP INDEX idx_password_reset_requests_user_id_created_at; +DROP INDEX idx_platform_password_reset_requests_user_id_created_at; + +ALTER TABLE platform_password_reset_requests + DROP COLUMN failed_attempts; + +ALTER TABLE password_reset_requests + DROP COLUMN failed_attempts; diff --git a/services/opensecret/migrations/2026-11-25-000000_password_reset_durable_limits/up.sql b/services/opensecret/migrations/2026-11-25-000000_password_reset_durable_limits/up.sql new file mode 100644 index 000000000..3ecb8cb34 --- /dev/null +++ b/services/opensecret/migrations/2026-11-25-000000_password_reset_durable_limits/up.sql @@ -0,0 +1,20 @@ +-- Durable, database-backed limits for the password-reset email codes +-- (issue #1486). One failed-attempt counter per reset request row makes the +-- guess budget cross-process: charging is a guarded UPDATE scoped to the +-- request's own secret, so nobody can spend a budget belonging to a request +-- they did not start. The email cap is the per-account count of unconsumed +-- requests created inside the rolling hour; the creation transaction refuses +-- to add a row once the cap is reached, and every created request row means +-- exactly one sent email. +ALTER TABLE password_reset_requests + ADD COLUMN failed_attempts INTEGER NOT NULL DEFAULT 0; + +ALTER TABLE platform_password_reset_requests + ADD COLUMN failed_attempts INTEGER NOT NULL DEFAULT 0; + +-- The rolling-hour email cap counts a account's recent request rows. +CREATE INDEX idx_password_reset_requests_user_id_created_at + ON password_reset_requests(user_id, created_at); + +CREATE INDEX idx_platform_password_reset_requests_user_id_created_at + ON platform_password_reset_requests(platform_user_id, created_at); diff --git a/services/opensecret/src/aead_db_tamper_tests.rs b/services/opensecret/src/aead_db_tamper_tests.rs index b1e1fb9e3..f2ae2aade 100644 --- a/services/opensecret/src/aead_db_tamper_tests.rs +++ b/services/opensecret/src/aead_db_tamper_tests.rs @@ -3447,4 +3447,294 @@ mod password_reset_limits { delete_platform_user(&app_state, &user); } + + /// The durable guess budget coordinates separate processes: two app + /// states over one database share the per-request counter, so a burst + /// split across replicas cannot exceed it, and the exhausted request + /// stays closed to whichever process receives the next attempt. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + #[ignore = "requires AEAD_TAMPER_TEST_DATABASE_URL pointing at disposable migrated local Postgres"] + async fn db_reset_guess_budget_is_shared_across_separate_app_states() { + let database_url = + std::env::var("AEAD_TAMPER_TEST_DATABASE_URL").expect("disposable migrated Postgres"); + let first = Arc::new(build_local_test_app_state(database_url.clone()).await); + let second = Arc::new(build_local_test_app_state(database_url).await); + let project = first_active_project(&first); + let user = create_user(&first, &project, "shared-guess").await; + let email = user.email.clone().expect("test user has an email"); + let new_password = test_credential("shared-guess-new"); + + let secret = "shared-guess-secret".to_string(); + let code = first + .create_password_reset_request( + email.clone(), + generate_reset_hash(secret.clone()), + project.id, + ) + .await + .unwrap(); + + // Alternate the process (app state) per wrong guess: the durable + // counter, not any process-local bucket, must hold the budget. + for attempt in 0..5 { + let app_state = if attempt % 2 == 0 { &first } else { &second }; + let result = app_state + .confirm_password_reset( + email.clone(), + wrong_code(&code), + secret.clone(), + new_password.to_string(), + project.id, + ) + .await; + assert!(matches!(result, Err(Error::InvalidPasswordResetRequest))); + } + + // Both processes see the request as closed, even to the right code. + for app_state in [&first, &second] { + let result = app_state + .confirm_password_reset( + email.clone(), + code.clone(), + secret.clone(), + new_password.to_string(), + project.id, + ) + .await; + assert!( + matches!( + result, + Err(Error::RateLimited(ApiError::RateLimited { .. })) + ), + "an exhausted request must stay closed on every process" + ); + } + assert!(!password_opens_account(&first, &project, &user, new_password).await); + + first.db.delete_user(&user).unwrap(); + } + + /// Concurrent wrong guesses over separate pooled connections cannot + /// push the durable counter past its cap: the guarded charge fails + /// closed exactly at the boundary. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "requires AEAD_TAMPER_TEST_DATABASE_URL pointing at disposable migrated local Postgres"] + async fn db_concurrent_wrong_guesses_cannot_exceed_the_request_budget() { + let database_url = + std::env::var("AEAD_TAMPER_TEST_DATABASE_URL").expect("disposable migrated Postgres"); + let app_state = Arc::new(build_local_test_app_state(database_url).await); + let project = first_active_project(&app_state); + let user = create_user(&app_state, &project, "concurrent-guess").await; + let email = user.email.clone().expect("test user has an email"); + let new_password = test_credential("concurrent-guess-new"); + + let secret = "concurrent-guess-secret".to_string(); + let code = app_state + .create_password_reset_request( + email.clone(), + generate_reset_hash(secret.clone()), + project.id, + ) + .await + .unwrap(); + let request_id = { + use crate::models::schema::password_reset_requests; + let conn = &mut app_state + .db + .get_pool() + .get() + .expect("test database connection should be available"); + password_reset_requests::table + .filter(password_reset_requests::user_id.eq(user.uuid)) + .filter( + password_reset_requests::hashed_secret.eq(generate_reset_hash(secret.clone())), + ) + .order(password_reset_requests::id.desc()) + .select(password_reset_requests::id) + .first::(conn) + .expect("the just-created request should load") + }; + + // Far more parallel wrong guesses than the budget allows. The proof + // check is synchronous Diesel work, so plain OS threads overlap the + // separate pooled connections. + let attempts = 20; + std::thread::scope(|scope| { + let state = &app_state; + for _ in 0..attempts { + let email = email.clone(); + let code = code.clone(); + let secret = secret.clone(); + scope.spawn(move || { + let outcome = state + .verify_password_reset_proof(email, wrong_code(&code), secret, project.id) + .expect_err("every concurrent guess must fail"); + assert!( + matches!( + outcome, + Error::InvalidPasswordResetRequest + | Error::RateLimited(ApiError::RateLimited { .. }) + ), + "a wrong guess is refused or rate-limited, never accepted: {outcome:?}" + ); + }); + } + }); + + let stored = { + use crate::models::schema::password_reset_requests; + let conn = &mut app_state + .db + .get_pool() + .get() + .expect("test database connection should be available"); + password_reset_requests::table + .find(request_id) + .select(password_reset_requests::failed_attempts) + .first::(conn) + .expect("the request row should load") + }; + assert!( + stored <= crate::models::password_reset::PASSWORD_RESET_MAX_FAILED_ATTEMPTS, + "the durable counter must never exceed its cap, got {stored}" + ); + + // Whatever the interleaving, the request is now closed: the next + // attempt with the correct code is refused. + let result = app_state + .confirm_password_reset( + email.clone(), + code.clone(), + secret.clone(), + new_password.to_string(), + project.id, + ) + .await; + assert!(matches!( + result, + Err(Error::RateLimited(ApiError::RateLimited { .. })) + | Err(Error::InvalidPasswordResetRequest) + )); + assert!(!password_opens_account(&app_state, &project, &user, new_password).await); + + app_state.db.delete_user(&user).unwrap(); + } + + /// Concurrent reset initiation over separate pooled connections cannot + /// create more request rows than the rolling-hour email cap allows. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "requires AEAD_TAMPER_TEST_DATABASE_URL pointing at disposable migrated local Postgres"] + async fn db_concurrent_reset_initiation_cannot_exceed_the_email_cap() { + let database_url = + std::env::var("AEAD_TAMPER_TEST_DATABASE_URL").expect("disposable migrated Postgres"); + let app_state = Arc::new(build_local_test_app_state(database_url).await); + let project = first_active_project(&app_state); + let user = create_user(&app_state, &project, "concurrent-cap").await; + let email = user.email.clone().expect("test user has an email"); + + // Far more parallel initiations than the cap allows, each with its + // own secret, all through the async app-state creation path. Each + // worker owns a minimal runtime, so the initiations truly overlap. + let initiations = 12; + std::thread::scope(|scope| { + let state = &app_state; + for attempt in 0..initiations { + let email = email.clone(); + scope.spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("initiation worker runtime should start"); + runtime.block_on(async move { + let _ = state + .create_password_reset_request( + email, + generate_reset_hash(format!("concurrent-cap-{attempt}")), + project.id, + ) + .await; + }); + }); + } + }); + + let created = unconsumed_reset_requests(&app_state, &user); + assert!( + created <= crate::models::password_reset::PASSWORD_RESET_REQUESTS_PER_HOUR, + "the durable email cap bounds concurrent creation, got {created}" + ); + + app_state.db.delete_user(&user).unwrap(); + } + + /// The rolling email window frees budget only when an hour has passed: + /// rows outside the window do not count, even while they remain + /// unconsumed. Uses direct model calls so the clock can be moved by + /// backdating rows, without touching deployed clock behavior. + #[tokio::test] + #[ignore = "requires AEAD_TAMPER_TEST_DATABASE_URL pointing at disposable migrated local Postgres"] + async fn db_reset_email_cap_counts_only_rows_inside_the_rolling_hour() { + let database_url = + std::env::var("AEAD_TAMPER_TEST_DATABASE_URL").expect("disposable migrated Postgres"); + let app_state = Arc::new(build_local_test_app_state(database_url).await); + let project = first_active_project(&app_state); + let user = create_user(&app_state, &project, "window").await; + let email = user.email.clone().expect("test user has an email"); + + // Create up to the cap, then backdate every row outside the window. + for attempt in 0..5 { + let _ = app_state + .create_password_reset_request( + email.clone(), + generate_reset_hash(format!("window-{attempt}")), + project.id, + ) + .await + .unwrap(); + } + let conn = &mut app_state + .db + .get_pool() + .get() + .expect("test database connection should be available"); + diesel::update(crate::models::schema::password_reset_requests::table) + .filter(crate::models::schema::password_reset_requests::user_id.eq(user.uuid)) + .set( + crate::models::schema::password_reset_requests::created_at + .eq(chrono::Utc::now() - chrono::Duration::seconds(61 * 60)), + ) + .execute(conn) + .expect("test rows should backdate"); + + // The rolling window sees none of the backdated rows: the budget is + // whole again, and a new request (and email) is allowed. + let _ = app_state + .create_password_reset_request( + email.clone(), + generate_reset_hash("window-fresh".to_string()), + project.id, + ) + .await + .unwrap(); + let created = { + use crate::models::schema::password_reset_requests; + let conn = &mut app_state + .db + .get_pool() + .get() + .expect("test database connection should be available"); + password_reset_requests::table + .filter(password_reset_requests::user_id.eq(user.uuid)) + .filter( + password_reset_requests::created_at + .gt(chrono::Utc::now() - chrono::Duration::seconds(60 * 60)), + ) + .count() + .get_result::(conn) + .expect("recent rows should be countable") + }; + assert_eq!(created, 1, "only the fresh row is inside the window"); + + app_state.db.delete_user(&user).unwrap(); + } } diff --git a/services/opensecret/src/db.rs b/services/opensecret/src/db.rs index c64b7c8f3..918d6e1bb 100644 --- a/services/opensecret/src/db.rs +++ b/services/opensecret/src/db.rs @@ -239,6 +239,28 @@ pub trait DBConnection { &self, new_request: NewPasswordResetRequest, ) -> Result; + /// Creates the request only while the account still has durable email + /// budget in the rolling hour. `Ok(None)` means the account is capped: + /// no request row and no reset email may be created. + fn create_password_reset_request_within_email_budget( + &self, + new_request: NewPasswordResetRequest, + ) -> Result, DBError>; + /// Atomically charges one failed email-code guess to the durable budget + /// of the account's unconsumed requests created with the secret. Fails + /// closed once every matching request's budget is exhausted. + fn charge_password_reset_attempt_for_secret( + &self, + user_id: Uuid, + hashed_secret: &str, + ) -> Result<(), DBError>; + /// The newest unconsumed request for the account created with the + /// secret: the request a completion through this secret would select. + fn get_password_reset_request_by_user_id_and_secret( + &self, + user_id: Uuid, + hashed_secret: &str, + ) -> Result, DBError>; fn get_password_reset_request_by_user_id_and_code( &self, user_id: Uuid, @@ -552,7 +574,20 @@ pub trait DBConnection { &self, new_request: NewPlatformPasswordResetRequest, ) -> Result; - + /// Platform mirror of + /// [`DBConnection::create_password_reset_request_within_email_budget`]. + fn create_platform_password_reset_request_within_email_budget( + &self, + new_request: NewPlatformPasswordResetRequest, + ) -> Result, DBError>; + /// Charges one failed guess to the durable budget of the account's active + /// request(s) created with `hashed_secret`. Fails closed once every + /// matching request's budget is exhausted. + fn charge_platform_password_reset_attempt_for_secret( + &self, + user_id: Uuid, + hashed_secret: &str, + ) -> Result<(), DBError>; fn get_platform_password_reset_request_by_user_id_and_code( &self, user_id: Uuid, @@ -1116,6 +1151,56 @@ impl DBConnection for PostgresConnection { result } + fn create_password_reset_request_within_email_budget( + &self, + new_request: NewPasswordResetRequest, + ) -> Result, DBError> { + let conn = &mut self.db.get().map_err(|_| DBError::ConnectionError)?; + let result = new_request + .insert_within_email_budget(conn) + .map_err(DBError::from); + if let Err(ref e) = result { + error!("Failed to create password reset request: {:?}", e); + } + result + } + + fn charge_password_reset_attempt_for_secret( + &self, + user_id: Uuid, + hashed_secret: &str, + ) -> Result<(), DBError> { + let conn = &mut self.db.get().map_err(|_| DBError::ConnectionError)?; + match PasswordResetRequest::charge_failed_attempt_for_secret(conn, user_id, hashed_secret) { + Ok(()) => Ok(()), + Err(PasswordResetError::AttemptBudgetExhausted) => { + Err(DBError::PasswordResetRequestNotFound) + } + Err(e) => { + error!("Failed to charge password reset attempt: {:?}", e); + Err(DBError::from(e)) + } + } + } + + fn get_password_reset_request_by_user_id_and_secret( + &self, + user_id: Uuid, + hashed_secret: &str, + ) -> Result, DBError> { + let conn = &mut self.db.get().map_err(|_| DBError::ConnectionError)?; + let result = PasswordResetRequest::newest_unconsumed_for_user_id_and_secret( + conn, + user_id, + hashed_secret, + ) + .map_err(DBError::from); + if let Err(ref e) = result { + error!("Failed to look up password reset request: {:?}", e); + } + result + } + fn get_password_reset_request_by_user_id_and_code( &self, user_id: Uuid, @@ -2344,6 +2429,42 @@ impl DBConnection for PostgresConnection { result } + fn create_platform_password_reset_request_within_email_budget( + &self, + new_request: NewPlatformPasswordResetRequest, + ) -> Result, DBError> { + let conn = &mut self.db.get().map_err(|_| DBError::ConnectionError)?; + let result = new_request + .insert_within_email_budget(conn) + .map_err(DBError::from); + if let Err(ref e) = result { + error!("Failed to create platform password reset request: {:?}", e); + } + result + } + + fn charge_platform_password_reset_attempt_for_secret( + &self, + user_id: Uuid, + hashed_secret: &str, + ) -> Result<(), DBError> { + let conn = &mut self.db.get().map_err(|_| DBError::ConnectionError)?; + match PlatformPasswordResetRequest::charge_failed_attempt_for_secret( + conn, + user_id, + hashed_secret, + ) { + Ok(()) => Ok(()), + Err(PlatformPasswordResetError::AttemptBudgetExhausted) => { + Err(DBError::PlatformPasswordResetRequestNotFound) + } + Err(e) => { + error!("Failed to charge platform password reset attempt: {:?}", e); + Err(DBError::from(e)) + } + } + } + fn get_platform_password_reset_request_by_user_id_and_code( &self, user_id: Uuid, diff --git a/services/opensecret/src/main.rs b/services/opensecret/src/main.rs index 2cc030780..8d81267fb 100644 --- a/services/opensecret/src/main.rs +++ b/services/opensecret/src/main.rs @@ -2142,7 +2142,10 @@ impl AppState { // Only password-backed users can use the password reset flow. OAuth-only // users recover by signing in with their linked OAuth provider. if user.get_email().is_some() && user.password_enc.is_some() { - // User exists, proceed with the actual reset request + // User exists, proceed with the actual reset request. + // The durable per-account email budget decides whether a + // new request (and so a new email) may exist at all; + // past the cap nothing is created or sent. let reset_code_mac = password_reset_code_mac( &self.enclave_key, project_id, @@ -2158,20 +2161,35 @@ impl AppState { 24, // 24 hours expiration ); - self.db.create_password_reset_request(new_request)?; - - // Send the actual email in the background - let app_state = self.clone(); - let user_email = email.clone(); - let code = alphanumeric_code.clone(); - tokio::spawn(async move { - if let Err(e) = - send_password_reset_email(&app_state, project_id, user_email, code) + match self + .db + .create_password_reset_request_within_email_budget(new_request) + { + Ok(Some(_)) => { + // Send the actual email in the background; the + // request row exists, so the budget was spent. + let app_state = self.clone(); + let user_email = email.clone(); + let code = alphanumeric_code.clone(); + tokio::spawn(async move { + if let Err(e) = send_password_reset_email( + &app_state, project_id, user_email, code, + ) .await - { - error!("Failed to send password reset email: {:?}", e); + { + error!("Failed to send password reset email: {:?}", e); + } + }); } - }); + Ok(None) => { + // Throttled: the account is at its rolling-hour + // email cap, so no request and no email. + debug!("Password reset email cap reached for existing account"); + } + Err(e) => { + error!("Error during password reset request: {:?}", e); + } + } } } Err(DBError::UserNotFound) => { @@ -2220,8 +2238,11 @@ impl AppState { /// the v2 options route: the alphanumeric code must MAC to an active, /// unexpired reset request for the addressed user, and the client reset /// secret must match the stored hash. Valid proofs spend no guess budget - /// and leave the request unchanged. Failed proofs charge only a budget - /// belonging to the submitted account and client secret. + /// and leave the request unchanged. Failed proofs charge the request's + /// durable database budget: the counter lives on the request row, so the + /// limit holds across enclave processes and restarts, and the guarded + /// charge matches the request's own secret, so nobody else can spend its + /// attempts. fn verify_password_reset_proof( &self, email: String, @@ -2243,12 +2264,30 @@ impl AppState { { return Err(Error::InvalidPasswordResetRequest); } - let attempt_key = web::rate_limit::Key::scoped(user.uuid, &[hashed_plaintext.as_bytes()]); let attempts = &self.rate_limits.password_reset_attempt; + let attempt_key = web::rate_limit::Key::scoped(user.uuid, &[hashed_plaintext.as_bytes()]); + // Process-local guardrail first: it cheaply sheds most of a burst + // before any database work. attempts .check_available(attempt_key) .map_err(Error::RateLimited)?; + // The durable budget closes the request once its attempts are spent, + // even to the correct code: check it on the request this secret would + // select, before any code is examined, mirroring the process-local + // limiter. + let budget_request = self + .db + .get_password_reset_request_by_user_id_and_secret(user.uuid, &hashed_plaintext)?; + match &budget_request { + Some(request) if !request.is_expired() && !request.has_attempt_budget() => { + return Err(Error::RateLimited(ApiError::RateLimited { + retry_after: web::rate_limit::reset_request_retry_after(), + })); + } + _ => {} + } + // MAC the provided alphanumeric code for lookup, bound to this user/project. let reset_code_mac = password_reset_code_mac(&self.enclave_key, project_id, user.uuid, &alphanumeric_code) @@ -2257,20 +2296,40 @@ impl AppState { let reset_request = self .db .get_password_reset_request_by_user_id_and_code(user.uuid, reset_code_mac.to_vec())?; - let failure = match reset_request { - Some(request) if request.is_expired() => Error::PasswordResetExpired, + let failure = match &reset_request { + Some(request) if request.is_expired() => { + // Expired requests keep their spent budget but charge + // nothing: the expiry itself has already ended guessing. + Error::PasswordResetExpired + } Some(request) => { if hashed_plaintext .as_bytes() .ct_eq(request.hashed_secret.as_bytes()) .into() { - return Ok((user, request)); + // A correct code with the matching secret proves the + // request owner: never charge the budget. + return Ok((user, request.clone())); } + // Correct code, wrong secret for this request: refused + // without charging, so an attacker who guesses the code + // cannot burn the owner's budget. Error::InvalidPasswordResetSecret } None => Error::InvalidPasswordResetRequest, }; + // A wrong code against the request this secret belongs to: charge + // the durable per-secret budget before reporting the failure. Once + // the budget is spent, the charge itself fails closed, which maps to + // the generic rate-limited response. + self.db + .charge_password_reset_attempt_for_secret(user.uuid, &hashed_plaintext) + .map_err(|_| { + Error::RateLimited(ApiError::RateLimited { + retry_after: web::rate_limit::reset_request_retry_after(), + }) + })?; attempts.check(attempt_key).map_err(Error::RateLimited)?; Err(failure) } @@ -2494,25 +2553,39 @@ impl AppState { } }; - self.db - .create_platform_password_reset_request(new_request)?; - - // Send the actual email in the background - let app_state = self.clone(); - let user_email = email.clone(); - let code = alphanumeric_code.clone(); - spawn(async move { - if let Err(e) = send_platform_password_reset_email( - &app_state, - app_state.resend_api_key.clone(), - user_email, - code, - ) - .await - { - error!("Failed to send platform password reset email: {:?}", e); + // The durable per-account email budget decides whether a + // new request (and so a new email) may exist at all. + match self + .db + .create_platform_password_reset_request_within_email_budget(new_request) + { + Ok(Some(_)) => { + // Send the actual email in the background + let app_state = self.clone(); + let user_email = email.clone(); + let code = alphanumeric_code.clone(); + spawn(async move { + if let Err(e) = send_platform_password_reset_email( + &app_state, + app_state.resend_api_key.clone(), + user_email, + code, + ) + .await + { + error!("Failed to send platform password reset email: {:?}", e); + } + }); } - }); + Ok(None) => { + debug!( + "Platform password reset email cap reached for existing account" + ); + } + Err(e) => { + return Err(Error::DatabaseError(e)); + } + } } } Ok(None) => { @@ -2567,6 +2640,17 @@ impl AppState { encrypted_code, )?; + // The durable budget closes the request once its attempts are spent, + // even to the correct code: check it before the code is examined, + // mirroring the user-side proof and the process-local limiter. + if let Some(ref request) = reset_request { + if !request.is_expired() && !request.has_attempt_budget() { + return Err(Error::RateLimited(ApiError::RateLimited { + retry_after: web::rate_limit::reset_request_retry_after(), + })); + } + } + if let Some(reset_request) = reset_request { if reset_request.is_expired() { warn!( @@ -2618,6 +2702,9 @@ impl AppState { Ok(()) } else { + // Correct code, wrong secret for this request: refused + // without charging, so a code guess cannot burn the owner's + // durable budget. warn!( "Password verification failed for platform user {}. Hashes do not match.", platform_user.uuid @@ -2625,6 +2712,21 @@ impl AppState { Err(Error::InvalidPasswordResetSecret) } } else { + // No live request for this code: a wrong code against the request + // this secret belongs to, so charge the durable per-request + // budget before reporting the failure. The platform lookup + // filters active requests by code; the secret was proven to + // belong to at least one active request above. + self.db + .charge_platform_password_reset_attempt_for_secret( + platform_user.uuid, + &hashed_plaintext, + ) + .map_err(|_| { + Error::RateLimited(ApiError::RateLimited { + retry_after: web::rate_limit::reset_request_retry_after(), + }) + })?; Err(Error::InvalidPasswordResetRequest) } } diff --git a/services/opensecret/src/models/password_reset.rs b/services/opensecret/src/models/password_reset.rs index b4e7f9bcf..c64755852 100644 --- a/services/opensecret/src/models/password_reset.rs +++ b/services/opensecret/src/models/password_reset.rs @@ -9,8 +9,21 @@ use uuid::Uuid; pub enum PasswordResetError { #[error("Database error: {0}")] DatabaseError(#[from] diesel::result::Error), + #[error("No attempt budget left for this reset request")] + AttemptBudgetExhausted, } +/// Durable per-request guess budget shared by every process that reaches the +/// database: at most this many incorrect email-code guesses per request. +pub const PASSWORD_RESET_MAX_FAILED_ATTEMPTS: i32 = 5; + +/// Durable per-account email cap: at most this many reset requests (and so +/// reset emails) created inside the rolling hour below. +pub const PASSWORD_RESET_REQUESTS_PER_HOUR: i64 = 5; + +/// Length of the rolling window the per-account email cap counts over. +pub const PASSWORD_RESET_EMAIL_WINDOW_SECONDS: i64 = 60 * 60; + #[derive(Queryable, Identifiable, AsChangeset, Serialize, Deserialize, Clone, Debug)] #[diesel(table_name = password_reset_requests)] pub struct PasswordResetRequest { @@ -21,6 +34,7 @@ pub struct PasswordResetRequest { pub expiration_time: DateTime, pub created_at: DateTime, pub is_reset: bool, + pub failed_attempts: i32, } impl PasswordResetRequest { @@ -72,6 +86,81 @@ impl PasswordResetRequest { pub fn is_expired(&self) -> bool { Utc::now() > self.expiration_time } + + /// Charges one failed guess to the durable budget of the account's + /// unconsumed requests created with `hashed_secret`. + /// + /// Used when the submitted code matched no request: the secret has + /// already been proven to belong to at least one unconsumed request (the + /// admission check), so the wrong code is charged to that request's + /// owner. The guarded `UPDATE` matches only rows carrying that secret, so + /// nobody without the secret can spend this budget, and an unrelated + /// secret cannot burn anyone else's. + pub fn charge_failed_attempt_for_secret( + conn: &mut PgConnection, + lookup_user_id: Uuid, + lookup_hashed_secret: &str, + ) -> Result<(), PasswordResetError> { + let charged = diesel::update( + password_reset_requests::table + .filter(password_reset_requests::user_id.eq(lookup_user_id)) + .filter(password_reset_requests::hashed_secret.eq(lookup_hashed_secret)) + .filter(password_reset_requests::is_reset.eq(false)) + .filter( + password_reset_requests::failed_attempts.lt(PASSWORD_RESET_MAX_FAILED_ATTEMPTS), + ), + ) + .set( + password_reset_requests::failed_attempts + .eq(password_reset_requests::failed_attempts + 1), + ) + .execute(conn)?; + if charged == 0 { + return Err(PasswordResetError::AttemptBudgetExhausted); + } + Ok(()) + } + + /// The newest unconsumed request for the account created with + /// `hashed_secret`, if any: the request a completion through this + /// secret would select. Expiry is left to the caller. + pub fn newest_unconsumed_for_user_id_and_secret( + conn: &mut PgConnection, + lookup_user_id: Uuid, + lookup_hashed_secret: &str, + ) -> Result, PasswordResetError> { + password_reset_requests::table + .filter(password_reset_requests::user_id.eq(lookup_user_id)) + .filter(password_reset_requests::hashed_secret.eq(lookup_hashed_secret)) + .filter(password_reset_requests::is_reset.eq(false)) + .order(password_reset_requests::id.desc()) + .first::(conn) + .optional() + .map_err(PasswordResetError::DatabaseError) + } + + /// Whether this request still has unused guess budget. A read-only view + /// of the same durable counter `charge_failed_attempt` spends. + pub fn has_attempt_budget(&self) -> bool { + self.failed_attempts < PASSWORD_RESET_MAX_FAILED_ATTEMPTS + } + + /// Count of this account's reset requests created inside the rolling + /// email window. Every request row means one sent email, so this count is + /// the durable per-account email budget already spent. + pub fn count_recent_requests_for_user( + conn: &mut PgConnection, + lookup_user_id: Uuid, + ) -> Result { + let window_start = + Utc::now() - chrono::Duration::seconds(PASSWORD_RESET_EMAIL_WINDOW_SECONDS); + password_reset_requests::table + .filter(password_reset_requests::user_id.eq(lookup_user_id)) + .filter(password_reset_requests::created_at.gt(window_start)) + .count() + .get_result(conn) + .map_err(PasswordResetError::DatabaseError) + } } #[derive(Insertable)] @@ -98,6 +187,56 @@ impl NewPasswordResetRequest { } } + /// Inserts the request only while the account still has email budget in + /// the rolling hour. The user-row lock serializes competing creations + /// for the same account before the count, so concurrent processes + /// cannot exceed the cap together. Returns the inserted request, or + /// `None` when the account is capped and no row (and so no email) may + /// be created. + pub fn insert_within_email_budget( + &self, + conn: &mut PgConnection, + ) -> Result, PasswordResetError> { + use crate::models::schema::users; + conn.transaction::<_, PasswordResetError, _>(|conn| { + // Serialize creations for this account the same way the + // credential-mutation flows do: through the user row. + let locked = users::table + .filter(users::uuid.eq(self.user_id)) + .select(users::uuid) + .for_update() + .first::(conn) + .optional()?; + if locked.is_none() { + // The account vanished between the eligibility check and + // this insert; nothing may be created for it. + return Ok(None); + } + let recent = Self::recent_request_count(conn, self.user_id)?; + if recent >= PASSWORD_RESET_REQUESTS_PER_HOUR { + return Ok(None); + } + let inserted = diesel::insert_into(password_reset_requests::table) + .values(self) + .get_result::(conn)?; + Ok(Some(inserted)) + }) + } + + fn recent_request_count( + conn: &mut PgConnection, + lookup_user_id: Uuid, + ) -> Result { + let window_start = + Utc::now() - chrono::Duration::seconds(PASSWORD_RESET_EMAIL_WINDOW_SECONDS); + password_reset_requests::table + .filter(password_reset_requests::user_id.eq(lookup_user_id)) + .filter(password_reset_requests::created_at.gt(window_start)) + .count() + .get_result(conn) + .map_err(PasswordResetError::DatabaseError) + } + pub fn insert( &self, conn: &mut PgConnection, diff --git a/services/opensecret/src/models/platform_password_reset.rs b/services/opensecret/src/models/platform_password_reset.rs index 5b1c0a87b..789d44fd0 100644 --- a/services/opensecret/src/models/platform_password_reset.rs +++ b/services/opensecret/src/models/platform_password_reset.rs @@ -11,8 +11,20 @@ pub enum PlatformPasswordResetError { DatabaseError(#[from] diesel::result::Error), #[error("Invalid expiration hours: {0}")] InvalidExpirationHours(String), + #[error("No attempt budget left for this reset request")] + AttemptBudgetExhausted, } +/// Durable per-request guess budget for platform (developer) accounts, +/// matching the user-account budget in `models/password_reset.rs`. +pub const PLATFORM_PASSWORD_RESET_MAX_FAILED_ATTEMPTS: i32 = 5; + +/// Durable per-account email cap for platform (developer) accounts. +pub const PLATFORM_PASSWORD_RESET_REQUESTS_PER_HOUR: i64 = 5; + +/// Length of the rolling window the platform email cap counts over. +pub const PLATFORM_PASSWORD_RESET_EMAIL_WINDOW_SECONDS: i64 = 60 * 60; + #[derive(Queryable, Identifiable, AsChangeset, Serialize, Deserialize, Clone, Debug)] #[diesel(table_name = platform_password_reset_requests)] pub struct PlatformPasswordResetRequest { @@ -24,6 +36,7 @@ pub struct PlatformPasswordResetRequest { pub created_at: DateTime, pub updated_at: DateTime, pub is_reset: bool, + pub failed_attempts: i32, } impl PlatformPasswordResetRequest { @@ -73,6 +86,46 @@ impl PlatformPasswordResetRequest { pub fn is_expired(&self) -> bool { Utc::now() > self.expiration_time } + + /// Whether this request still has unused guess budget. + pub fn has_attempt_budget(&self) -> bool { + self.failed_attempts < PLATFORM_PASSWORD_RESET_MAX_FAILED_ATTEMPTS + } + + /// Charges one failed guess to the durable budget of the account's oldest + /// active request created with `hashed_secret`. + /// + /// Used when the submitted code matched no request: the secret has + /// already been proven to belong to at least one active request (the + /// admission check), so the wrong code is charged to that request's + /// owner. The guarded `UPDATE` matches only rows carrying that secret, + /// so nobody without the secret can spend this budget. + pub fn charge_failed_attempt_for_secret( + conn: &mut PgConnection, + lookup_user_id: Uuid, + lookup_hashed_secret: &str, + ) -> Result<(), PlatformPasswordResetError> { + let charged = diesel::update( + platform_password_reset_requests::table + .filter(platform_password_reset_requests::platform_user_id.eq(lookup_user_id)) + .filter(platform_password_reset_requests::hashed_secret.eq(lookup_hashed_secret)) + .filter(platform_password_reset_requests::is_reset.eq(false)) + .filter(platform_password_reset_requests::expiration_time.gt(Utc::now())) + .filter( + platform_password_reset_requests::failed_attempts + .lt(PLATFORM_PASSWORD_RESET_MAX_FAILED_ATTEMPTS), + ), + ) + .set( + platform_password_reset_requests::failed_attempts + .eq(platform_password_reset_requests::failed_attempts + 1), + ) + .execute(conn)?; + if charged == 0 { + return Err(PlatformPasswordResetError::AttemptBudgetExhausted); + } + Ok(()) + } } #[derive(Insertable)] @@ -105,6 +158,46 @@ impl NewPlatformPasswordResetRequest { }) } + /// Inserts the request only while the platform account still has email + /// budget in the rolling hour, the platform mirror of + /// [`NewPasswordResetRequest::insert_within_email_budget`]. The + /// platform-user-row lock serializes competing creations for the same + /// account before the count. Returns `None` when the account is capped: + /// no row and no email may be created. + pub fn insert_within_email_budget( + &self, + conn: &mut PgConnection, + ) -> Result, PlatformPasswordResetError> { + use crate::models::schema::platform_users; + conn.transaction::<_, PlatformPasswordResetError, _>(|conn| { + let locked = platform_users::table + .filter(platform_users::uuid.eq(self.platform_user_id)) + .select(platform_users::uuid) + .for_update() + .first::(conn) + .optional()?; + if locked.is_none() { + return Ok(None); + } + let window_start = Utc::now() + - chrono::Duration::seconds(PLATFORM_PASSWORD_RESET_EMAIL_WINDOW_SECONDS); + let recent: i64 = platform_password_reset_requests::table + .filter( + platform_password_reset_requests::platform_user_id.eq(self.platform_user_id), + ) + .filter(platform_password_reset_requests::created_at.gt(window_start)) + .count() + .get_result(conn)?; + if recent >= PLATFORM_PASSWORD_RESET_REQUESTS_PER_HOUR { + return Ok(None); + } + let inserted = diesel::insert_into(platform_password_reset_requests::table) + .values(self) + .get_result::(conn)?; + Ok(Some(inserted)) + }) + } + pub fn insert( &self, conn: &mut PgConnection, diff --git a/services/opensecret/src/models/schema.rs b/services/opensecret/src/models/schema.rs index 51082b322..d91595b9b 100644 --- a/services/opensecret/src/models/schema.rs +++ b/services/opensecret/src/models/schema.rs @@ -315,6 +315,7 @@ diesel::table! { expiration_time -> Timestamptz, created_at -> Timestamptz, is_reset -> Bool, + failed_attempts -> Int4, } } @@ -348,6 +349,7 @@ diesel::table! { created_at -> Timestamptz, updated_at -> Timestamptz, is_reset -> Bool, + failed_attempts -> Int4, } } diff --git a/services/opensecret/src/web/rate_limit.rs b/services/opensecret/src/web/rate_limit.rs index f8b6193e7..eb3bfe5d9 100644 --- a/services/opensecret/src/web/rate_limit.rs +++ b/services/opensecret/src/web/rate_limit.rs @@ -261,6 +261,13 @@ pub(crate) struct RateLimits { pub(crate) platform_password_reset_attempt: Arc, } +/// `Retry-After` reported when a reset request's durable guess budget is +/// exhausted: one request lifetime, because the per-request budget never +/// refills while that request lives. +pub(crate) fn reset_request_retry_after() -> std::time::Duration { + PASSWORD_RESET_REQUEST_LIFETIME +} + impl RateLimits { pub(crate) fn from_env() -> Result { let rpm = setting("INFERENCE_RATE_LIMIT_RPM", DEFAULT_INFERENCE_RPM, 1_000)?; From 7e6d03f7a2f7fcfbb7550d4c6e99c51a437b5f54 Mon Sep 17 00:00:00 2001 From: Muharem Hrnjadovic Date: Wed, 25 Nov 2026 11:17:07 +0300 Subject: [PATCH 2/2] Bind the durable reset budget to the code-selected request; narrow 429s and expiry charges Review fixes on PR #1684: - The guess budget is now checked on the request the submitted code selects, not on the newest request sharing the secret: a spent request stays closed even to its correct code, and a same-secret sibling can neither reopen it nor be shielded by it. Wrong-code guesses still charge the shared per-(account, secret) budget, per the #1486 charging spec, with a regression covering several open requests sharing one secret. - Only a genuinely spent budget maps to the rate-limited response on both the user and platform paths; any other database failure propagates as an infrastructure error instead of a 24-hour 429. - Expired user requests are never charged: expiry returns before the charge, the guarded UPDATE filters to active rows, and a secret whose requests have all expired reports the failure without charging (new NoActivePasswordResetRequest distinction). Expiry coverage added. - The concurrent-initiation test now asserts the exact cap and that every initiation call itself succeeded, so a no-op path cannot pass. --- .../opensecret/src/aead_db_tamper_tests.rs | 269 +++++++++++++++++- services/opensecret/src/db.rs | 30 +- services/opensecret/src/main.rs | 73 ++--- .../opensecret/src/models/password_reset.rs | 76 +++-- 4 files changed, 345 insertions(+), 103 deletions(-) diff --git a/services/opensecret/src/aead_db_tamper_tests.rs b/services/opensecret/src/aead_db_tamper_tests.rs index f2ae2aade..2282126bd 100644 --- a/services/opensecret/src/aead_db_tamper_tests.rs +++ b/services/opensecret/src/aead_db_tamper_tests.rs @@ -3636,8 +3636,10 @@ mod password_reset_limits { // own secret, all through the async app-state creation path. Each // worker owns a minimal runtime, so the initiations truly overlap. let initiations = 12; + let outcomes = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); std::thread::scope(|scope| { let state = &app_state; + let outcomes = &outcomes; for attempt in 0..initiations { let email = email.clone(); scope.spawn(move || { @@ -3646,22 +3648,34 @@ mod password_reset_limits { .build() .expect("initiation worker runtime should start"); runtime.block_on(async move { - let _ = state + if state .create_password_reset_request( email, generate_reset_hash(format!("concurrent-cap-{attempt}")), project.id, ) - .await; + .await + .is_ok() + { + outcomes.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } }); }); } }); + // Exactly the cap: creation is bounded from below as well as above, + // so the test fails on a path that creates nothing. + let cap = crate::models::password_reset::PASSWORD_RESET_REQUESTS_PER_HOUR; let created = unconsumed_reset_requests(&app_state, &user); - assert!( - created <= crate::models::password_reset::PASSWORD_RESET_REQUESTS_PER_HOUR, - "the durable email cap bounds concurrent creation, got {created}" + assert_eq!( + created, cap, + "concurrent creation must reach and not exceed the durable email cap" + ); + assert_eq!( + outcomes.load(std::sync::atomic::Ordering::Relaxed), + initiations as usize, + "every initiation call itself succeeds; the cap refuses to create rows" ); app_state.db.delete_user(&user).unwrap(); @@ -3737,4 +3751,249 @@ mod password_reset_limits { app_state.db.delete_user(&user).unwrap(); } + + /// The durable budget binds to the request the submitted code selects, + /// not to any other request sharing the secret: a spent request stays + /// closed even when a fresher request with the same secret exists, and a + /// fresh request never shields a spent one from its own exhaustion. + #[tokio::test] + #[ignore = "requires AEAD_TAMPER_TEST_DATABASE_URL pointing at disposable migrated local Postgres"] + async fn db_reset_budget_binds_to_the_code_selected_request_not_the_secret() { + let database_url = + std::env::var("AEAD_TAMPER_TEST_DATABASE_URL").expect("disposable migrated Postgres"); + let app_state = Arc::new(build_local_test_app_state(database_url).await); + let project = first_active_project(&app_state); + let user = create_user(&app_state, &project, "code-bound").await; + let email = user.email.clone().expect("test user has an email"); + let new_password = test_credential("code-bound-new"); + + // Two requests created with the same secret but different codes. + let secret = "code-bound-shared-secret".to_string(); + let first_code = app_state + .create_password_reset_request( + email.clone(), + generate_reset_hash(secret.clone()), + project.id, + ) + .await + .unwrap(); + let second_code = app_state + .create_password_reset_request( + email.clone(), + generate_reset_hash(secret.clone()), + project.id, + ) + .await + .unwrap(); + assert_ne!(first_code, second_code); + + // Spend the first request's budget with wrong codes. + for _ in 0..5 { + let result = app_state + .confirm_password_reset( + email.clone(), + wrong_code(&first_code), + secret.clone(), + new_password.to_string(), + project.id, + ) + .await; + assert!(matches!(result, Err(Error::InvalidPasswordResetRequest))); + } + + // The spent request stays closed to its correct code, even though a + // fresher request shares the secret and still has its whole budget. + let result = app_state + .confirm_password_reset( + email.clone(), + first_code.clone(), + secret.clone(), + new_password.to_string(), + project.id, + ) + .await; + assert!( + matches!( + result, + Err(Error::RateLimited(ApiError::RateLimited { .. })) + ), + "a spent request must stay closed; a same-secret sibling cannot reopen it" + ); + assert!(!password_opens_account(&app_state, &project, &user, new_password).await); + + // Wrong-code guesses charge the shared per-secret budget (#1486 + // charges every active request whose reset-secret hash matches the + // submitted secret), so the same-secret sibling has spent it too and + // stays closed to its own correct code. + let result = app_state + .confirm_password_reset( + email.clone(), + second_code, + secret, + new_password.to_string(), + project.id, + ) + .await; + assert!( + matches!( + result, + Err(Error::RateLimited(ApiError::RateLimited { .. })) + ), + "wrong-code guesses charge the shared per-secret budget, so the sibling is spent too" + ); + assert!(!password_opens_account(&app_state, &project, &user, new_password).await); + + // A request created with a different secret keeps its own budget and + // still completes. + let fresh_secret = "code-bound-fresh-secret".to_string(); + let fresh_code = app_state + .create_password_reset_request( + email.clone(), + generate_reset_hash(fresh_secret.clone()), + project.id, + ) + .await + .unwrap(); + app_state + .confirm_password_reset( + email, + fresh_code, + fresh_secret, + new_password.to_string(), + project.id, + ) + .await + .expect("a different-secret request must still complete the reset"); + assert!(password_opens_account(&app_state, &project, &user, new_password).await); + + app_state.db.delete_user(&user).unwrap(); + } + + /// Expired requests never charge and never spend a sibling's budget: a + /// correct code for an expired request reports expiry, a wrong code + /// leaves every expired row's counter untouched, and an active sibling + /// still completes afterwards. + #[tokio::test] + #[ignore = "requires AEAD_TAMPER_TEST_DATABASE_URL pointing at disposable migrated local Postgres"] + async fn db_expired_requests_report_expiry_without_charging_any_budget() { + let database_url = + std::env::var("AEAD_TAMPER_TEST_DATABASE_URL").expect("disposable migrated Postgres"); + let app_state = Arc::new(build_local_test_app_state(database_url).await); + let project = first_active_project(&app_state); + let user = create_user(&app_state, &project, "expired").await; + let email = user.email.clone().expect("test user has an email"); + let new_password = test_credential("expired-new"); + + let expired_secret = "expired-secret".to_string(); + let expired_code = app_state + .create_password_reset_request( + email.clone(), + generate_reset_hash(expired_secret.clone()), + project.id, + ) + .await + .unwrap(); + // Backdate the row past its expiration without touching the clock. + { + use crate::models::schema::password_reset_requests; + let conn = &mut app_state + .db + .get_pool() + .get() + .expect("test database connection should be available"); + diesel::update(password_reset_requests::table) + .filter(password_reset_requests::user_id.eq(user.uuid)) + .filter( + password_reset_requests::hashed_secret + .eq(generate_reset_hash(expired_secret.clone())), + ) + .set( + password_reset_requests::expiration_time + .eq(chrono::Utc::now() - chrono::Duration::hours(1)), + ) + .execute(conn) + .expect("the expired fixture row should backdate"); + } + + // The correct code for the expired request reports expiry, never a + // budget response, and never charges. + let result = app_state.verify_password_reset_proof( + email.clone(), + expired_code.clone(), + expired_secret.clone(), + project.id, + ); + assert!( + matches!(result, Err(Error::PasswordResetExpired)), + "an expired request must report expiry, got {result:?}" + ); + + // A wrong code against the same secret is refused without charging: + // the expired row's counter must stay at zero. + let _ = app_state + .confirm_password_reset( + email.clone(), + wrong_code(&expired_code), + expired_secret.clone(), + new_password.to_string(), + project.id, + ) + .await; + let result = app_state.verify_password_reset_proof( + email.clone(), + wrong_code(&expired_code), + expired_secret, + project.id, + ); + assert!( + matches!(result, Err(Error::InvalidPasswordResetRequest)) + | matches!(result, Err(Error::PasswordResetExpired)), + "a wrong code against an expired request is refused, got {result:?}" + ); + let expired_attempts = { + use crate::models::schema::password_reset_requests; + let conn = &mut app_state + .db + .get_pool() + .get() + .expect("test database connection should be available"); + password_reset_requests::table + .filter(password_reset_requests::user_id.eq(user.uuid)) + .filter( + password_reset_requests::hashed_secret + .eq(generate_reset_hash("expired-secret".to_string())), + ) + .select(password_reset_requests::failed_attempts) + .first::(conn) + .expect("the expired row should load") + }; + assert_eq!( + expired_attempts, 0, + "an expired request must never be charged" + ); + + // An active sibling request still completes with its whole budget. + let active_secret = "expired-active-secret".to_string(); + let active_code = app_state + .create_password_reset_request( + email.clone(), + generate_reset_hash(active_secret.clone()), + project.id, + ) + .await + .unwrap(); + app_state + .confirm_password_reset( + email, + active_code, + active_secret, + new_password.to_string(), + project.id, + ) + .await + .expect("an active sibling must still complete after expired refusals"); + assert!(password_opens_account(&app_state, &project, &user, new_password).await); + + app_state.db.delete_user(&user).unwrap(); + } } diff --git a/services/opensecret/src/db.rs b/services/opensecret/src/db.rs index 918d6e1bb..c5eb0ed2b 100644 --- a/services/opensecret/src/db.rs +++ b/services/opensecret/src/db.rs @@ -247,20 +247,13 @@ pub trait DBConnection { new_request: NewPasswordResetRequest, ) -> Result, DBError>; /// Atomically charges one failed email-code guess to the durable budget - /// of the account's unconsumed requests created with the secret. Fails + /// of the account's active requests created with the secret. Fails /// closed once every matching request's budget is exhausted. fn charge_password_reset_attempt_for_secret( &self, user_id: Uuid, hashed_secret: &str, ) -> Result<(), DBError>; - /// The newest unconsumed request for the account created with the - /// secret: the request a completion through this secret would select. - fn get_password_reset_request_by_user_id_and_secret( - &self, - user_id: Uuid, - hashed_secret: &str, - ) -> Result, DBError>; fn get_password_reset_request_by_user_id_and_code( &self, user_id: Uuid, @@ -1176,6 +1169,9 @@ impl DBConnection for PostgresConnection { Err(PasswordResetError::AttemptBudgetExhausted) => { Err(DBError::PasswordResetRequestNotFound) } + Err(PasswordResetError::NoActivePasswordResetRequest) => Err( + DBError::PasswordResetError(PasswordResetError::NoActivePasswordResetRequest), + ), Err(e) => { error!("Failed to charge password reset attempt: {:?}", e); Err(DBError::from(e)) @@ -1183,24 +1179,6 @@ impl DBConnection for PostgresConnection { } } - fn get_password_reset_request_by_user_id_and_secret( - &self, - user_id: Uuid, - hashed_secret: &str, - ) -> Result, DBError> { - let conn = &mut self.db.get().map_err(|_| DBError::ConnectionError)?; - let result = PasswordResetRequest::newest_unconsumed_for_user_id_and_secret( - conn, - user_id, - hashed_secret, - ) - .map_err(DBError::from); - if let Err(ref e) = result { - error!("Failed to look up password reset request: {:?}", e); - } - result - } - fn get_password_reset_request_by_user_id_and_code( &self, user_id: Uuid, diff --git a/services/opensecret/src/main.rs b/services/opensecret/src/main.rs index 8d81267fb..fdac6a551 100644 --- a/services/opensecret/src/main.rs +++ b/services/opensecret/src/main.rs @@ -14,7 +14,9 @@ use crate::login_routes::RegisterCredentials; use crate::models::account_deletion::{AccountDeletionError, NewAccountDeletionRequest}; use crate::models::email_verification::{EmailVerificationError, NewEmailVerification}; use crate::models::oauth::{NewUserOAuthConnection, OAuthError}; -use crate::models::password_reset::{NewPasswordResetRequest, PasswordResetRequest}; +use crate::models::password_reset::{ + NewPasswordResetRequest, PasswordResetError, PasswordResetRequest, +}; use crate::models::platform_password_reset::NewPlatformPasswordResetRequest; use crate::models::platform_users::PlatformUser; use crate::sqs::SqsEventPublisher; @@ -2272,22 +2274,6 @@ impl AppState { .check_available(attempt_key) .map_err(Error::RateLimited)?; - // The durable budget closes the request once its attempts are spent, - // even to the correct code: check it on the request this secret would - // select, before any code is examined, mirroring the process-local - // limiter. - let budget_request = self - .db - .get_password_reset_request_by_user_id_and_secret(user.uuid, &hashed_plaintext)?; - match &budget_request { - Some(request) if !request.is_expired() && !request.has_attempt_budget() => { - return Err(Error::RateLimited(ApiError::RateLimited { - retry_after: web::rate_limit::reset_request_retry_after(), - })); - } - _ => {} - } - // MAC the provided alphanumeric code for lookup, bound to this user/project. let reset_code_mac = password_reset_code_mac(&self.enclave_key, project_id, user.uuid, &alphanumeric_code) @@ -2298,11 +2284,20 @@ impl AppState { .get_password_reset_request_by_user_id_and_code(user.uuid, reset_code_mac.to_vec())?; let failure = match &reset_request { Some(request) if request.is_expired() => { - // Expired requests keep their spent budget but charge + // Expired requests keep their spent budget and charge // nothing: the expiry itself has already ended guessing. - Error::PasswordResetExpired + return Err(Error::PasswordResetExpired); } Some(request) => { + // The durable budget is checked on the request this code + // selects, not on any other request sharing the secret: a + // spent request stays closed even to its correct code, and a + // fresh request sharing the secret cannot reopen it. + if !request.has_attempt_budget() { + return Err(Error::RateLimited(ApiError::RateLimited { + retry_after: web::rate_limit::reset_request_retry_after(), + })); + } if hashed_plaintext .as_bytes() .ct_eq(request.hashed_secret.as_bytes()) @@ -2320,16 +2315,25 @@ impl AppState { None => Error::InvalidPasswordResetRequest, }; // A wrong code against the request this secret belongs to: charge - // the durable per-secret budget before reporting the failure. Once - // the budget is spent, the charge itself fails closed, which maps to - // the generic rate-limited response. - self.db + // the durable per-secret budget before reporting the failure. Only a + // genuinely spent budget maps to the rate-limited response, and a + // secret whose requests have all expired reports the failure without + // charging; any other database failure stays an infrastructure error. + match self + .db .charge_password_reset_attempt_for_secret(user.uuid, &hashed_plaintext) - .map_err(|_| { - Error::RateLimited(ApiError::RateLimited { + { + Ok(()) => {} + Err(DBError::PasswordResetRequestNotFound) => { + return Err(Error::RateLimited(ApiError::RateLimited { retry_after: web::rate_limit::reset_request_retry_after(), - }) - })?; + })); + } + Err(DBError::PasswordResetError(PasswordResetError::NoActivePasswordResetRequest)) => { + return Err(failure) + } + Err(other) => return Err(Error::DatabaseError(other)), + } attempts.check(attempt_key).map_err(Error::RateLimited)?; Err(failure) } @@ -2716,16 +2720,21 @@ impl AppState { // this secret belongs to, so charge the durable per-request // budget before reporting the failure. The platform lookup // filters active requests by code; the secret was proven to - // belong to at least one active request above. + // belong to at least one active request above. Only a genuinely + // spent budget maps to the rate-limited response; any other + // database failure stays an infrastructure error. self.db .charge_platform_password_reset_attempt_for_secret( platform_user.uuid, &hashed_plaintext, ) - .map_err(|_| { - Error::RateLimited(ApiError::RateLimited { - retry_after: web::rate_limit::reset_request_retry_after(), - }) + .map_err(|e| match e { + DBError::PlatformPasswordResetRequestNotFound => { + Error::RateLimited(ApiError::RateLimited { + retry_after: web::rate_limit::reset_request_retry_after(), + }) + } + other => Error::DatabaseError(other), })?; Err(Error::InvalidPasswordResetRequest) } diff --git a/services/opensecret/src/models/password_reset.rs b/services/opensecret/src/models/password_reset.rs index c64755852..f1ef81609 100644 --- a/services/opensecret/src/models/password_reset.rs +++ b/services/opensecret/src/models/password_reset.rs @@ -11,6 +11,8 @@ pub enum PasswordResetError { DatabaseError(#[from] diesel::result::Error), #[error("No attempt budget left for this reset request")] AttemptBudgetExhausted, + #[error("No active reset request carries this secret")] + NoActivePasswordResetRequest, } /// Durable per-request guess budget shared by every process that reaches the @@ -88,14 +90,15 @@ impl PasswordResetRequest { } /// Charges one failed guess to the durable budget of the account's - /// unconsumed requests created with `hashed_secret`. + /// active requests created with `hashed_secret`. /// /// Used when the submitted code matched no request: the secret has /// already been proven to belong to at least one unconsumed request (the /// admission check), so the wrong code is charged to that request's - /// owner. The guarded `UPDATE` matches only rows carrying that secret, so - /// nobody without the secret can spend this budget, and an unrelated - /// secret cannot burn anyone else's. + /// owner. The guarded `UPDATE` matches only active rows carrying that + /// secret, so nobody without the secret can spend this budget, an + /// unrelated secret cannot burn anyone else's, and expired requests keep + /// their spent budget without charging further. pub fn charge_failed_attempt_for_secret( conn: &mut PgConnection, lookup_user_id: Uuid, @@ -106,6 +109,13 @@ impl PasswordResetRequest { .filter(password_reset_requests::user_id.eq(lookup_user_id)) .filter(password_reset_requests::hashed_secret.eq(lookup_hashed_secret)) .filter(password_reset_requests::is_reset.eq(false)) + .filter( + password_reset_requests::expiration_time.gt(diesel::dsl::sql::< + diesel::sql_types::Timestamptz, + >( + "clock_timestamp()" + )), + ) .filter( password_reset_requests::failed_attempts.lt(PASSWORD_RESET_MAX_FAILED_ATTEMPTS), ), @@ -116,51 +126,37 @@ impl PasswordResetRequest { ) .execute(conn)?; if charged == 0 { + // Distinguish a spent budget from a secret whose requests have + // all left the active window: only the former is a budget + // failure the caller reports as rate-limited. + let any_active = diesel::select(diesel::dsl::exists( + password_reset_requests::table + .filter(password_reset_requests::user_id.eq(lookup_user_id)) + .filter(password_reset_requests::hashed_secret.eq(lookup_hashed_secret)) + .filter(password_reset_requests::is_reset.eq(false)) + .filter( + password_reset_requests::expiration_time.gt(diesel::dsl::sql::< + diesel::sql_types::Timestamptz, + >( + "clock_timestamp()" + )), + ), + )) + .get_result::(conn)?; + if !any_active { + return Err(PasswordResetError::NoActivePasswordResetRequest); + } return Err(PasswordResetError::AttemptBudgetExhausted); } Ok(()) } - /// The newest unconsumed request for the account created with - /// `hashed_secret`, if any: the request a completion through this - /// secret would select. Expiry is left to the caller. - pub fn newest_unconsumed_for_user_id_and_secret( - conn: &mut PgConnection, - lookup_user_id: Uuid, - lookup_hashed_secret: &str, - ) -> Result, PasswordResetError> { - password_reset_requests::table - .filter(password_reset_requests::user_id.eq(lookup_user_id)) - .filter(password_reset_requests::hashed_secret.eq(lookup_hashed_secret)) - .filter(password_reset_requests::is_reset.eq(false)) - .order(password_reset_requests::id.desc()) - .first::(conn) - .optional() - .map_err(PasswordResetError::DatabaseError) - } - /// Whether this request still has unused guess budget. A read-only view - /// of the same durable counter `charge_failed_attempt` spends. + /// of the same durable counter `charge_failed_attempt_for_secret` + /// spends. pub fn has_attempt_budget(&self) -> bool { self.failed_attempts < PASSWORD_RESET_MAX_FAILED_ATTEMPTS } - - /// Count of this account's reset requests created inside the rolling - /// email window. Every request row means one sent email, so this count is - /// the durable per-account email budget already spent. - pub fn count_recent_requests_for_user( - conn: &mut PgConnection, - lookup_user_id: Uuid, - ) -> Result { - let window_start = - Utc::now() - chrono::Duration::seconds(PASSWORD_RESET_EMAIL_WINDOW_SECONDS); - password_reset_requests::table - .filter(password_reset_requests::user_id.eq(lookup_user_id)) - .filter(password_reset_requests::created_at.gt(window_start)) - .count() - .get_result(conn) - .map_err(PasswordResetError::DatabaseError) - } } #[derive(Insertable)]