From e0de13bab6c6e5bc4a5f79fe34160a0dc1381ccc Mon Sep 17 00:00:00 2001 From: Muharem Hrnjadovic Date: Wed, 25 Nov 2026 10:37:03 +0300 Subject: [PATCH 1/3] 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/3] 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)] From 4308e4d1eea80ff867b11f7f746c7b74af4d5d89 Mon Sep 17 00:00:00 2001 From: Muharem Hrnjadovic Date: Sat, 28 Nov 2026 19:16:58 +0300 Subject: [PATCH 3/3] Serialize reset proof attempts per secret under row locks - Decide each user and platform reset proof in one transaction that locks the submitted secret's unconsumed requests, so concurrent guesses cannot read a stale budget before a correct proof is accepted. - Share one pure decision (`decide_proof_attempt`) between user and platform resets: a correct code with another request's secret is charged on both, and budget outcomes are an enum instead of overloaded errors. - Keep failed user proofs for an all-expired secret on the process-local limiter, and report a correct platform code for an expired request as expired instead of charging a sibling. - Fix the migration comment, the email-cap log line and the password-reset contract docs; tighten the concurrency test and add lock, expiry-throttle and platform charge tests. --- .../opensecret/docs/development-contracts.md | 59 ++-- .../up.sql | 14 +- .../opensecret/src/aead_db_tamper_tests.rs | 243 +++++++++++++++- services/opensecret/src/db.rs | 80 ++---- services/opensecret/src/main.rs | 214 +++++--------- .../opensecret/src/models/password_reset.rs | 268 ++++++++++++++---- .../src/models/platform_password_reset.rs | 77 +++-- .../opensecret/src/security_invariants.rs | 3 +- 8 files changed, 632 insertions(+), 326 deletions(-) diff --git a/services/opensecret/docs/development-contracts.md b/services/opensecret/docs/development-contracts.md index cca237ff8..319b7dce6 100644 --- a/services/opensecret/docs/development-contracts.md +++ b/services/opensecret/docs/development-contracts.md @@ -130,30 +130,45 @@ inputs, never in command arguments or logs. #### Password reset User (`/password-reset/*`) and platform (`/platform/password-reset/*`) accounts -have the same two limits, each with its own state. - -Reset requests are limited to 5 per targeted account in a rolling hour. Past -that, the request route returns its ordinary generic answer but creates no -request and sends no email, so a throttled, unknown, OAuth-only and valid -account stay indistinguishable. Because a request lives 24 hours, this also -bounds the reset codes that can be live for one account. Any caller can spend an -account's allowance; the cost to its owner is a delayed reset email, never a -changed credential. - -Each reset request allows 5 confirmation attempts for its whole 24-hour life. -The confirm route first matches the submitted secret to a request of that -account. A submission whose secret matches none cannot complete anything and is -refused without being counted. An exhausted budget returns a generic 429 even -with the right code. Only the party that started a request holds its secret, -so nobody else can spend its attempts; the owner of an exhausted request -starts a new one. +have the same two limits, each with its own tables. PostgreSQL holds both +limits, so they survive restarts and hold across enclave processes. The +process-local limiters in `web/rate_limit.rs` stay as a cheap first line. + +Reset requests are limited to 5 per targeted account in a rolling hour. Every +request row created in the hour counts, consumed or not. Creation locks the +account row, counts and inserts in one transaction, so concurrent processes +cannot exceed the cap together. Past that, the request route returns its +ordinary generic answer but creates no request and sends no email, so a +throttled, unknown, OAuth-only and valid account stay indistinguishable. +Because a request lives 24 hours, this also bounds the reset codes that can be +live for one account. Any caller can spend an account's allowance; the cost to +its owner is a delayed reset email, never a changed credential. + +Each reset request allows 5 failed confirmation attempts for its whole 24-hour +life, counted in its `failed_attempts` column. The confirm route first matches +the submitted secret to a request of that account. A submission whose secret +matches none cannot complete anything and is refused without being counted. +Each admitted attempt then runs in one transaction that locks every unconsumed +request carrying the submitted secret, so attempts that could succeed run one +at a time and always see current counters. In that transaction: + +- the request the code selects is refused as expired, or with a generic 429 + when its budget is spent, before its secret is compared, even with the right + code; +- a wrong code, or a correct code with another request's secret, charges every + active request carrying the submitted secret; when all of them are spent the + answer is the generic 429; +- expired requests are never charged. + +Only the party that started a request holds its secret, so nobody else can +spend its attempts; the owner of an exhausted request starts a new one. User reset proof verification is shared by legacy confirmation and V2 options -and completion. Failed proofs with a matching client secret spend the budget; -valid proofs check availability without spending it. Repeated valid options -checks and a later completion therefore work within the same budget. An -exhausted request returns the same generic 429 on all three paths, even with -the right code. Platform confirmation still counts every admitted attempt, +and completion. Valid proofs spend no budget, so repeated valid options checks +and a later completion work within the same budget. An exhausted request +returns the same generic 429 on all three paths, even with the right code. +Every failed user proof also spends the process-local budget. Platform +confirmation spends the process-local budget on every admitted attempt, including a correct one, since successful confirmation consumes its request. ### Responses context scope 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 index 3ecb8cb34..545df99bd 100644 --- 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 @@ -1,18 +1,18 @@ -- 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. +-- guess budget cross-process: a failed guess is charged, under row locks, to +-- the active requests carrying the submitted secret, so nobody can spend a +-- budget belonging to a request they did not start. The email cap is the +-- per-account count of all requests (consumed or not) 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. +-- The rolling-hour email cap counts an account's recent request rows. CREATE INDEX idx_password_reset_requests_user_id_created_at ON password_reset_requests(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 2282126bd..4ae9e1015 100644 --- a/services/opensecret/src/aead_db_tamper_tests.rs +++ b/services/opensecret/src/aead_db_tamper_tests.rs @@ -3559,8 +3559,10 @@ mod password_reset_limits { // check is synchronous Diesel work, so plain OS threads overlap the // separate pooled connections. let attempts = 20; + let refused = std::sync::atomic::AtomicUsize::new(0); std::thread::scope(|scope| { let state = &app_state; + let refused = &refused; for _ in 0..attempts { let email = email.clone(); let code = code.clone(); @@ -3569,14 +3571,13 @@ mod password_reset_limits { 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:?}" - ); + match outcome { + Error::InvalidPasswordResetRequest => { + refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + Error::RateLimited(ApiError::RateLimited { .. }) => {} + other => panic!("a wrong guess is refused or rate-limited: {other:?}"), + } }); } }); @@ -3594,9 +3595,17 @@ mod password_reset_limits { .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}" + let max = crate::models::password_reset::PASSWORD_RESET_MAX_FAILED_ATTEMPTS; + assert_eq!( + stored, max, + "the durable counter must stop exactly at its cap" + ); + // Attempts are serialized per secret, so exactly the budget's worth of + // guesses was examined; every other one was refused as exhausted. + assert_eq!( + refused.load(std::sync::atomic::Ordering::Relaxed), + max as usize, + "exactly the budget of concurrent guesses may be examined" ); // Whatever the interleaving, the request is now closed: the next @@ -3613,13 +3622,83 @@ mod password_reset_limits { 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(); } + /// A correct proof waits for an in-flight failed guess on the same + /// secret and sees its charge: it can never read a budget that a + /// concurrent guess is about to spend. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + #[ignore = "requires AEAD_TAMPER_TEST_DATABASE_URL pointing at disposable migrated local Postgres"] + async fn db_correct_proof_waits_for_an_in_flight_guess_on_the_same_secret() { + use crate::models::schema::password_reset_requests; + use diesel::Connection; + 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, "in-flight").await; + let email = user.email.clone().expect("test user has an email"); + let secret = "in-flight-secret".to_string(); + let hashed_secret = generate_reset_hash(secret.clone()); + let code = app_state + .create_password_reset_request(email.clone(), hashed_secret.clone(), project.id) + .await + .unwrap(); + let max = crate::models::password_reset::PASSWORD_RESET_MAX_FAILED_ATTEMPTS; + + let conn = &mut app_state + .db + .get_pool() + .get() + .expect("test database connection should be available"); + // One guess short of the cap. + diesel::update(password_reset_requests::table) + .filter(password_reset_requests::user_id.eq(user.uuid)) + .set(password_reset_requests::failed_attempts.eq(max - 1)) + .execute(conn) + .expect("the fixture counter should be set"); + + let proof = conn + .transaction::<_, diesel::result::Error, _>(|conn| { + // Stand in for a failed guess holding the secret's row locks. + password_reset_requests::table + .filter(password_reset_requests::user_id.eq(user.uuid)) + .filter(password_reset_requests::hashed_secret.eq(&hashed_secret)) + .select(password_reset_requests::id) + .for_update() + .load::(conn)?; + let state = app_state.clone(); + let (email, code, secret) = (email.clone(), code.clone(), secret.clone()); + let proof = std::thread::spawn(move || { + state.verify_password_reset_proof(email, code, secret, project.id) + }); + std::thread::sleep(std::time::Duration::from_millis(500)); + assert!( + !proof.is_finished(), + "the correct proof must wait for the in-flight guess" + ); + // The in-flight guess spends the last attempt and commits. + diesel::update(password_reset_requests::table) + .filter(password_reset_requests::user_id.eq(user.uuid)) + .set(password_reset_requests::failed_attempts.eq(max)) + .execute(conn)?; + Ok(proof) + }) + .expect("the in-flight guess should commit") + .join() + .expect("the proof thread should not panic"); + assert!( + matches!(proof, Err(Error::RateLimited(ApiError::RateLimited { .. }))), + "the correct proof must see the spent budget, got {proof:?}" + ); + + 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)] @@ -3996,4 +4075,144 @@ mod password_reset_limits { app_state.db.delete_user(&user).unwrap(); } + + /// A secret whose requests have all expired has no durable budget to + /// charge, so its failed guesses still spend the process-local budget + /// instead of running unthrottled. + #[tokio::test] + #[ignore = "requires AEAD_TAMPER_TEST_DATABASE_URL pointing at disposable migrated local Postgres"] + async fn db_failed_guesses_for_an_expired_secret_stay_throttled() { + use crate::models::schema::password_reset_requests; + 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-throttle").await; + let email = user.email.clone().expect("test user has an email"); + let secret = "expired-throttle-secret".to_string(); + let code = app_state + .create_password_reset_request( + email.clone(), + generate_reset_hash(secret.clone()), + project.id, + ) + .await + .unwrap(); + { + 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)) + .set( + password_reset_requests::expiration_time + .eq(chrono::Utc::now() - chrono::Duration::hours(1)), + ) + .execute(conn) + .expect("the fixture row should expire"); + } + + for _ in 0..5 { + let result = app_state.verify_password_reset_proof( + email.clone(), + wrong_code(&code), + secret.clone(), + project.id, + ); + assert!(matches!(result, Err(Error::InvalidPasswordResetRequest))); + } + let result = + app_state.verify_password_reset_proof(email, wrong_code(&code), secret, project.id); + assert!( + matches!( + result, + Err(Error::RateLimited(ApiError::RateLimited { .. })) + ), + "failed guesses for an expired secret must stay throttled, got {result:?}" + ); + + app_state.db.delete_user(&user).unwrap(); + } + + /// Platform confirmation reports a correct code for an expired request as + /// expired without charging a same-secret sibling, and charges a correct + /// code submitted with another request's secret to the submitted secret. + #[tokio::test] + #[ignore = "requires AEAD_TAMPER_TEST_DATABASE_URL pointing at disposable migrated local Postgres"] + async fn db_platform_expired_and_wrong_secret_proofs_charge_like_user_proofs() { + use crate::models::schema::platform_password_reset_requests as requests; + let app_state = test_app_state().await; + let user = create_platform_user(&app_state, "platform-expiry").await; + let new_password = test_credential("platform-expiry-new"); + let secret = "platform-expiry-secret".to_string(); + let other_secret = "platform-expiry-other-secret".to_string(); + let mut codes = Vec::new(); + for hashed in [&secret, &secret, &other_secret] { + codes.push( + app_state + .create_platform_password_reset_request( + user.email.clone(), + generate_reset_hash(hashed.clone()), + ) + .await + .unwrap(), + ); + } + let conn = &mut app_state + .db + .get_pool() + .get() + .expect("test database connection should be available"); + let ids: Vec = requests::table + .filter(requests::platform_user_id.eq(user.uuid)) + .order(requests::id.asc()) + .select(requests::id) + .load(conn) + .expect("the fixture rows should load"); + diesel::update(requests::table.find(ids[0])) + .set(requests::expiration_time.eq(chrono::Utc::now() - chrono::Duration::hours(1))) + .execute(conn) + .expect("the first fixture row should expire"); + let attempts = |conn: &mut diesel::PgConnection| -> Vec { + requests::table + .filter(requests::platform_user_id.eq(user.uuid)) + .order(requests::id.asc()) + .select(requests::failed_attempts) + .load(conn) + .expect("the counters should load") + }; + + let result = app_state + .confirm_platform_password_reset( + user.email.clone(), + codes[0].clone(), + secret.clone(), + new_password.to_string(), + ) + .await; + assert!( + matches!(result, Err(Error::PasswordResetExpired)), + "an expired request must report expiry, got {result:?}" + ); + assert_eq!(attempts(conn), vec![0, 0, 0], "expiry charges nothing"); + + let result = app_state + .confirm_platform_password_reset( + user.email.clone(), + codes[2].clone(), + secret, + new_password.to_string(), + ) + .await; + assert!(matches!(result, Err(Error::InvalidPasswordResetSecret))); + assert_eq!( + attempts(conn), + vec![0, 1, 0], + "a wrong secret charges only the submitted secret's active request" + ); + + delete_platform_user(&app_state, &user); + } } diff --git a/services/opensecret/src/db.rs b/services/opensecret/src/db.rs index c5eb0ed2b..26a285e34 100644 --- a/services/opensecret/src/db.rs +++ b/services/opensecret/src/db.rs @@ -17,7 +17,7 @@ use crate::models::org_project_secrets::{ use crate::models::org_projects::{NewOrgProject, OrgProject, OrgProjectError}; use crate::models::orgs::{NewOrg, Org, OrgError}; use crate::models::password_reset::{ - NewPasswordResetRequest, PasswordResetError, PasswordResetRequest, + NewPasswordResetRequest, PasswordResetError, PasswordResetRequest, ResetProofAttempt, }; use crate::models::platform_email_verification::{ NewPlatformEmailVerification, PlatformEmailVerification, PlatformEmailVerificationError, @@ -246,14 +246,14 @@ pub trait DBConnection { &self, new_request: NewPasswordResetRequest, ) -> Result, DBError>; - /// Atomically charges one failed email-code guess to the durable budget - /// 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( + /// Decides one reset proof attempt against the durable guess budget and + /// charges a failed guess, serialized per reset secret. + fn attempt_password_reset_proof( &self, user_id: Uuid, hashed_secret: &str, - ) -> Result<(), DBError>; + encrypted_code: Vec, + ) -> Result, DBError>; fn get_password_reset_request_by_user_id_and_code( &self, user_id: Uuid, @@ -573,19 +573,13 @@ pub trait DBConnection { &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( + /// Platform mirror of [`DBConnection::attempt_password_reset_proof`]. + fn attempt_platform_password_reset_proof( &self, user_id: Uuid, hashed_secret: &str, - ) -> Result<(), DBError>; - fn get_platform_password_reset_request_by_user_id_and_code( - &self, - user_id: Uuid, encrypted_code: Vec, - ) -> Result, DBError>; + ) -> Result, DBError>; fn platform_password_reset_request_is_active_for_secret( &self, @@ -1158,25 +1152,20 @@ impl DBConnection for PostgresConnection { result } - fn charge_password_reset_attempt_for_secret( + fn attempt_password_reset_proof( &self, user_id: Uuid, hashed_secret: &str, - ) -> Result<(), DBError> { + encrypted_code: Vec, + ) -> 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(PasswordResetError::NoActivePasswordResetRequest) => Err( - DBError::PasswordResetError(PasswordResetError::NoActivePasswordResetRequest), - ), - Err(e) => { - error!("Failed to charge password reset attempt: {:?}", e); - Err(DBError::from(e)) - } + let result = + PasswordResetRequest::attempt_proof(conn, user_id, hashed_secret, &encrypted_code) + .map_err(DBError::from); + if let Err(ref e) = result { + error!("Failed to check password reset proof: {:?}", e); } + result } fn get_password_reset_request_by_user_id_and_code( @@ -2421,39 +2410,22 @@ impl DBConnection for PostgresConnection { result } - fn charge_platform_password_reset_attempt_for_secret( + fn attempt_platform_password_reset_proof( &self, user_id: Uuid, hashed_secret: &str, - ) -> Result<(), DBError> { + encrypted_code: Vec, + ) -> Result, DBError> { let conn = &mut self.db.get().map_err(|_| DBError::ConnectionError)?; - match PlatformPasswordResetRequest::charge_failed_attempt_for_secret( + let result = PlatformPasswordResetRequest::attempt_proof( 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, - encrypted_code: Vec, - ) -> Result, DBError> { - let conn = &mut self.db.get().map_err(|_| DBError::ConnectionError)?; - let result = - PlatformPasswordResetRequest::get_by_user_id_and_code(conn, user_id, &encrypted_code) - .map_err(DBError::from); + &encrypted_code, + ) + .map_err(DBError::from); if let Err(ref e) = result { - error!("Failed to get platform password reset request: {:?}", e); + error!("Failed to check platform password reset proof: {:?}", e); } result } diff --git a/services/opensecret/src/main.rs b/services/opensecret/src/main.rs index fdac6a551..e99167fa5 100644 --- a/services/opensecret/src/main.rs +++ b/services/opensecret/src/main.rs @@ -15,7 +15,7 @@ use crate::models::account_deletion::{AccountDeletionError, NewAccountDeletionRe use crate::models::email_verification::{EmailVerificationError, NewEmailVerification}; use crate::models::oauth::{NewUserOAuthConnection, OAuthError}; use crate::models::password_reset::{ - NewPasswordResetRequest, PasswordResetError, PasswordResetRequest, + NewPasswordResetRequest, PasswordResetRequest, ResetProofAttempt, }; use crate::models::platform_password_reset::NewPlatformPasswordResetRequest; use crate::models::platform_users::PlatformUser; @@ -2186,7 +2186,7 @@ impl AppState { 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"); + debug!("No password reset request created: email cap reached or account removed"); } Err(e) => { error!("Error during password reset request: {:?}", e); @@ -2242,8 +2242,8 @@ impl AppState { /// secret must match the stored hash. Valid proofs spend no guess budget /// 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 + /// limit holds across enclave processes and restarts, and the charge is + /// scoped to the submitted secret, so nobody without it can spend its /// attempts. fn verify_password_reset_proof( &self, @@ -2279,61 +2279,26 @@ impl AppState { password_reset_code_mac(&self.enclave_key, project_id, user.uuid, &alphanumeric_code) .map_err(|e| Error::EncryptionError(e.to_string()))?; - 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() => { - // Expired requests keep their spent budget and charge - // nothing: the expiry itself has already ended guessing. - 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()) - .into() - { - // 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. 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) - { - Ok(()) => {} - Err(DBError::PasswordResetRequestNotFound) => { + // The budget check, the code and secret comparison, and the charge + // of a failed guess run in one transaction serialized per secret. + let failure = match self.db.attempt_password_reset_proof( + user.uuid, + &hashed_plaintext, + reset_code_mac.to_vec(), + )? { + ResetProofAttempt::Valid(request) => return Ok((user, request)), + ResetProofAttempt::Exhausted => { 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)), - } + ResetProofAttempt::Expired => Error::PasswordResetExpired, + ResetProofAttempt::WrongSecret => Error::InvalidPasswordResetSecret, + ResetProofAttempt::WrongCode => Error::InvalidPasswordResetRequest, + }; + // Every failure also spends the process-local budget, including a + // secret whose requests have all expired and so has no durable + // budget left to charge. attempts.check(attempt_key).map_err(Error::RateLimited)?; Err(failure) } @@ -2583,7 +2548,7 @@ impl AppState { } Ok(None) => { debug!( - "Platform password reset email cap reached for existing account" + "No platform password reset request created: email cap reached or account removed" ); } Err(e) => { @@ -2637,107 +2602,70 @@ impl AppState { .map_err(|e| Error::EncryptionError(e.to_string()))?; let encrypted_code = encrypt_key_deterministic(&secret_key, alphanumeric_code.as_bytes()); - let reset_request = self - .db - .get_platform_password_reset_request_by_user_id_and_code( - platform_user.uuid, - 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() { + // The budget check, the code and secret comparison, and the charge + // of a failed guess run in one transaction serialized per secret. + let reset_request = match self.db.attempt_platform_password_reset_proof( + platform_user.uuid, + &hashed_plaintext, + encrypted_code, + )? { + ResetProofAttempt::Valid(request) => request, + ResetProofAttempt::Exhausted => { 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() { + ResetProofAttempt::Expired => { warn!( "Platform password reset expired for user: {}", platform_user.uuid ); return Err(Error::PasswordResetExpired); } + ResetProofAttempt::WrongSecret => { + warn!( + "Password verification failed for platform user {}. Hashes do not match.", + platform_user.uuid + ); + return Err(Error::InvalidPasswordResetSecret); + } + ResetProofAttempt::WrongCode => return Err(Error::InvalidPasswordResetRequest), + }; - // Compare the hashed values using constant-time comparison - if hashed_plaintext - .as_bytes() - .ct_eq(reset_request.hashed_secret.as_bytes()) - .into() - { - // Password verification succeeded, continue with reset - // Hash the new password - let password_hash = password_auth::generate_hash(new_password.clone()); - - // Encrypt the hashed password - let secret_key = SecretKey::from_slice(&self.enclave_key) - .map_err(|e| Error::EncryptionError(e.to_string()))?; - let encrypted_password = - encrypt_with_key(&secret_key, password_hash.as_bytes()).await; + // Password verification succeeded, continue with reset + // Hash the new password + let password_hash = password_auth::generate_hash(new_password.clone()); - // Update the platform user's password - self.db - .update_platform_user_password(&platform_user, encrypted_password)?; - self.db - .mark_platform_password_reset_as_complete(&reset_request)?; + // Encrypt the hashed password + let secret_key = SecretKey::from_slice(&self.enclave_key) + .map_err(|e| Error::EncryptionError(e.to_string()))?; + let encrypted_password = encrypt_with_key(&secret_key, password_hash.as_bytes()).await; - // Send confirmation email in the background - let user_email = platform_user.email.clone(); - let app_state = self.clone(); - spawn(async move { - if let Err(e) = send_platform_password_reset_confirmation_email( - &app_state, - app_state.resend_api_key.clone(), - user_email, - ) - .await - { - error!( - "Failed to send platform password reset confirmation email: {:?}", - e - ); - } - }); + // Update the platform user's password + self.db + .update_platform_user_password(&platform_user, encrypted_password)?; + self.db + .mark_platform_password_reset_as_complete(&reset_request)?; - 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 + // Send confirmation email in the background + let user_email = platform_user.email.clone(); + let app_state = self.clone(); + spawn(async move { + if let Err(e) = send_platform_password_reset_confirmation_email( + &app_state, + app_state.resend_api_key.clone(), + user_email, + ) + .await + { + error!( + "Failed to send platform password reset confirmation email: {:?}", + e ); - 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. 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(|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) - } + }); + + Ok(()) } async fn update_user_password_and_seed_wrap( diff --git a/services/opensecret/src/models/password_reset.rs b/services/opensecret/src/models/password_reset.rs index f1ef81609..470119e25 100644 --- a/services/opensecret/src/models/password_reset.rs +++ b/services/opensecret/src/models/password_reset.rs @@ -2,6 +2,7 @@ use crate::models::schema::password_reset_requests; use chrono::{DateTime, Utc}; use diesel::prelude::*; use serde::{Deserialize, Serialize}; +use subtle::ConstantTimeEq; use thiserror::Error; use uuid::Uuid; @@ -9,10 +10,6 @@ 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, - #[error("No active reset request carries this secret")] - NoActivePasswordResetRequest, } /// Durable per-request guess budget shared by every process that reaches the @@ -89,76 +86,136 @@ impl PasswordResetRequest { Utc::now() > self.expiration_time } - /// Charges one failed guess to the durable budget of the account's - /// active requests created with `hashed_secret`. + /// Decides one reset proof attempt for the code-selected request and + /// charges a failed guess, all inside one transaction. /// - /// 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 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( + /// Every unconsumed request created with `lookup_hashed_secret` is + /// locked first. Only those requests can ever be completed by this + /// secret, so every attempt that could succeed queues on the same row + /// locks and sees the charges of the attempts before it: concurrent + /// guesses cannot read a stale budget. See [`decide_proof_attempt`]. + pub fn attempt_proof( conn: &mut PgConnection, lookup_user_id: Uuid, lookup_hashed_secret: &str, - ) -> Result<(), PasswordResetError> { - let charged = diesel::update( - password_reset_requests::table + lookup_encrypted_code: &[u8], + ) -> Result, PasswordResetError> { + conn.transaction(|conn| { + let secret_requests = 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()" - )), + .order(password_reset_requests::id.asc()) + .for_update() + .load::(conn)?; + let selected = + Self::get_by_user_id_and_code(conn, lookup_user_id, lookup_encrypted_code)?; + let (attempt, charge) = + decide_proof_attempt(&secret_requests, selected, lookup_hashed_secret); + if !charge.is_empty() { + diesel::update( + password_reset_requests::table + .filter(password_reset_requests::id.eq_any(charge)), ) - .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 { - // 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); + .set( + password_reset_requests::failed_attempts + .eq(password_reset_requests::failed_attempts + 1), + ) + .execute(conn)?; } - return Err(PasswordResetError::AttemptBudgetExhausted); - } - Ok(()) + Ok(attempt) + }) } - /// Whether this request still has unused guess budget. A read-only view - /// of the same durable counter `charge_failed_attempt_for_secret` - /// spends. + /// Whether this request still has unused guess budget. pub fn has_attempt_budget(&self) -> bool { self.failed_attempts < PASSWORD_RESET_MAX_FAILED_ATTEMPTS } } +impl ResetRequestRow for PasswordResetRequest { + fn row_id(&self) -> i32 { + self.id + } + fn row_hashed_secret(&self) -> &str { + &self.hashed_secret + } + fn expired(&self) -> bool { + self.is_expired() + } + fn has_budget(&self) -> bool { + self.has_attempt_budget() + } +} + +/// Outcome of one reset proof attempt, shared by user and platform resets. +#[derive(Debug)] +pub enum ResetProofAttempt { + /// Correct code and secret for an active request with budget left. + Valid(R), + /// The code selects an expired request; nothing was charged. + Expired, + /// The code-selected request, or every active request carrying the + /// submitted secret, has spent its budget. + Exhausted, + /// The code selects another secret's request; the guess was charged. + WrongSecret, + /// The code selects no request; the guess was charged. + WrongCode, +} + +/// The fields the shared proof decision reads from either reset table. +pub(crate) trait ResetRequestRow { + fn row_id(&self) -> i32; + fn row_hashed_secret(&self) -> &str; + fn expired(&self) -> bool; + fn has_budget(&self) -> bool; +} + +/// Decides a proof attempt from the locked rows carrying the submitted +/// secret and the row the submitted code selects. Returns the outcome and +/// the ids of the rows a failed guess charges. +/// +/// The code-selected row's budget is checked before its secret is compared, +/// so a spent request stays closed even to its correct proof. Any failed +/// guess (wrong code, or correct code with a wrong secret) charges every +/// active row carrying the submitted secret, so nobody without that secret +/// can spend its budget. Expired rows are never charged; a secret with no +/// active row left has nothing durable to charge. +pub(crate) fn decide_proof_attempt( + secret_rows: &[R], + selected: Option, + submitted_hashed_secret: &str, +) -> (ResetProofAttempt, Vec) { + let failure = match selected { + Some(row) if row.expired() => return (ResetProofAttempt::Expired, Vec::new()), + Some(row) if !row.has_budget() => return (ResetProofAttempt::Exhausted, Vec::new()), + Some(row) + if bool::from( + submitted_hashed_secret + .as_bytes() + .ct_eq(row.row_hashed_secret().as_bytes()), + ) => + { + return (ResetProofAttempt::Valid(row), Vec::new()) + } + Some(_) => ResetProofAttempt::WrongSecret, + None => ResetProofAttempt::WrongCode, + }; + let mut any_active = false; + let mut charge = Vec::new(); + for row in secret_rows.iter().filter(|row| !row.expired()) { + any_active = true; + if row.has_budget() { + charge.push(row.row_id()); + } + } + if any_active && charge.is_empty() { + return (ResetProofAttempt::Exhausted, Vec::new()); + } + (failure, charge) +} + #[derive(Insertable)] #[diesel(table_name = password_reset_requests)] pub struct NewPasswordResetRequest { @@ -243,3 +300,98 @@ impl NewPasswordResetRequest { .map_err(PasswordResetError::DatabaseError) } } + +#[cfg(test)] +mod tests { + use super::{decide_proof_attempt, ResetProofAttempt, ResetRequestRow}; + + #[derive(Debug, Clone)] + struct Row { + id: i32, + secret: &'static str, + expired: bool, + budget: bool, + } + + impl ResetRequestRow for Row { + fn row_id(&self) -> i32 { + self.id + } + fn row_hashed_secret(&self) -> &str { + self.secret + } + fn expired(&self) -> bool { + self.expired + } + fn has_budget(&self) -> bool { + self.budget + } + } + + fn row(id: i32, secret: &'static str, expired: bool, budget: bool) -> Row { + Row { + id, + secret, + expired, + budget, + } + } + + #[test] + fn valid_proof_is_accepted_without_charging() { + let rows = [row(1, "s", false, true)]; + let (attempt, charge) = decide_proof_attempt(&rows, Some(rows[0].clone()), "s"); + assert!(matches!( + attempt, + ResetProofAttempt::Valid(Row { id: 1, .. }) + )); + assert!(charge.is_empty()); + } + + #[test] + fn spent_or_expired_selected_request_is_refused_before_the_secret_is_compared() { + let spent = [row(1, "s", false, false)]; + let (attempt, charge) = decide_proof_attempt(&spent, Some(spent[0].clone()), "s"); + assert!(matches!(attempt, ResetProofAttempt::Exhausted)); + assert!(charge.is_empty()); + + let expired = [row(1, "s", true, true)]; + let (attempt, charge) = decide_proof_attempt(&expired, Some(expired[0].clone()), "s"); + assert!(matches!(attempt, ResetProofAttempt::Expired)); + assert!(charge.is_empty()); + } + + #[test] + fn failed_guess_charges_only_active_secret_rows_with_budget() { + let rows = [ + row(1, "s", true, true), + row(2, "s", false, true), + row(3, "s", false, false), + ]; + let (attempt, charge) = decide_proof_attempt(&rows, None, "s"); + assert!(matches!(attempt, ResetProofAttempt::WrongCode)); + assert_eq!(charge, vec![2]); + + // Correct code for another secret's request is a charged failure too. + let other = row(9, "other", false, true); + let (attempt, charge) = decide_proof_attempt(&rows, Some(other), "s"); + assert!(matches!(attempt, ResetProofAttempt::WrongSecret)); + assert_eq!(charge, vec![2]); + } + + #[test] + fn failed_guess_with_no_budget_left_is_exhausted() { + let rows = [row(1, "s", true, true), row(2, "s", false, false)]; + let (attempt, charge) = decide_proof_attempt(&rows, None, "s"); + assert!(matches!(attempt, ResetProofAttempt::Exhausted)); + assert!(charge.is_empty()); + } + + #[test] + fn failed_guess_with_no_active_secret_row_charges_nothing() { + let rows = [row(1, "s", true, true)]; + let (attempt, charge) = decide_proof_attempt(&rows, None, "s"); + assert!(matches!(attempt, ResetProofAttempt::WrongCode)); + assert!(charge.is_empty()); + } +} diff --git a/services/opensecret/src/models/platform_password_reset.rs b/services/opensecret/src/models/platform_password_reset.rs index 789d44fd0..c0935835c 100644 --- a/services/opensecret/src/models/platform_password_reset.rs +++ b/services/opensecret/src/models/platform_password_reset.rs @@ -1,3 +1,4 @@ +use crate::models::password_reset::{decide_proof_attempt, ResetProofAttempt, ResetRequestRow}; use crate::models::schema::platform_password_reset_requests; use chrono::{DateTime, Utc}; use diesel::prelude::*; @@ -11,8 +12,6 @@ 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, @@ -49,7 +48,10 @@ impl PlatformPasswordResetRequest { .filter(platform_password_reset_requests::platform_user_id.eq(lookup_user_id)) .filter(platform_password_reset_requests::encrypted_code.eq(lookup_encrypted_code)) .filter(platform_password_reset_requests::is_reset.eq(false)) - .filter(platform_password_reset_requests::expiration_time.gt(Utc::now())) + // Expiry is left to the caller, which reports an expired request + // as such instead of treating its correct code as a wrong guess. + // Codes can repeat across open requests; pick the newest. + .order(platform_password_reset_requests::id.desc()) .first::(conn) .optional() .map_err(PlatformPasswordResetError::DatabaseError) @@ -92,39 +94,56 @@ impl PlatformPasswordResetRequest { 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( + /// Platform mirror of + /// [`crate::models::password_reset::PasswordResetRequest::attempt_proof`]: + /// locks every unconsumed request carrying the secret, then decides and + /// charges the attempt in one transaction. + pub fn attempt_proof( conn: &mut PgConnection, lookup_user_id: Uuid, lookup_hashed_secret: &str, - ) -> Result<(), PlatformPasswordResetError> { - let charged = diesel::update( - platform_password_reset_requests::table + lookup_encrypted_code: &[u8], + ) -> Result, PlatformPasswordResetError> { + conn.transaction(|conn| { + let secret_requests = 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( + .order(platform_password_reset_requests::id.asc()) + .for_update() + .load::(conn)?; + let selected = + Self::get_by_user_id_and_code(conn, lookup_user_id, lookup_encrypted_code)?; + let (attempt, charge) = + decide_proof_attempt(&secret_requests, selected, lookup_hashed_secret); + if !charge.is_empty() { + diesel::update( + platform_password_reset_requests::table + .filter(platform_password_reset_requests::id.eq_any(charge)), + ) + .set( 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(()) + .eq(platform_password_reset_requests::failed_attempts + 1), + ) + .execute(conn)?; + } + Ok(attempt) + }) + } +} + +impl ResetRequestRow for PlatformPasswordResetRequest { + fn row_id(&self) -> i32 { + self.id + } + fn row_hashed_secret(&self) -> &str { + &self.hashed_secret + } + fn expired(&self) -> bool { + self.is_expired() + } + fn has_budget(&self) -> bool { + self.has_attempt_budget() } } diff --git a/services/opensecret/src/security_invariants.rs b/services/opensecret/src/security_invariants.rs index bce63ac13..6a334b443 100644 --- a/services/opensecret/src/security_invariants.rs +++ b/services/opensecret/src/security_invariants.rs @@ -786,7 +786,8 @@ fn user_password_reset_uses_mac_lookup_and_destructive_reseed() { "user.get_email().is_none()", "user.password_enc.is_none()", "password_reset_code_mac(", - "get_password_reset_request_by_user_id_and_code(user.uuid, reset_code_mac.to_vec())", + "attempt_password_reset_proof(", + "reset_code_mac.to_vec()", ] { assert!( proof_body.contains(required_pattern),