| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use std::time::Duration; |
| 7 | |
| 8 | use forge_core::password::{hash_password, verify_password}; |
| 9 | use forge_core::session::{new_csrf_token, new_session_token}; |
| 10 | use forge_core::time::stamp_after; |
| 11 | use forge_core::token::{constant_time_eq, hash_token}; |
| 12 | use forge_core::{Session, Store, User, secret, totp}; |
| 13 | use topcoat::Result; |
| 14 | use topcoat::context::{Cx, app_context}; |
| 15 | use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; |
| 16 | use topcoat::router::error::{forbidden, see_other}; |
| 17 | use topcoat::router::request::{headers, uri}; |
| 18 | |
| 19 | use crate::state::AppState; |
| 20 | |
| 21 | |
| 22 | pub const SESSION_COOKIE: &str = "forge_session"; |
| 23 | |
| 24 | pub const SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60); |
| 25 | |
| 26 | |
| 27 | |
| 28 | pub const PRE_CSRF_COOKIE: &str = "forge_precsrf"; |
| 29 | |
| 30 | const PRE_CSRF_TTL: Duration = Duration::from_secs(60 * 60); |
| 31 | |
| 32 | |
| 33 | |
| 34 | pub const PENDING_2FA_COOKIE: &str = "forge_2fa"; |
| 35 | |
| 36 | pub const PENDING_2FA_TTL: Duration = Duration::from_secs(5 * 60); |
| 37 | |
| 38 | |
| 39 | const MAX_NEXT_LEN: usize = 2048; |
| 40 | |
| 41 | |
| 42 | fn session_jar(cx: &Cx) -> impl Cookies + '_ { |
| 43 | cookies(cx).override_prefix_host() |
| 44 | } |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)>> { |
| 51 | let Some(cookie) = session_jar(cx).get(SESSION_COOKIE) else { |
| 52 | return Ok(None); |
| 53 | }; |
| 54 | let store = &app_context::<AppState>(cx).store; |
| 55 | let Some(session) = store |
| 56 | .session_by_token_hash(&hash_token(cookie.value())) |
| 57 | .await? |
| 58 | else { |
| 59 | return Ok(None); |
| 60 | }; |
| 61 | |
| 62 | let Some(user) = store |
| 63 | .user_by_id(&session.user_id) |
| 64 | .await? |
| 65 | .filter(|user| !user.is_org()) |
| 66 | else { |
| 67 | return Ok(None); |
| 68 | }; |
| 69 | store.touch_session(&session.id).await?; |
| 70 | Ok(Some((user, session))) |
| 71 | } |
| 72 | |
| 73 | |
| 74 | pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> { |
| 75 | let store = &app_context::<AppState>(cx).store; |
| 76 | let token = new_session_token(); |
| 77 | let session = store |
| 78 | .create_session( |
| 79 | &user.id, |
| 80 | &hash_token(&token), |
| 81 | &new_csrf_token(), |
| 82 | &stamp_after(SESSION_TTL), |
| 83 | user_agent(cx).as_deref(), |
| 84 | ) |
| 85 | .await?; |
| 86 | |
| 87 | app_context::<AppState>(cx) |
| 88 | .live |
| 89 | .bump(&crate::live::Topic::Account(user.id.clone())); |
| 90 | let max_age = time::Duration::seconds(i64::try_from(SESSION_TTL.as_secs()).unwrap_or(i64::MAX)); |
| 91 | session_jar(cx).add( |
| 92 | Cookie::build((SESSION_COOKIE, token)) |
| 93 | .path("/") |
| 94 | .secure(true) |
| 95 | .http_only(true) |
| 96 | .same_site(SameSite::Lax) |
| 97 | .max_age(max_age) |
| 98 | .build(), |
| 99 | ); |
| 100 | Ok(session) |
| 101 | } |
| 102 | |
| 103 | |
| 104 | pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> { |
| 105 | let state = app_context::<AppState>(cx); |
| 106 | state.store.delete_session(&session.id).await?; |
| 107 | |
| 108 | crate::pages::settings_live::bump_account(state, &session.user_id); |
| 109 | session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); |
| 110 | Ok(()) |
| 111 | } |
| 112 | |
| 113 | |
| 114 | pub fn check_csrf(session: &Session, submitted: &str) -> bool { |
| 115 | |
| 116 | !session.csrf_token.is_empty() |
| 117 | && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) |
| 118 | } |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | pub fn pre_csrf_token(cx: &Cx) -> String { |
| 125 | if let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) { |
| 126 | let value = cookie.value(); |
| 127 | if !value.is_empty() { |
| 128 | return value.to_owned(); |
| 129 | } |
| 130 | } |
| 131 | let token = new_csrf_token(); |
| 132 | session_jar(cx).add(pre_csrf_cookie(token.clone())); |
| 133 | token |
| 134 | } |
| 135 | |
| 136 | |
| 137 | pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool { |
| 138 | let Some(cookie) = session_jar(cx).get(PRE_CSRF_COOKIE) else { |
| 139 | return false; |
| 140 | }; |
| 141 | !cookie.value().is_empty() && constant_time_eq(cookie.value().as_bytes(), submitted.as_bytes()) |
| 142 | } |
| 143 | |
| 144 | |
| 145 | pub fn clear_pre_csrf(cx: &Cx) { |
| 146 | session_jar(cx).remove(Cookie::build((PRE_CSRF_COOKIE, "")).path("/")); |
| 147 | } |
| 148 | |
| 149 | fn pre_csrf_cookie(token: String) -> Cookie<'static> { |
| 150 | Cookie::build((PRE_CSRF_COOKIE, token)) |
| 151 | .path("/") |
| 152 | .secure(true) |
| 153 | .http_only(true) |
| 154 | .same_site(SameSite::Strict) |
| 155 | .max_age(time::Duration::seconds( |
| 156 | i64::try_from(PRE_CSRF_TTL.as_secs()).unwrap_or(i64::MAX), |
| 157 | )) |
| 158 | .build() |
| 159 | } |
| 160 | |
| 161 | |
| 162 | pub async fn hash_password_async(password: String) -> forge_core::Result<String> { |
| 163 | tokio::task::spawn_blocking(move || hash_password(&password)) |
| 164 | .await |
| 165 | .map_err(|_| forge_core::Error::Crypto("password hashing task failed".into()))? |
| 166 | } |
| 167 | |
| 168 | |
| 169 | pub async fn verify_password_async(password: String, hash: String) -> forge_core::Result<bool> { |
| 170 | tokio::task::spawn_blocking(move || verify_password(&password, &hash)) |
| 171 | .await |
| 172 | .map_err(|_| forge_core::Error::Crypto("password verification task failed".into())) |
| 173 | } |
| 174 | |
| 175 | |
| 176 | pub async fn require_user(cx: &Cx) -> Result<(User, Session)> { |
| 177 | match current_user(cx).await? { |
| 178 | Some(viewer) => Ok(viewer), |
| 179 | None => { |
| 180 | let path = uri(cx).path_and_query().map_or("/", |p| p.as_str()); |
| 181 | let target = format!("/login?next={}", percent_encode(path)); |
| 182 | Err(see_other(target).into()) |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | |
| 188 | pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> { |
| 189 | let (user, session) = require_user(cx).await?; |
| 190 | if check_csrf(&session, submitted) { |
| 191 | Ok((user, session)) |
| 192 | } else { |
| 193 | Err(forbidden().into()) |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | |
| 198 | pub struct PendingLogin { |
| 199 | pub user_id: String, |
| 200 | pub next: String, |
| 201 | } |
| 202 | |
| 203 | |
| 204 | pub fn unix_now() -> u64 { |
| 205 | std::time::SystemTime::now() |
| 206 | .duration_since(std::time::UNIX_EPOCH) |
| 207 | .map_or(0, |d| d.as_secs()) |
| 208 | } |
| 209 | |
| 210 | |
| 211 | |
| 212 | pub fn set_pending_login( |
| 213 | cx: &Cx, |
| 214 | key: &[u8; 32], |
| 215 | user_id: &str, |
| 216 | next: &str, |
| 217 | ) -> forge_core::Result<()> { |
| 218 | let expires = unix_now() + PENDING_2FA_TTL.as_secs(); |
| 219 | let sealed = secret::seal(key, format!("{expires}|{user_id}|{next}").as_bytes())?; |
| 220 | let max_age = time::Duration::seconds(i64::try_from(PENDING_2FA_TTL.as_secs()).unwrap_or(0)); |
| 221 | session_jar(cx).add( |
| 222 | Cookie::build((PENDING_2FA_COOKIE, sealed)) |
| 223 | .path("/") |
| 224 | .secure(true) |
| 225 | .http_only(true) |
| 226 | .same_site(SameSite::Strict) |
| 227 | .max_age(max_age) |
| 228 | .build(), |
| 229 | ); |
| 230 | Ok(()) |
| 231 | } |
| 232 | |
| 233 | |
| 234 | |
| 235 | pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<PendingLogin> { |
| 236 | let cookie = session_jar(cx).get(PENDING_2FA_COOKIE)?; |
| 237 | let plain = secret::open(key, cookie.value()).ok()?; |
| 238 | let text = String::from_utf8(plain).ok()?; |
| 239 | let mut parts = text.splitn(3, '|'); |
| 240 | let expires: u64 = parts.next()?.parse().ok()?; |
| 241 | let user_id = parts.next()?; |
| 242 | let next = parts.next()?; |
| 243 | if unix_now() >= expires { |
| 244 | return None; |
| 245 | } |
| 246 | Some(PendingLogin { |
| 247 | user_id: user_id.to_owned(), |
| 248 | next: next.to_owned(), |
| 249 | }) |
| 250 | } |
| 251 | |
| 252 | |
| 253 | pub fn clear_pending_login(cx: &Cx) { |
| 254 | session_jar(cx).remove(Cookie::build((PENDING_2FA_COOKIE, "")).path("/")); |
| 255 | } |
| 256 | |
| 257 | |
| 258 | pub async fn two_factor_enabled(store: &Store, user_id: &str) -> forge_core::Result<bool> { |
| 259 | Ok(store |
| 260 | .totp_state(user_id) |
| 261 | .await? |
| 262 | .is_some_and(|state| state.enabled)) |
| 263 | } |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | pub async fn verify_second_factor( |
| 269 | store: &Store, |
| 270 | key: &[u8; 32], |
| 271 | user_id: &str, |
| 272 | input: &str, |
| 273 | ) -> forge_core::Result<bool> { |
| 274 | let input = input.trim(); |
| 275 | |
| 276 | if store |
| 277 | .user_by_id(user_id) |
| 278 | .await? |
| 279 | .is_none_or(|user| user.is_org()) |
| 280 | { |
| 281 | return Ok(false); |
| 282 | } |
| 283 | let Some(state) = store.totp_state(user_id).await? else { |
| 284 | return Ok(false); |
| 285 | }; |
| 286 | let Some(sealed) = state.sealed_secret.as_deref() else { |
| 287 | return Ok(false); |
| 288 | }; |
| 289 | if !state.enabled { |
| 290 | return Ok(false); |
| 291 | } |
| 292 | let shared = secret::open(key, sealed)?; |
| 293 | let is_totp = input.len() == totp::DIGITS && input.bytes().all(|b| b.is_ascii_digit()); |
| 294 | if is_totp { |
| 295 | return match totp::verify(&shared, input, totp::step_for(unix_now()), state.last_step) { |
| 296 | Some(step) => store.accept_totp_step(user_id, step).await, |
| 297 | None => Ok(false), |
| 298 | }; |
| 299 | } |
| 300 | store |
| 301 | .consume_recovery_code(user_id, &totp::recovery_code_hash(input)) |
| 302 | .await |
| 303 | } |
| 304 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | pub fn safe_next(next: Option<&str>) -> &str { |
| 310 | match next { |
| 311 | Some(n) if is_local_path(n) => n, |
| 312 | _ => "/", |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | fn is_local_path(path: &str) -> bool { |
| 317 | path.len() <= MAX_NEXT_LEN |
| 318 | && path.starts_with('/') |
| 319 | && !path.starts_with("//") |
| 320 | && !path.starts_with("/\\") |
| 321 | && path.chars().all(|c| !c.is_control()) |
| 322 | } |
| 323 | |
| 324 | |
| 325 | pub fn percent_encode(input: &str) -> String { |
| 326 | let mut out = String::with_capacity(input.len()); |
| 327 | for b in input.bytes() { |
| 328 | match b { |
| 329 | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { |
| 330 | out.push(char::from(b)); |
| 331 | } |
| 332 | _ => out.push_str(&format!("%{b:02X}")), |
| 333 | } |
| 334 | } |
| 335 | out |
| 336 | } |
| 337 | |
| 338 | |
| 339 | pub fn user_agent(cx: &Cx) -> Option<String> { |
| 340 | headers(cx) |
| 341 | .get(http::header::USER_AGENT) |
| 342 | .and_then(|v| v.to_str().ok()) |
| 343 | .map(|s| s.chars().take(512).collect()) |
| 344 | } |
| 345 | |
| 346 | #[cfg(test)] |
| 347 | mod tests { |
| 348 | use super::*; |
| 349 | |
| 350 | fn session_with_csrf(csrf: &str) -> Session { |
| 351 | Session { |
| 352 | id: "s1".into(), |
| 353 | user_id: "u1".into(), |
| 354 | csrf_token: csrf.into(), |
| 355 | created_at: String::new(), |
| 356 | expires_at: String::new(), |
| 357 | last_seen: String::new(), |
| 358 | user_agent: None, |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | #[test] |
| 363 | fn csrf_accepts_only_the_exact_token() { |
| 364 | let s = session_with_csrf("abc123"); |
| 365 | assert!(check_csrf(&s, "abc123")); |
| 366 | assert!(!check_csrf(&s, "abc124")); |
| 367 | assert!(!check_csrf(&s, "abc12")); |
| 368 | assert!(!check_csrf(&s, "")); |
| 369 | } |
| 370 | |
| 371 | #[test] |
| 372 | fn csrf_rejects_empty_session_token() { |
| 373 | let s = session_with_csrf(""); |
| 374 | assert!(!check_csrf(&s, "")); |
| 375 | assert!(!check_csrf(&s, "x")); |
| 376 | } |
| 377 | |
| 378 | #[test] |
| 379 | fn next_allows_local_paths() { |
| 380 | assert_eq!(safe_next(Some("/")), "/"); |
| 381 | assert_eq!(safe_next(Some("/tahinli/repo")), "/tahinli/repo"); |
| 382 | assert_eq!(safe_next(Some("/settings/keys?x=1")), "/settings/keys?x=1"); |
| 383 | } |
| 384 | |
| 385 | #[test] |
| 386 | fn next_rejects_open_redirects() { |
| 387 | for bad in [ |
| 388 | "", |
| 389 | "https://evil.example/", |
| 390 | "//evil.example/", |
| 391 | "/\\evil.example/", |
| 392 | "evil.example", |
| 393 | "\\\\evil", |
| 394 | "/\n/evil", |
| 395 | "/\t", |
| 396 | ] { |
| 397 | assert_eq!(safe_next(Some(bad)), "/", "input {bad:?}"); |
| 398 | } |
| 399 | assert_eq!(safe_next(None), "/"); |
| 400 | } |
| 401 | |
| 402 | #[test] |
| 403 | fn next_rejects_overlong_paths() { |
| 404 | let long = format!("/{}", "a".repeat(MAX_NEXT_LEN)); |
| 405 | assert_eq!(safe_next(Some(&long)), "/"); |
| 406 | } |
| 407 | |
| 408 | #[test] |
| 409 | fn percent_encode_keeps_slashes_and_encodes_the_rest() { |
| 410 | assert_eq!(percent_encode("/a/b-c_d.e~f"), "/a/b-c_d.e~f"); |
| 411 | assert_eq!(percent_encode("/s?x=1&y=2"), "/s%3Fx%3D1%26y%3D2"); |
| 412 | assert_eq!(percent_encode("/a b"), "/a%20b"); |
| 413 | } |
| 414 | |
| 415 | |
| 416 | |
| 417 | #[tokio::test] |
| 418 | async fn an_org_never_passes_a_second_factor() { |
| 419 | let dir = tempfile::tempdir().unwrap(); |
| 420 | let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); |
| 421 | let key = [7u8; 32]; |
| 422 | let tahinli = store |
| 423 | .create_user("tahinli", None, "h", false) |
| 424 | .await |
| 425 | .unwrap(); |
| 426 | let org = store.create_org("acme", &tahinli.id).await.unwrap(); |
| 427 | let shared = forge_core::totp::new_secret(); |
| 428 | let sealed = forge_core::secret::seal(&key, &shared).unwrap(); |
| 429 | let code = forge_core::totp::code_at(&shared, forge_core::totp::step_for(unix_now())); |
| 430 | let recovery = forge_core::totp::recovery_code_hash("aaaa-bbbb"); |
| 431 | for id in [&org.id, &tahinli.id] { |
| 432 | store.set_totp_secret(id, &sealed).await.unwrap(); |
| 433 | store |
| 434 | .enable_totp(id, 0, std::slice::from_ref(&recovery)) |
| 435 | .await |
| 436 | .unwrap(); |
| 437 | } |
| 438 | |
| 439 | assert!( |
| 440 | !verify_second_factor(&store, &key, &org.id, &code) |
| 441 | .await |
| 442 | .unwrap() |
| 443 | ); |
| 444 | assert!( |
| 445 | !verify_second_factor(&store, &key, &org.id, "aaaa-bbbb") |
| 446 | .await |
| 447 | .unwrap() |
| 448 | ); |
| 449 | |
| 450 | assert!( |
| 451 | verify_second_factor(&store, &key, &tahinli.id, "aaaa-bbbb") |
| 452 | .await |
| 453 | .unwrap() |
| 454 | ); |
| 455 | } |
| 456 | } |