summaryrefslogtreecommitdiffstats
path: root/src/http/auth.rs
blob: 0f174ef76a731aedef585a786fb235e391f48153 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::OnceLock;

use crate::hash;

static SESSIONS: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();

fn sessions() -> &'static Mutex<HashMap<String, bool>> {
    SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
}

fn random_hex() -> Option<String> {
    use std::io::Read;
    let mut buf = [0u8; 32];
    let mut f = std::fs::File::open("/dev/urandom").ok()?;
    f.read_exact(&mut buf).ok()?;
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let salt = format!("{:?}", (buf, nanos, std::process::id(), counter()));
    Some(hash::hex(salt.as_bytes()))
}

fn counter() -> u64 {
    static C: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    C.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

pub(crate) fn new_session() -> Option<String> {
    let sid = random_hex()?;
    if let Ok(mut s) = sessions().lock() {
        s.insert(sid.clone(), false);
    }
    Some(sid)
}

pub(crate) fn is_valid_session(sid: &str) -> bool {
    sessions().lock().map(|s| s.contains_key(sid)).unwrap_or(false)
}

pub(crate) fn authenticate(sid: &str) {
    if let Ok(mut s) = sessions().lock() {
        if let Some(authenticated) = s.get_mut(sid) {
            *authenticated = true;
        }
    }
}

pub(crate) fn is_authenticated(sid: &str) -> bool {
    sessions().lock().map(|s| s.get(sid).copied().unwrap_or(false)).unwrap_or(false)
}

pub(crate) fn drop_session(sid: &str) {
    if let Ok(mut s) = sessions().lock() {
        s.remove(sid);
    }
}

pub(crate) fn csrf_token(sid: &str) -> String {
    hash::hex(format!("csrf|{sid}").as_bytes())[..32].to_string()
}

pub(crate) fn csrf_ok(sid: &str, token: &str) -> bool {
    !token.is_empty() && is_valid_session(sid) && constant_time_eq(&csrf_token(sid), token)
}

fn constant_time_eq(a: &str, b: &str) -> bool {
    let (a, b) = (a.as_bytes(), b.as_bytes());
    if a.len() != b.len() {
        return false;
    }
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

pub(crate) fn parse_cookies(header: &str) -> Vec<(String, String)> {
    header
        .split(';')
        .filter_map(|p| {
            let p = p.trim();
            let (k, v) = p.split_once('=')?;
            Some((k.trim().to_string(), v.trim().to_string()))
        })
        .collect()
}

pub(crate) fn password_ok(cfg: &crate::config::Config, given: &str) -> bool {
    cfg.password.is_empty() || constant_time_eq(&cfg.password, given)
}

pub(crate) fn auth_required(cfg: &crate::config::Config) -> bool {
    !cfg.password.is_empty()
}