diff options
Diffstat (limited to 'src/http/auth.rs')
| -rw-r--r-- | src/http/auth.rs | 40 |
1 files changed, 34 insertions, 6 deletions
diff --git a/src/http/auth.rs b/src/http/auth.rs index 9186f0e..3d05cab 100644 --- a/src/http/auth.rs +++ b/src/http/auth.rs @@ -5,17 +5,26 @@ //! opaque random id held in memory; the CSRF token is derived from it, so a //! cross-site form cannot produce one it has not seen, and there is no token //! table to keep in step with the sessions. +//! +//! **The sid is the credential.** A sid is minted for anonymous visitors too, +//! because the CSRF token has to be derivable before anyone has typed a +//! password; what the password buys is the `authenticated` flag on one sid. +//! Nothing else in the request proves who you are, which is why there is no +//! separate "logged in" cookie to forge. -use std::collections::HashSet; +use std::collections::HashMap; use std::sync::Mutex; use std::sync::OnceLock; use crate::hash; -static SESSIONS: OnceLock<Mutex<HashSet<String>>> = OnceLock::new(); +/// Live sids and whether each has passed the password gate. One map, so the +/// two facts cannot drift apart: dropping a session removes its authentication +/// with it. +static SESSIONS: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new(); -fn sessions() -> &'static Mutex<HashSet<String>> { - SESSIONS.get_or_init(|| Mutex::new(HashSet::new())) +fn sessions() -> &'static Mutex<HashMap<String, bool>> { + SESSIONS.get_or_init(|| Mutex::new(HashMap::new())) } /// Random hex token from the system RNG (`/dev/urandom` through our hash). @@ -39,16 +48,35 @@ fn counter() -> u64 { C.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } +/// Mint an anonymous session: enough for a CSRF token, not enough to see a +/// single page when a password is set. pub fn new_session() -> String { let sid = random_hex(); if let Ok(mut s) = sessions().lock() { - s.insert(sid.clone()); + s.insert(sid.clone(), false); } sid } pub fn is_valid_session(sid: &str) -> bool { - sessions().lock().map(|s| s.contains(sid)).unwrap_or(false) + sessions().lock().map(|s| s.contains_key(sid)).unwrap_or(false) +} + +/// Mark a session as having passed the password gate. Only ever called with a +/// sid this process minted, and it cannot mint one: an unknown sid stays +/// unknown rather than being inserted as a side effect of a login attempt. +pub fn authenticate(sid: &str) { + if let Ok(mut s) = sessions().lock() { + if let Some(authenticated) = s.get_mut(sid) { + *authenticated = true; + } + } +} + +/// The gate's whole question: is this sid one we issued *and* did someone type +/// the password into a form on this session? +pub fn is_authenticated(sid: &str) -> bool { + sessions().lock().map(|s| s.get(sid).copied().unwrap_or(false)).unwrap_or(false) } pub fn drop_session(sid: &str) { |
