git clone https://garage44.eu/jeroen/cartopolis.git.. /crates/simulator/src/password_reset.rs
//! "Forgot your password?": a link mailed to the account's confirmed address,
//! good for one new password.
//!
//! # What it rests on
//!
//! Control of the mailbox the account was confirmed with — the same proof
//! registration took (`registration`). So only an account with a *confirmed*
//! address gets a link. A pending one has never shown its address answers, and
//! the useful mail for it is the confirmation link again, which the handler
//! sends instead; an operator-made account, or one made through another site
//! that shared no address, has nowhere to send anything, and its way back is
//! still an operator.
//!
//! # What a reset does besides the password
//!
//! Signs the account out everywhere ([`crate::auth::Sessions::revoke_principal`]):
//! the person asking may be asking *because* somebody else has the password,
//! and a reset that left that somebody's session open would not have helped.
use crate::auth::{random_token, token_hash};
use anyhow::Context;
use rusqlite::{Connection, OptionalExtension};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// How long a reset link works.
///
/// Much shorter than a confirmation link (`registration::VERIFICATION_TTL`):
/// the person asking is at the form now, waiting for the mail, and this link
/// sets the password, so a copy left in a mailbox should stop working soon.
pub const RESET_TTL: Duration = Duration::from_secs(60 * 60);
fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// What [`request`] found for an address.
#[derive(Debug, PartialEq, Eq)]
pub enum Request {
/// A confirmed account: mail it this link's token.
Reset { username: String, token: String },
/// An account whose address was never confirmed: mail the confirmation
/// link again rather than a reset (`registration::reissue`).
Pending,
/// No account has this address. Told to nobody.
Unknown,
}
/// Mint a reset token for the account with `email`, replacing any it had.
///
/// Replacing, as the confirmation link's re-send does: two live links means
/// the older mail still works after the newer one was asked for.
pub fn request(conn: &Connection, email: &str) -> anyhow::Result<Request> {
let email = email.trim().to_lowercase();
let row: Option<(String, String, Option<String>)> = conn
.query_row(
"SELECT id, username, email_verified_at FROM accounts WHERE lower(email) = ?1",
[&email],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?;
let Some((principal, username, verified_at)) = row else {
return Ok(Request::Unknown);
};
if verified_at.is_none() {
return Ok(Request::Pending);
}
let token = random_token();
let now = unix_now();
conn.execute(
"DELETE FROM password_resets WHERE principal = ?1 OR expires_at < ?2",
rusqlite::params![principal, now],
)?;
conn.execute(
"INSERT INTO password_resets (token_hash, principal, created_at, expires_at)
VALUES (?1, ?2, ?3, ?4)",
rusqlite::params![
token_hash(&token),
principal,
now,
now + RESET_TTL.as_secs() as i64,
],
)
.context("insert password reset")?;
Ok(Request::Reset { username, token })
}
/// What [`finish`] made of a token.
#[derive(Debug, PartialEq, Eq)]
pub enum Finish {
/// The password is replaced.
Done { principal: String, username: String },
/// No such token: never issued, already used, or replaced by a newer one.
Unknown,
/// Issued, and too old.
Expired,
}
/// Spend a reset token on a new password, given as an argon2 PHC string — the
/// caller hashes it first, with no database lock held (`auth`'s module note).
///
/// The row goes whether the token was in time or not, as a confirmation
/// link's does: an expired one is worth nothing, and a used one must not work
/// twice.
pub fn finish(conn: &mut Connection, token: &str, pw_hash: &str) -> anyhow::Result<Finish> {
let hash = token_hash(token);
let tx = conn.transaction()?;
let row: Option<(String, i64)> = tx
.query_row(
"SELECT principal, expires_at FROM password_resets WHERE token_hash = ?1",
[&hash],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
let Some((principal, expires_at)) = row else {
return Ok(Finish::Unknown);
};
tx.execute("DELETE FROM password_resets WHERE token_hash = ?1", [&hash])?;
if expires_at < unix_now() {
tx.commit()?;
return Ok(Finish::Expired);
}
let username: Option<String> = tx
.query_row(
"SELECT username FROM accounts WHERE id = ?1",
[&principal],
|r| r.get(0),
)
.optional()?;
let Some(username) = username else {
// The account was deleted between the mail and the click.
tx.commit()?;
return Ok(Finish::Unknown);
};
tx.execute(
"UPDATE accounts SET pw_hash = ?2 WHERE id = ?1",
rusqlite::params![principal, pw_hash],
)?;
tx.commit()?;
Ok(Finish::Done {
principal,
username,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::registration;
fn db() -> Connection {
let mut conn = Connection::open_in_memory().unwrap();
crate::db::migrate(&mut conn).unwrap();
conn
}
fn hash(pw: &str) -> String {
crate::auth::hash_password(pw).unwrap()
}
/// A registered account whose link was opened.
fn confirmed(conn: &mut Connection, username: &str, email: &str) {
let registration::Begin::Created { token, .. } =
registration::begin(conn, username, email, &hash("oldpassword")).unwrap()
else {
panic!("registration did not create an account");
};
registration::verify(conn, &token).unwrap();
}
fn signs_in(conn: &Connection, username: &str, password: &str) -> bool {
let stored = crate::auth::lookup_credential(conn, username)
.unwrap()
.unwrap();
crate::auth::verify_password(password, &stored.phc)
}
#[test]
fn a_link_sets_the_password_once() {
let mut conn = db();
confirmed(&mut conn, "ada", "ada@example.com");
let Request::Reset { username, token } = request(&conn, " Ada@Example.com ").unwrap()
else {
panic!("a confirmed address gets a link");
};
assert_eq!(username, "ada");
let outcome = finish(&mut conn, &token, &hash("newpassword")).unwrap();
assert!(matches!(outcome, Finish::Done { ref username, .. } if username == "ada"));
assert!(signs_in(&conn, "ada", "newpassword"));
assert!(!signs_in(&conn, "ada", "oldpassword"));
assert_eq!(
finish(&mut conn, &token, &hash("thirdpassword")).unwrap(),
Finish::Unknown
);
assert!(signs_in(&conn, "ada", "newpassword"));
}
#[test]
fn asking_again_replaces_the_earlier_link() {
let mut conn = db();
confirmed(&mut conn, "ada", "ada@example.com");
let Request::Reset { token: first, .. } = request(&conn, "ada@example.com").unwrap() else {
panic!()
};
let Request::Reset { token: second, .. } = request(&conn, "ada@example.com").unwrap()
else {
panic!()
};
assert_eq!(
finish(&mut conn, &first, &hash("newpassword")).unwrap(),
Finish::Unknown
);
assert!(matches!(
finish(&mut conn, &second, &hash("newpassword")).unwrap(),
Finish::Done { .. }
));
}
#[test]
fn only_a_confirmed_address_gets_a_link() {
let mut conn = db();
registration::begin(&mut conn, "grace", "grace@example.com", &hash("pw12345678")).unwrap();
assert_eq!(
request(&conn, "grace@example.com").unwrap(),
Request::Pending
);
assert_eq!(
request(&conn, "nobody@example.com").unwrap(),
Request::Unknown
);
}
#[test]
fn an_expired_link_is_told_apart_and_spent() {
let mut conn = db();
confirmed(&mut conn, "ada", "ada@example.com");
let Request::Reset { token, .. } = request(&conn, "ada@example.com").unwrap() else {
panic!()
};
conn.execute("UPDATE password_resets SET expires_at = 0", [])
.unwrap();
assert_eq!(
finish(&mut conn, &token, &hash("newpassword")).unwrap(),
Finish::Expired
);
assert!(signs_in(&conn, "ada", "oldpassword"));
assert_eq!(
finish(&mut conn, &token, &hash("newpassword")).unwrap(),
Finish::Unknown
);
}
}