//! Accounts, sessions, cookies, and the request extractor. use argon2::Argon2; use argon2::PasswordHasher; use argon2::password_hash::PasswordHash; use argon2::password_hash::PasswordVerifier; use argon2::password_hash::SaltString; use argon2::password_hash::rand_core::OsRng as SaltRng; use axum::extract::FromRequestParts; use axum::http::HeaderMap; use axum::http::request::Parts; use axum_extra::extract::CookieJar; use axum_extra::extract::cookie::{Cookie, SameSite}; use crate::config::Config; use crate::error::{AppError, AppResult}; use crate::models::User; use crate::state::Shared; use crate::util::{now_ms, random_token, sha256_hex}; /// The login cookie. pub const SESSION_COOKIE: &str = "together_session"; /// The double-submit CSRF cookie, readable by the client. pub const CSRF_COOKIE: &str = "together_csrf"; /// How long a login lasts. pub const SESSION_DAYS: i64 = 30; /// The signed-in account taken from the request cookie. #[derive(Debug, Clone)] pub struct AuthUser { pub user: User, } impl FromRequestParts for AuthUser { type Rejection = AppError; async fn from_request_parts( parts: &mut Parts, state: &Shared, ) -> Result { let jar = CookieJar::from_headers(&parts.headers); let token = jar .get(SESSION_COOKIE) .map(|cookie| cookie.value().to_owned()) .ok_or_else(|| AppError::unauthorized("sign in first"))?; let token_hash = sha256_hex(token.as_bytes()); let user = user_from_token(state, &token_hash) .ok_or_else(|| AppError::unauthorized("session expired"))?; Ok(Self { user }) } } /// Looks up a live session by its token hash and refreshes its /// `last_seen`. pub fn user_from_token(state: &Shared, token_hash: &str) -> Option { let now = now_ms(); let row = state .db .conn() .query_row( "SELECT a.id, a.handle, a.display_name, a.kind, s.expires_at, (SELECT updated_at FROM avatars WHERE account_id = a.id) FROM auth_sessions s JOIN accounts a ON a.id = s.account_id WHERE s.token_hash = ?1", rusqlite::params![token_hash], |row| { Ok(( User { id: row.get(0)?, handle: row.get(1)?, display_name: row.get(2)?, kind: row.get(3)?, avatar_updated_at: row.get(5)?, }, row.get::<_, i64>(4)?, )) }, ) .ok()?; if row.1 < now { let _ = state.db.conn().execute( "DELETE FROM auth_sessions WHERE token_hash = ?1", rusqlite::params![token_hash], ); return None; } let _ = state.db.conn().execute( "UPDATE auth_sessions SET last_seen = ?1 WHERE token_hash = ?2", rusqlite::params![now, token_hash], ); Some(row.0) } /// The user behind the request cookies, if any. pub fn user_from_headers(state: &Shared, headers: &HeaderMap) -> Option { let jar = CookieJar::from_headers(headers); let token = jar.get(SESSION_COOKIE)?.value().to_owned(); user_from_token(state, &sha256_hex(token.as_bytes())) } /// Hashes a password with argon2id and a fresh salt. pub fn hash_password(password: &str) -> AppResult { let salt = SaltString::generate(&mut SaltRng); Argon2::default() .hash_password(password.as_bytes(), &salt) .map(|hash| hash.to_string()) .map_err(|_| AppError::internal("could not hash the password")) } /// A valid hash used to keep a missing account's login time close to a /// wrong password's. Generated once, then reused. pub(crate) fn dummy_password_hash() -> &'static str { static HASH: std::sync::OnceLock = std::sync::OnceLock::new(); HASH.get_or_init(|| hash_password("rhema-together-login-timing").unwrap_or_default()) } /// Verifies a password against a stored argon2 hash. pub fn verify_password(stored: &str, password: &str) -> bool { let Ok(hash) = PasswordHash::new(stored) else { return false; }; Argon2::default() .verify_password(password.as_bytes(), &hash) .is_ok() } /// Creates a login session row and returns the raw token. pub fn create_session(state: &Shared, account_id: &str) -> AppResult { let token = random_token(32); let now = now_ms(); state.db.conn().execute( "INSERT INTO auth_sessions (token_hash, account_id, created_at, expires_at, last_seen) VALUES (?1, ?2, ?3, ?4, ?3)", rusqlite::params![ sha256_hex(token.as_bytes()), account_id, now, now + SESSION_DAYS * 86_400_000 ], )?; Ok(token) } /// A fresh CSRF token, not stored: the cookie and the header carry the /// same value, which is enough for a same-origin client. pub fn new_csrf() -> String { random_token(24) } /// The cookies a successful login sets. pub fn session_cookies(config: &Config, token: &str, csrf: &str) -> CookieJar { let mut session = Cookie::new(SESSION_COOKIE, token.to_owned()); session.set_http_only(true); session.set_same_site(SameSite::Lax); session.set_path("/"); session.set_secure(config.secure_cookies()); session.set_max_age(time::Duration::days(SESSION_DAYS)); let mut csrf_cookie = Cookie::new(CSRF_COOKIE, csrf.to_owned()); csrf_cookie.set_http_only(false); csrf_cookie.set_same_site(SameSite::Lax); csrf_cookie.set_path("/"); csrf_cookie.set_secure(config.secure_cookies()); csrf_cookie.set_max_age(time::Duration::days(SESSION_DAYS)); CookieJar::new().add(session).add(csrf_cookie) } /// The cookies a logout clears. pub fn cleared_cookies(config: &Config) -> CookieJar { let mut session = Cookie::new(SESSION_COOKIE, String::new()); session.set_path("/"); session.set_max_age(time::Duration::seconds(0)); session.set_secure(config.secure_cookies()); let mut csrf = Cookie::new(CSRF_COOKIE, String::new()); csrf.set_path("/"); csrf.set_max_age(time::Duration::seconds(0)); csrf.set_secure(config.secure_cookies()); CookieJar::new().add(session).add(csrf) } /// Requires the `X-CSRF-Token` header to match the CSRF cookie. pub fn require_csrf(headers: &HeaderMap, jar: &CookieJar) -> AppResult<()> { let cookie = jar .get(CSRF_COOKIE) .map(|cookie| cookie.value().to_owned()) .ok_or_else(|| AppError::forbidden("missing CSRF cookie"))?; let header = headers .get("x-csrf-token") .and_then(|value| value.to_str().ok()) .ok_or_else(|| AppError::forbidden("missing CSRF header"))?; if cookie != header { return Err(AppError::forbidden("CSRF token mismatch")); } Ok(()) } /// Validates a handle: 3 to 32 lowercase letters, digits, `_` or `-`. pub fn valid_handle(handle: &str) -> bool { let len = handle.len(); (3..=32).contains(&len) && handle .bytes() .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-') } /// Normalizes a display name: trimmed, 1 to 48 characters. pub fn clean_display_name(name: &str) -> AppResult { let name = name.trim(); if name.is_empty() || name.chars().count() > 48 { return Err(AppError::bad_request( "display name must be 1 to 48 characters", )); } Ok(name.to_owned()) }