use std::sync::{Arc, OnceLock}; use std::time::Duration; use forge_core::password::{hash_password, verify_password}; use forge_core::time::{now_unix, stamp_after}; use forge_core::token::{constant_time_eq, hash_token, random_b64url}; use forge_core::{Session, Store, User, secret, totp}; use serde::Deserialize; use tokio::sync::Semaphore; use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; use topcoat::router::error::{forbidden, see_other}; use topcoat::router::request::{headers, uri}; use crate::client_ip::client_addr; use crate::state::AppState; pub const SESSION_COOKIE: &str = "forge_session"; pub const SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60); pub const PRE_CSRF_COOKIE: &str = "forge_precsrf"; const PRE_CSRF_TTL: Duration = Duration::from_secs(60 * 60); pub const PENDING_2FA_COOKIE: &str = "forge_2fa"; pub const PENDING_2FA_TTL: Duration = Duration::from_secs(5 * 60); const MAX_NEXT_LEN: usize = 2048; fn session_jar(cx: &Cx) -> impl Cookies + '_ { cookies(cx).override_prefix_host() } pub async fn current_user(cx: &Cx) -> forge_core::Result> { let Some(cookie) = session_jar(cx).get(SESSION_COOKIE) else { return Ok(None); }; let store = &context::(cx).store; let Some(session) = store .session_by_token_hash(&hash_token(cookie.value())) .await? else { return Ok(None); }; let Some(user) = store .user_by_id(&session.user_id) .await? .filter(|user| !user.is_org()) else { return Ok(None); }; let addr = client_addr(cx).to_string(); store.touch_session(&session.id, Some(&addr)).await?; Ok(Some((user, session))) } pub async fn login(cx: &Cx, user: &User) -> forge_core::Result { let store = &context::(cx).store; let token = random_b64url(); let addr = client_addr(cx).to_string(); let session = store .create_session( &user.id, &hash_token(&token), &random_b64url(), &stamp_after(SESSION_TTL), user_agent(cx).as_deref(), Some(&addr), ) .await?; context::(cx) .live .bump(&crate::live::Topic::Account(user.id.clone())); let max_age = time::Duration::seconds(i64::try_from(SESSION_TTL.as_secs()).unwrap_or(i64::MAX)); session_jar(cx).add( Cookie::build((SESSION_COOKIE, token)) .path("/") .secure(true) .http_only(true) .same_site(SameSite::Lax) .max_age(max_age) .build(), ); Ok(session) } pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> { let state = context::(cx); state.store.delete_session(&session.id).await?; crate::live::bump_account(state, &session.user_id); session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); Ok(()) } pub fn check_csrf(session: &Session, submitted: &str) -> bool { !session.csrf_token.is_empty() && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) } pub fn pre_csrf_token(cx: &Cx) -> String { if let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) { let value = cookie.value(); if !value.is_empty() { return value.to_owned(); } } let token = random_b64url(); session_jar(cx).add(pre_csrf_cookie(token.clone())); token } pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool { let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) else { return false; }; !cookie.value().is_empty() && constant_time_eq(cookie.value().as_bytes(), submitted.as_bytes()) } pub fn clear_pre_csrf(cx: &Cx) { session_jar(cx).remove(Cookie::build((PRE_CSRF_COOKIE, "")).path("/")); } fn pre_csrf_cookie(token: String) -> Cookie<'static> { Cookie::build((PRE_CSRF_COOKIE, token)) .path("/") .secure(true) .http_only(true) .same_site(SameSite::Strict) .max_age(time::Duration::seconds( i64::try_from(PRE_CSRF_TTL.as_secs()).unwrap_or(i64::MAX), )) .build() } const MAX_CONCURRENT_PASSWORD_HASHES: usize = 4; fn password_slots() -> &'static Arc { static SLOTS: OnceLock> = OnceLock::new(); SLOTS.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_PASSWORD_HASHES))) } pub async fn hash_password_async(password: String) -> forge_core::Result { let _permit = password_slots() .acquire() .await .map_err(|_| forge_core::Error::Crypto("password hashing is shut down".into()))?; tokio::task::spawn_blocking(move || hash_password(&password)) .await .map_err(|_| forge_core::Error::Crypto("password hashing task failed".into()))? } pub async fn verify_password_async(password: String, hash: String) -> forge_core::Result { let _permit = password_slots() .acquire() .await .map_err(|_| forge_core::Error::Crypto("password verification is shut down".into()))?; tokio::task::spawn_blocking(move || verify_password(&password, &hash)) .await .map_err(|_| forge_core::Error::Crypto("password verification task failed".into())) } pub async fn require_user(cx: &Cx) -> Result<(User, Session)> { match current_user(cx).await? { Some(viewer) => Ok(viewer), None => { let path = uri(cx).path_and_query().map_or("/", |p| p.as_str()); let target = format!("/login?next={}", percent_encode(path)); Err(see_other(target).into()) } } } #[derive(Deserialize)] pub struct CsrfForm { #[serde(default)] pub csrf: String, } pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> { let (user, session) = require_user(cx).await?; if check_csrf(&session, submitted) { Ok((user, session)) } else { Err(forbidden().into()) } } pub struct PendingLogin { pub user_id: String, pub next: String, } pub fn set_pending_login( cx: &Cx, key: &[u8; 32], user_id: &str, next: &str, ) -> forge_core::Result<()> { let expires = now_unix().saturating_add_unsigned(PENDING_2FA_TTL.as_secs()); let sealed = secret::seal(key, format!("{expires}|{user_id}|{next}").as_bytes())?; let max_age = time::Duration::seconds(i64::try_from(PENDING_2FA_TTL.as_secs()).unwrap_or(0)); session_jar(cx).add( Cookie::build((PENDING_2FA_COOKIE, sealed)) .path("/") .secure(true) .http_only(true) .same_site(SameSite::Strict) .max_age(max_age) .build(), ); Ok(()) } pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option { let cookie = session_jar(cx).get(PENDING_2FA_COOKIE)?; let plain = secret::open(key, cookie.value()).ok()?; let text = String::from_utf8(plain).ok()?; let mut parts = text.splitn(3, '|'); let expires: i64 = parts.next()?.parse().ok()?; let user_id = parts.next()?; let next = parts.next()?; if now_unix() >= expires { return None; } Some(PendingLogin { user_id: user_id.to_owned(), next: next.to_owned(), }) } pub fn clear_pending_login(cx: &Cx) { session_jar(cx).remove(Cookie::build((PENDING_2FA_COOKIE, "")).path("/")); } pub async fn two_factor_enabled(store: &Store, user_id: &str) -> forge_core::Result { Ok(store .totp_state(user_id) .await? .is_some_and(|state| state.enabled)) } pub async fn verify_second_factor( store: &Store, key: &[u8; 32], user_id: &str, input: &str, ) -> forge_core::Result { let input = input.trim(); if store .user_by_id(user_id) .await? .is_none_or(|user| user.is_org()) { return Ok(false); } let Some(state) = store.totp_state(user_id).await? else { return Ok(false); }; let Some(sealed) = state.sealed_secret.as_deref() else { return Ok(false); }; if !state.enabled { return Ok(false); } let shared = secret::open(key, sealed)?; let is_totp = input.len() == totp::DIGITS && input.bytes().all(|b| b.is_ascii_digit()); if is_totp { return match totp::verify(&shared, input, totp::step_for(now_unix()), state.last_step) { Some(step) => store.accept_totp_step(user_id, step).await, None => Ok(false), }; } store .consume_recovery_code(user_id, &totp::recovery_code_hash(input)) .await } pub fn safe_next(next: Option<&str>) -> &str { match next { Some(n) if is_local_path(n) => n, _ => "/", } } fn is_local_path(path: &str) -> bool { path.len() <= MAX_NEXT_LEN && path.starts_with('/') && !path.starts_with("//") && !path.starts_with("/\\") && path.chars().all(|c| !c.is_control()) } pub fn percent_encode(input: &str) -> String { let mut out = String::with_capacity(input.len()); for b in input.bytes() { match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { out.push(char::from(b)); } _ => out.push_str(&format!("%{b:02X}")), } } out } pub fn user_agent(cx: &Cx) -> Option { headers(cx) .get(http::header::USER_AGENT) .and_then(|v| v.to_str().ok()) .map(|s| s.chars().take(512).collect()) } #[cfg(test)] mod tests { use super::*; fn session_with_csrf(csrf: &str) -> Session { Session { id: "s1".into(), user_id: "u1".into(), csrf_token: csrf.into(), created_at: String::new(), expires_at: String::new(), last_seen: String::new(), user_agent: None, ip: None, last_ip: None, } } #[test] fn csrf_accepts_only_the_exact_token() { let s = session_with_csrf("abc123"); assert!(check_csrf(&s, "abc123")); assert!(!check_csrf(&s, "abc124")); assert!(!check_csrf(&s, "abc12")); assert!(!check_csrf(&s, "")); } #[test] fn csrf_rejects_empty_session_token() { let s = session_with_csrf(""); assert!(!check_csrf(&s, "")); assert!(!check_csrf(&s, "x")); } #[test] fn next_allows_local_paths() { assert_eq!(safe_next(Some("/")), "/"); assert_eq!(safe_next(Some("/tahinli/repo")), "/tahinli/repo"); assert_eq!(safe_next(Some("/settings/keys?x=1")), "/settings/keys?x=1"); } #[test] fn next_rejects_open_redirects() { for bad in [ "", "https://evil.example/", "//evil.example/", "/\\evil.example/", "evil.example", "\\\\evil", "/\n/evil", "/\t", ] { assert_eq!(safe_next(Some(bad)), "/", "input {bad:?}"); } assert_eq!(safe_next(None), "/"); } #[test] fn next_rejects_overlong_paths() { let long = format!("/{}", "a".repeat(MAX_NEXT_LEN)); assert_eq!(safe_next(Some(&long)), "/"); } #[test] fn percent_encode_keeps_slashes_and_encodes_the_rest() { assert_eq!(percent_encode("/a/b-c_d.e~f"), "/a/b-c_d.e~f"); assert_eq!(percent_encode("/s?x=1&y=2"), "/s%3Fx%3D1%26y%3D2"); assert_eq!(percent_encode("/a b"), "/a%20b"); } #[tokio::test] async fn an_org_never_passes_a_second_factor() { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); let key = [7u8; 32]; let tahinli = store .create_user("tahinli", None, "h", false) .await .unwrap(); let org = store.create_org("acme", &tahinli.id).await.unwrap(); let shared = forge_core::totp::new_secret(); let sealed = forge_core::secret::seal(&key, &shared).unwrap(); let code = forge_core::totp::code_at(&shared, forge_core::totp::step_for(now_unix())); let recovery = forge_core::totp::recovery_code_hash("aaaa-bbbb"); for id in [&org.id, &tahinli.id] { store.set_totp_secret(id, &sealed).await.unwrap(); store .enable_totp(id, 0, std::slice::from_ref(&recovery)) .await .unwrap(); } assert!( !verify_second_factor(&store, &key, &org.id, &code) .await .unwrap() ); assert!( !verify_second_factor(&store, &key, &org.id, "aaaa-bbbb") .await .unwrap() ); assert!( verify_second_factor(&store, &key, &tahinli.id, "aaaa-bbbb") .await .unwrap() ); } }