//! Sessions in PostgreSQL, pending logins in memory. //! //! A session survives a restart (deploys do not sign anyone out). The table //! holds the SHA-256 of the cookie's value, never the value itself. use std::collections::HashMap; use std::sync::Mutex; use std::time::{Duration, Instant}; use anyhow::Result; use axum::http::HeaderMap; use axum::http::header::COOKIE; use serde::Serialize; use sqlx::PgPool; use crate::oidc::random_token; /// `__Host-`: Secure, Path=/ and no Domain, so no other name under the /// app's domain can set or read it. pub const SESSION_COOKIE: &str = "__Host-visa"; /// Binds a login in progress to the browser that started it. pub const FLOW_COOKIE: &str = "__Host-visa-login"; pub const SESSION_TTL: Duration = Duration::from_secs(12 * 3600); pub const FLOW_TTL: Duration = Duration::from_secs(600); const MAX_FLOWS: usize = 1000; #[derive(Clone, Debug, Serialize)] pub struct User { pub login: String, pub name: String, /// Local development without login. pub local: bool, /// The session's token for forms (CSRF); templates get it as `csrf`. #[serde(skip)] pub csrf: String, } impl User { pub fn local(csrf: &str) -> User { User { login: "local".into(), name: "Local development".into(), local: true, csrf: csrf.to_string(), } } } #[derive(Clone, Debug)] pub struct Flow { pub state: String, pub nonce: String, pub verifier: String, /// Where to go after the login. pub next: String, created: Instant, } #[derive(Default)] pub struct Flows { flows: Mutex>, } impl Flows { /// A new login; None when too many are pending (someone hammering /login). pub fn start(&self, next: String) -> Option { let mut flows = self.flows.lock().unwrap_or_else(|e| e.into_inner()); flows.retain(|_, f| f.created.elapsed() < FLOW_TTL); if flows.len() >= MAX_FLOWS { return None; } let flow = Flow { state: random_token(), nonce: random_token(), verifier: random_token(), next, created: Instant::now(), }; flows.insert(flow.state.clone(), flow.clone()); Some(flow) } /// The pending login for this state, once. pub fn take(&self, state: &str) -> Option { let mut flows = self.flows.lock().unwrap_or_else(|e| e.into_inner()); flows .remove(state) .filter(|f| f.created.elapsed() < FLOW_TTL) } } fn hash(id: &str) -> Vec { ring::digest::digest(&ring::digest::SHA256, id.as_bytes()) .as_ref() .to_vec() } /// Creates a session; returns the cookie's value. pub async fn create(db: &PgPool, login: &str, name: &str) -> Result { let id = random_token(); let ttl = chrono::TimeDelta::seconds(SESSION_TTL.as_secs() as i64); sqlx::query("DELETE FROM sessions WHERE expires_at < now()") .execute(db) .await?; sqlx::query( "INSERT INTO sessions (id_hash, login, name, csrf, expires_at) \ VALUES ($1, $2, $3, $4, now() + $5)", ) .bind(hash(&id)) .bind(login) .bind(name) .bind(random_token()) .bind(ttl) .execute(db) .await?; Ok(id) } pub async fn get(db: &PgPool, id: &str) -> Result> { let row: Option<(String, String, String)> = sqlx::query_as( "SELECT login, name, csrf FROM sessions WHERE id_hash = $1 AND expires_at > now()", ) .bind(hash(id)) .fetch_optional(db) .await?; Ok(row.map(|(login, name, csrf)| User { login, name, local: false, csrf, })) } pub async fn remove(db: &PgPool, id: &str) -> Result<()> { sqlx::query("DELETE FROM sessions WHERE id_hash = $1") .bind(hash(id)) .execute(db) .await?; Ok(()) } pub fn cookie_value(headers: &HeaderMap, name: &str) -> Option { for value in headers.get_all(COOKIE) { let Ok(text) = value.to_str() else { continue; }; for part in text.split(';') { if let Some((k, v)) = part.trim().split_once('=') && k == name { return Some(v.to_string()); } } } None } pub fn set_cookie(name: &str, value: &str, max_age: Duration) -> String { format!( "{name}={value}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age={}", max_age.as_secs() ) } pub fn clear_cookie(name: &str) -> String { format!("{name}=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0") } /// Compares two tokens in time independent of where they differ. pub fn same_token(a: &str, b: &str) -> bool { let (a, b) = (a.as_bytes(), b.as_bytes()); if a.len() != b.len() || a.is_empty() { return false; } a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 } #[cfg(test)] mod tests { use super::*; use axum::http::HeaderValue; #[test] fn flows_are_single_use() { let f = Flows::default(); let flow = f.start("/people/3".into()).unwrap(); assert_eq!(f.take(&flow.state).unwrap().next, "/people/3"); assert!(f.take(&flow.state).is_none()); } #[test] fn cookies_and_tokens() { let mut h = HeaderMap::new(); h.append(COOKIE, HeaderValue::from_static("a=1; __Host-visa=abc")); assert_eq!(cookie_value(&h, SESSION_COOKIE).as_deref(), Some("abc")); assert_eq!(cookie_value(&h, FLOW_COOKIE), None); assert!(set_cookie(SESSION_COOKIE, "x", SESSION_TTL).contains("Max-Age=43200")); assert!(same_token("abc", "abc")); assert!(!same_token("abc", "abd")); assert!(!same_token("abc", "ab")); assert!(!same_token("", "")); assert_eq!(hash("x").len(), 32); } }