OXYGENHUB
◆ v0.5.1 oxygenhub / crates / hub / src / auth / mod.rs
5.2 KiB · Rust · last changed Notifications that reach you, and 2FA without the password twice 22 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
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
bff9106e Andy McCall ↶ 98
/// Proof, for the code step of a sign-in with two-factor authentication,
99
/// that `username` gave the right password: `UNTIL.MAC`, good until `until`
100
/// (ms) and void as soon as the account's session salt changes (a new
101
/// password, or everyone signed out), so the code step need not ask for
102
/// the password again.
103
pub fn pending_login(key: &CookieKey, username: &str, session_salt: &str, until: i64) -> String {
104
    format!("{until}.{}", key.mac(format!("pending-login:{username}:{session_salt}:{until}").as_bytes()))
105
}
106
107
/// Whether `token` is a [`pending_login`] for this account still in time.
108
pub fn pending_login_ok(key: &CookieKey, username: &str, session_salt: &str, token: &str, now: i64) -> bool {
109
    let Some((until, _)) = token.split_once('.') else { return false };
110
    let Ok(until) = until.parse::<i64>() else { return false };
111
    until > now && mac_equal(token, &pending_login(key, username, session_salt, until))
112
}
113
19bb31ff Andy McCall ↶ 114
/// The CSRF token bound to a session value.
115
pub fn csrf_token(key: &CookieKey, session_value: &str) -> String {
116
    key.mac(format!("csrf:{session_value}").as_bytes())
117
}
118
119
pub const SESSION_COOKIE: &str = "oxyhub";
120
121
#[cfg(test)]
122
mod tests {
123
    use super::*;
124
125
    #[test]
126
    fn passwords_and_tokens() {
127
        let h = hash_password("correct horse battery").unwrap();
128
        assert!(verify_password(&h, "correct horse battery"));
129
        assert!(!verify_password(&h, "wrong"));
130
        assert!(!verify_password("garbage", "x"));
131
        assert!(password_ok("short").is_err());
132
        let (secret, hash) = new_token();
133
        assert!(secret.starts_with("oxyhub_"));
134
        assert_eq!(token_hash(&secret), hash);
135
        assert!(mac_equal("ab", "ab") && !mac_equal("ab", "ac") && !mac_equal("a", "ab"));
136
    }
137
138
    #[test]
139
    fn cookie_key_persists() {
140
        let dir = tempfile::tempdir().unwrap();
141
        let a = CookieKey::load_or_create(dir.path()).unwrap();
142
        let b = CookieKey::load_or_create(dir.path()).unwrap();
143
        assert_eq!(a.mac(b"x"), b.mac(b"x"));
144
        let v = session_value(&a, "andy", "salt");
145
        assert!(v.starts_with("andy."));
146
        assert_ne!(csrf_token(&a, &v), csrf_token(&a, "other"));
147
    }
148
}