OXYGENHUB
◆ proposal-list-fast oxygenhub / crates / hub / src / auth / mod.rs
5.2 KiB · Rust · last changed Sessions are server-side records: random ids, expiry, listed and ended per browser 20 days ago source blame history raw
19bb31ff Andy McCall ↶ 1
//! Authentication and authorisation (hub spec §5, §15.3): passwords,
2
//! session cookies, CSRF tokens, TOTP, personal access tokens, roles, and
3
//! the viewer extractor pages use.
4
5
pub mod roles;
6
pub mod totp;
7
pub mod viewer;
8
9
pub use roles::{Access, Role};
10
pub use viewer::{Viewer, ViewerAccount};
11
12
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
13
use argon2::Argon2;
14
use rand::RngCore;
15
use std::path::Path;
16
use subtle::ConstantTimeEq;
17
18
/// The key that signs cookies and CSRF tokens, kept in `<data>/keys/cookie.key`.
19
#[derive(Clone)]
20
pub struct CookieKey([u8; 32]);
21
22
impl CookieKey {
23
    pub fn load_or_create(keys: &Path) -> anyhow::Result<CookieKey> {
24
        std::fs::create_dir_all(keys)?;
25
        let path = keys.join("cookie.key");
26
        if let Ok(bytes) = std::fs::read(&path) {
27
            if bytes.len() == 32 {
28
                return Ok(CookieKey(bytes.try_into().unwrap()));
29
            }
30
        }
31
        let mut k = [0u8; 32];
32
        rand::rngs::OsRng.fill_bytes(&mut k);
33
        std::fs::write(&path, k)?;
34
        #[cfg(unix)]
35
        {
36
            use std::os::unix::fs::PermissionsExt;
37
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
38
        }
39
        Ok(CookieKey(k))
40
    }
41
42
    /// Keyed BLAKE3 over `message`, as hex.
43
    pub fn mac(&self, message: &[u8]) -> String {
44
        hex::encode(blake3::keyed_hash(&self.0, message).as_bytes())
45
    }
46
}
47
48
/// Constant-time equality of two hex MACs.
49
pub fn mac_equal(a: &str, b: &str) -> bool {
50
    a.len() == b.len() && a.as_bytes().ct_eq(b.as_bytes()).into()
51
}
52
53
pub fn hash_password(password: &str) -> anyhow::Result<String> {
54
    let salt = SaltString::generate(&mut rand::rngs::OsRng);
55
    Ok(Argon2::default().hash_password(password.as_bytes(), &salt).map_err(|e| anyhow::anyhow!("{e}"))?.to_string())
56
}
57
58
pub fn verify_password(hash: &str, password: &str) -> bool {
59
    match PasswordHash::new(hash) {
60
        Ok(parsed) => Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok(),
61
        Err(_) => false,
62
    }
63
}
64
65
/// A password policy that is honest rather than theatrical: length only.
66
pub fn password_ok(password: &str) -> Result<(), &'static str> {
67
    if password.chars().count() < 10 {
68
        return Err("a password is at least 10 characters");
69
    }
70
    if password.len() > 256 {
71
        return Err("a password is at most 256 bytes");
72
    }
73
    Ok(())
74
}
75
76
pub fn random_hex(bytes: usize) -> String {
77
    let mut b = vec![0u8; bytes];
78
    rand::rngs::OsRng.fill_bytes(&mut b);
79
    hex::encode(b)
80
}
81
82
/// A personal access token: `oxyhub_` plus 32 random bytes as hex. Stored
83
/// as its BLAKE3 hash.
84
pub fn new_token() -> (String, String) {
85
    let secret = format!("oxyhub_{}", random_hex(32));
86
    (secret.clone(), token_hash(&secret))
87
}
88
89
pub fn token_hash(secret: &str) -> String {
90
    hex::encode(blake3::hash(secret.as_bytes()).as_bytes())
91
}
92
0024ccb1 Andy McCall ↶ 93
/// A new session id for the cookie (oxygenhub#223): random, and kept on
94
/// the server only as its [`token_hash`].
95
pub fn new_session_id() -> String {
96
    random_hex(32)
19bb31ff Andy McCall ↶ 97
}
98
bff9106e Andy McCall ↶ 99
/// Proof, for the code step of a sign-in with two-factor authentication,
100
/// that `username` gave the right password: `UNTIL.MAC`, good until `until`
101
/// (ms) and void as soon as the account's session salt changes (a new
102
/// password, or everyone signed out), so the code step need not ask for
103
/// the password again.
104
pub fn pending_login(key: &CookieKey, username: &str, session_salt: &str, until: i64) -> String {
105
    format!("{until}.{}", key.mac(format!("pending-login:{username}:{session_salt}:{until}").as_bytes()))
106
}
107
108
/// Whether `token` is a [`pending_login`] for this account still in time.
109
pub fn pending_login_ok(key: &CookieKey, username: &str, session_salt: &str, token: &str, now: i64) -> bool {
110
    let Some((until, _)) = token.split_once('.') else { return false };
111
    let Ok(until) = until.parse::<i64>() else { return false };
112
    until > now && mac_equal(token, &pending_login(key, username, session_salt, until))
113
}
114
19bb31ff Andy McCall ↶ 115
/// The CSRF token bound to a session value.
116
pub fn csrf_token(key: &CookieKey, session_value: &str) -> String {
117
    key.mac(format!("csrf:{session_value}").as_bytes())
118
}
119
120
pub const SESSION_COOKIE: &str = "oxyhub";
121
122
#[cfg(test)]
123
mod tests {
124
    use super::*;
125
126
    #[test]
127
    fn passwords_and_tokens() {
128
        let h = hash_password("correct horse battery").unwrap();
129
        assert!(verify_password(&h, "correct horse battery"));
130
        assert!(!verify_password(&h, "wrong"));
131
        assert!(!verify_password("garbage", "x"));
132
        assert!(password_ok("short").is_err());
133
        let (secret, hash) = new_token();
134
        assert!(secret.starts_with("oxyhub_"));
135
        assert_eq!(token_hash(&secret), hash);
136
        assert!(mac_equal("ab", "ab") && !mac_equal("ab", "ac") && !mac_equal("a", "ab"));
137
    }
138
139
    #[test]
140
    fn cookie_key_persists() {
141
        let dir = tempfile::tempdir().unwrap();
142
        let a = CookieKey::load_or_create(dir.path()).unwrap();
143
        let b = CookieKey::load_or_create(dir.path()).unwrap();
144
        assert_eq!(a.mac(b"x"), b.mac(b"x"));
0024ccb1 Andy McCall ↶ 145
        let v = new_session_id();
146
        assert_eq!(v.len(), 64);
147
        assert_ne!(v, new_session_id());
19bb31ff Andy McCall ↶ 148
        assert_ne!(csrf_token(&a, &v), csrf_token(&a, "other"));
149
    }
150
}