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/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..545df99bd --- /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: 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 an 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..4ae9e1015 100644 --- a/services/opensecret/src/aead_db_tamper_tests.rs +++ b/services/opensecret/src/aead_db_tamper_tests.rs @@ -3447,4 +3447,772 @@ 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; + 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(); + 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"); + 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:?}"), + } + }); + } + }); + + 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") + }; + 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 + // 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 { .. })) + )); + 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)] + #[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; + 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 || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("initiation worker runtime should start"); + runtime.block_on(async move { + if state + .create_password_reset_request( + email, + generate_reset_hash(format!("concurrent-cap-{attempt}")), + project.id, + ) + .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_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(); + } + + /// 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(); + } + + /// 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(); + } + + /// 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 c64b7c8f3..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, @@ -239,6 +239,21 @@ 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>; + /// 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, + encrypted_code: Vec, + ) -> Result, DBError>; fn get_password_reset_request_by_user_id_and_code( &self, user_id: Uuid, @@ -552,12 +567,19 @@ pub trait DBConnection { &self, new_request: NewPlatformPasswordResetRequest, ) -> Result; - - fn get_platform_password_reset_request_by_user_id_and_code( + /// 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>; + /// Platform mirror of [`DBConnection::attempt_password_reset_proof`]. + fn attempt_platform_password_reset_proof( &self, user_id: Uuid, + hashed_secret: &str, encrypted_code: Vec, - ) -> Result, DBError>; + ) -> Result, DBError>; fn platform_password_reset_request_is_active_for_secret( &self, @@ -1116,6 +1138,36 @@ 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 attempt_password_reset_proof( + &self, + user_id: Uuid, + hashed_secret: &str, + encrypted_code: Vec, + ) -> Result, DBError> { + let conn = &mut self.db.get().map_err(|_| DBError::ConnectionError)?; + 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( &self, user_id: Uuid, @@ -2344,17 +2396,36 @@ impl DBConnection for PostgresConnection { result } - fn get_platform_password_reset_request_by_user_id_and_code( + 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 attempt_platform_password_reset_proof( &self, user_id: Uuid, + hashed_secret: &str, encrypted_code: Vec, - ) -> Result, DBError> { + ) -> 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); + let result = PlatformPasswordResetRequest::attempt_proof( + conn, + user_id, + hashed_secret, + &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 2cc030780..e99167fa5 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, PasswordResetRequest, ResetProofAttempt, +}; use crate::models::platform_password_reset::NewPlatformPasswordResetRequest; use crate::models::platform_users::PlatformUser; use crate::sqs::SqsEventPublisher; @@ -2142,7 +2144,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 +2163,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!("No password reset request created: email cap reached or account removed"); + } + Err(e) => { + error!("Error during password reset request: {:?}", e); + } + } } } Err(DBError::UserNotFound) => { @@ -2220,8 +2240,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 charge is + /// scoped to the submitted secret, so nobody without it can spend its + /// attempts. fn verify_password_reset_proof( &self, email: String, @@ -2243,8 +2266,10 @@ 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)?; @@ -2254,23 +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() => Error::PasswordResetExpired, - Some(request) => { - if hashed_plaintext - .as_bytes() - .ct_eq(request.hashed_secret.as_bytes()) - .into() - { - return Ok((user, request)); - } - Error::InvalidPasswordResetSecret + // 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(), + })) } - None => Error::InvalidPasswordResetRequest, + 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) } @@ -2494,25 +2522,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!( + "No platform password reset request created: email cap reached or account removed" + ); + } + Err(e) => { + return Err(Error::DatabaseError(e)); + } + } } } Ok(None) => { @@ -2560,73 +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, - )?; - - if let Some(reset_request) = reset_request { - if reset_request.is_expired() { + // 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(), + })) + } + 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 { - 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 { - 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 b4e7f9bcf..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; @@ -11,6 +12,17 @@ pub enum PasswordResetError { DatabaseError(#[from] diesel::result::Error), } +/// 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 +33,7 @@ pub struct PasswordResetRequest { pub expiration_time: DateTime, pub created_at: DateTime, pub is_reset: bool, + pub failed_attempts: i32, } impl PasswordResetRequest { @@ -72,6 +85,135 @@ impl PasswordResetRequest { pub fn is_expired(&self) -> bool { Utc::now() > self.expiration_time } + + /// Decides one reset proof attempt for the code-selected request and + /// charges a failed guess, all inside one transaction. + /// + /// 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, + 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)) + .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)), + ) + .set( + password_reset_requests::failed_attempts + .eq(password_reset_requests::failed_attempts + 1), + ) + .execute(conn)?; + } + Ok(attempt) + }) + } + + /// 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)] @@ -98,6 +240,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, @@ -108,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 5b1c0a87b..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::*; @@ -13,6 +14,16 @@ pub enum PlatformPasswordResetError { InvalidExpirationHours(String), } +/// 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 +35,7 @@ pub struct PlatformPasswordResetRequest { pub created_at: DateTime, pub updated_at: DateTime, pub is_reset: bool, + pub failed_attempts: i32, } impl PlatformPasswordResetRequest { @@ -36,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) @@ -73,6 +88,63 @@ 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 + } + + /// 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, + 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)) + .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 + .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() + } } #[derive(Insertable)] @@ -105,6 +177,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/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), 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)?;