//! Email verification: tokens, and sending the link.
//!
//! An account whose `email_verified_at` is empty can read the forum but can't
//! post, reply, react, bookmark or tag while `REQUIRE_EMAIL_VERIFICATION` is
//! on (the default). Registration sends a link; the banner, the profile page
//! and `manage user resend-verification` send fresh ones (rate-limited).
//!
//! Tokens are 256-bit random values. Only their SHA-256 is stored, they expire
//! (`EMAIL_VERIFICATION_TTL_HOURS`, 48), work once, and a new one supersedes
//! any older unused one. Modelled on jupiter-trojan's
//! `tower-login-server/src/confirmation.rs`.
use anyhow::{Context, Result};
use argon2::password_hash::rand_core::{OsRng, RngCore};
use chrono::{DateTime, Duration, FixedOffset, Utc};
use sea_orm::*;
use sha2::{Digest, Sha256};
use tracing::{error, info};
use uuid::Uuid;
use crate::entities::{email_verification_tokens as evt, users};
use crate::mailer::{verify_email_message, Mailer};
use crate::Config;
/// A resend (banner, profile, CLI) doesn't send another link while one sent
/// this recently is still live, so it can't be used to flood an inbox.
pub const RESEND_AFTER_MINUTES: i64 = 10;
/// A fresh token for a link: 32 random bytes from the OS CSPRNG, hex.
pub fn generate_token() -> String {
let mut bytes = [0u8; 32];
OsRng.fill_bytes(&mut bytes);
hex(&bytes)
}
/// What is stored for a token: hex SHA-256.
pub fn hash_token(token: &str) -> String {
hex(&Sha256::digest(token.trim().as_bytes()))
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
/// Whether a token row can still be redeemed at `now`.
pub fn is_redeemable(row: &evt::Model, now: DateTime<Utc>) -> bool {
row.used_at.is_none() && row.expires_at > now
}
/// Issue a token verifying `email` for `user`. Older unused tokens for the
/// user are marked used (superseded). Returns the row and the raw token.
pub async fn issue_token<C: ConnectionTrait>(
db: &C,
user_id: Uuid,
email: &str,
ttl_hours: i64,
) -> Result<(evt::Model, String)> {
let now = Utc::now();
evt::Entity::update_many()
.col_expr(evt::Column::UsedAt, sea_orm::sea_query::Expr::value(Some(DateTime::<FixedOffset>::from(now))))
.filter(evt::Column::UserId.eq(user_id))
.filter(evt::Column::UsedAt.is_null())
.exec(db)
.await
.context("supersede older verification tokens")?;
let token = generate_token();
let row = evt::ActiveModel {
id: Set(Uuid::now_v7()),
user_id: Set(user_id),
token_hash: Set(hash_token(&token)),
email: Set(email.to_string()),
expires_at: Set((now + Duration::hours(ttl_hours)).into()),
used_at: Set(None),
created_at: Set(now.into()),
}
.insert(db)
.await
.context("insert verification token")?;
Ok((row, token))
}
/// When the user's most recent link was issued, if ever.
pub async fn latest_sent_at<C: ConnectionTrait>(db: &C, user_id: Uuid) -> Result<Option<DateTime<FixedOffset>>> {
Ok(evt::Entity::find()
.filter(evt::Column::UserId.eq(user_id))
.order_by_desc(evt::Column::CreatedAt)
.one(db)
.await
.context("latest verification token")?
.map(|t| t.created_at))
}
/// Mark the account's current address verified (CLI, trusted OIDC email).
pub async fn mark_verified<C: ConnectionTrait>(db: &C, user: &users::Model) -> Result<users::Model> {
if user.email_verified_at.is_some() {
return Ok(user.clone());
}
let mut am: users::ActiveModel = user.clone().into();
am.email_verified_at = Set(Some(Utc::now().into()));
am.updated_at = Set(Utc::now().into());
am.update(db).await.context("mark email verified")
}
/// What following a link did.
#[derive(Debug, PartialEq, Eq)]
pub enum Redeemed {
/// The address is now verified (username returned).
Verified(String),
/// Unknown, already used, superseded, or for an address the account no
/// longer has.
Invalid,
Expired,
}
/// Redeem a link's token: single use, unexpired, and only while the token's
/// address is still the account's address.
pub async fn redeem<C: ConnectionTrait>(db: &C, token: &str) -> Result<Redeemed> {
let Some(row) = evt::Entity::find()
.filter(evt::Column::TokenHash.eq(hash_token(token)))
.one(db)
.await
.context("look up verification token")?
else {
return Ok(Redeemed::Invalid);
};
let now = Utc::now();
if row.used_at.is_some() {
return Ok(Redeemed::Invalid);
}
if !is_redeemable(&row, now) {
return Ok(Redeemed::Expired);
}
let Some(user) = users::Entity::find_by_id(row.user_id).one(db).await.context("load user")? else {
return Ok(Redeemed::Invalid);
};
if !user.email.eq_ignore_ascii_case(&row.email) {
return Ok(Redeemed::Invalid);
}
let mut used: evt::ActiveModel = row.into();
used.used_at = Set(Some(now.into()));
used.update(db).await.context("consume verification token")?;
let user = mark_verified(db, &user).await?;
Ok(Redeemed::Verified(user.username))
}
/// What happened when a link was asked for.
#[derive(Debug, PartialEq, Eq)]
pub enum Sent {
/// Mailed (or, without mail-prism, logged).
Yes,
/// Not sent: a link went out less than [`RESEND_AFTER_MINUTES`] ago.
Recently,
/// Nothing to do: the address is already verified.
AlreadyVerified,
/// The token was issued but the mail didn't go (or the token couldn't be
/// made). Already logged.
Failed,
}
impl Sent {
pub fn as_str(&self) -> &'static str {
match self {
Sent::Yes => "sent",
Sent::Recently => "recent",
Sent::AlreadyVerified => "verified",
Sent::Failed => "failed",
}
}
}
/// Issue a link verifying the user's current address and mail it there.
pub async fn send(db: &DatabaseConnection, mailer: &dyn Mailer, config: &Config, user: &users::Model) -> Sent {
if user.email_verified_at.is_some() {
return Sent::AlreadyVerified;
}
let ttl_hours = config.email_verification_ttl_hours;
let (row, token) = match issue_token(db, user.id, &user.email, ttl_hours).await {
Ok(v) => v,
Err(e) => {
error!("failed to create verification token for {}: {e:#}", user.username);
return Sent::Failed;
}
};
let url = format!("{}/verify-email?token={token}", config.public_url);
let message = verify_email_message(&user.email, &config.app_name, &user.username, &url, ttl_hours, row.id);
if let Err(e) = mailer.send(&message).await {
error!("failed to send {} to {}: {e}", message.template, user.username);
return Sent::Failed;
}
info!("sent {} for {}", message.template, user.username);
Sent::Yes
}
/// A resend: a fresh link unless one went out in the last few minutes.
pub async fn send_if_due(db: &DatabaseConnection, mailer: &dyn Mailer, config: &Config, user: &users::Model) -> Sent {
if user.email_verified_at.is_some() {
return Sent::AlreadyVerified;
}
match latest_sent_at(db, user.id).await {
Ok(Some(at)) if at > Utc::now() - Duration::minutes(RESEND_AFTER_MINUTES) => return Sent::Recently,
Ok(_) => {}
Err(e) => {
error!("verification lookup failed for {}: {e:#}", user.username);
return Sent::Failed;
}
}
send(db, mailer, config, user).await
}
#[cfg(test)]
mod tests {
use super::*;
fn row(expires_in: Duration, used: bool) -> evt::Model {
let now = Utc::now();
evt::Model {
id: Uuid::nil(),
user_id: Uuid::nil(),
token_hash: hash_token("t"),
email: "a@example.com".into(),
expires_at: (now + expires_in).into(),
used_at: used.then(|| now.into()),
created_at: now.into(),
}
}
#[test]
fn tokens_are_random_and_only_the_hash_is_kept() {
let a = generate_token();
let b = generate_token();
assert_eq!(a.len(), 64);
assert_ne!(a, b);
let h = hash_token(&a);
assert_eq!(h.len(), 64);
assert_ne!(h, a);
assert_eq!(h, hash_token(&a), "hashing is deterministic");
assert_eq!(h, hash_token(&format!(" {a}\n")), "surrounding whitespace is ignored");
// Known SHA-256 vector.
assert_eq!(
hash_token("abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn expired_or_used_tokens_cannot_be_redeemed() {
let now = Utc::now();
assert!(is_redeemable(&row(Duration::hours(1), false), now));
assert!(!is_redeemable(&row(Duration::hours(-1), false), now));
assert!(!is_redeemable(&row(Duration::hours(1), true), now));
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions running · Badges · Packages
⭐
Log in to mark this repository.
8.7 KiB · text
History
de2cabc