OXYGENHUB
# 417184c73f4e oxygenhub / crates / hub / src / auth / mod.rs
4.3 KiB · Rust · last changed Milestone 0.2: accounts and access 1 month ago source blame history raw
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
93
/// The session cookie's value for an account: `username.mac`.
94
pub fn session_value(key: &CookieKey, username: &str, session_salt: &str) -> String {
95
    format!("{username}.{}", key.mac(format!("session:{username}:{session_salt}").as_bytes()))
96
}
97
98
/// The CSRF token bound to a session value.
99
pub fn csrf_token(key: &CookieKey, session_value: &str) -> String {
100
    key.mac(format!("csrf:{session_value}").as_bytes())
101
}
102
103
pub const SESSION_COOKIE: &str = "oxyhub";
104
105
#[cfg(test)]
106
mod tests {
107
    use super::*;
108
109
    #[test]
110
    fn passwords_and_tokens() {
111
        let h = hash_password("correct horse battery").unwrap();
112
        assert!(verify_password(&h, "correct horse battery"));
113
        assert!(!verify_password(&h, "wrong"));
114
        assert!(!verify_password("garbage", "x"));
115
        assert!(password_ok("short").is_err());
116
        let (secret, hash) = new_token();
117
        assert!(secret.starts_with("oxyhub_"));
118
        assert_eq!(token_hash(&secret), hash);
119
        assert!(mac_equal("ab", "ab") && !mac_equal("ab", "ac") && !mac_equal("a", "ab"));
120
    }
121
122
    #[test]
123
    fn cookie_key_persists() {
124
        let dir = tempfile::tempdir().unwrap();
125
        let a = CookieKey::load_or_create(dir.path()).unwrap();
126
        let b = CookieKey::load_or_create(dir.path()).unwrap();
127
        assert_eq!(a.mac(b"x"), b.mac(b"x"));
128
        let v = session_value(&a, "andy", "salt");
129
        assert!(v.starts_with("andy."));
130
        assert_ne!(csrf_token(&a, &v), csrf_token(&a, "other"));
131
    }
132
}