OXYGENHUB

Coverage / crates/hub/src/auth/mod.rs 96.5%

83 of 86 lines run, 26 of 30 functions · run #542 on main · run missed

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 phone;
6
pub mod roles;
7
pub mod totp;
8
pub mod viewer;
9
10
pub use roles::{Access, Role};
11
pub use viewer::{Viewer, ViewerAccount};
12
13
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
14
use argon2::Argon2;
15
use rand::RngCore;
16
use std::path::Path;
17
use subtle::ConstantTimeEq;
18
19
/// The key that signs cookies and CSRF tokens, kept in `<data>/keys/cookie.key`.
20
#[derive(Clone)]
21
pub struct CookieKey([u8; 32]);
22
23
impl CookieKey {
24209×
    pub fn load_or_create(keys: &Path) -> anyhow::Result<CookieKey> {
25209×
        std::fs::create_dir_all(keys)?;
26209×
        let path = keys.join("cookie.key");
27209×
        if let Ok(bytes) = std::fs::read(&path) {
281×
            if bytes.len() == 32 {
291×
                return Ok(CookieKey(bytes.try_into().unwrap()));
300×
            }
31208×
        }
32208×
        let mut k = [0u8; 32];
33208×
        rand::rngs::OsRng.fill_bytes(&mut k);
34208×
        std::fs::write(&path, k)?;
35
        #[cfg(unix)]
36
        {
37
            use std::os::unix::fs::PermissionsExt;
38208×
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
39
        }
40208×
        Ok(CookieKey(k))
41209×
    }
42
43
    /// Keyed BLAKE3 over `message`, as hex.
441435×
    pub fn mac(&self, message: &[u8]) -> String {
451435×
        hex::encode(blake3::keyed_hash(&self.0, message).as_bytes())
461435×
    }
47
}
48
49
/// Constant-time equality of two hex MACs.
502077×
pub fn mac_equal(a: &str, b: &str) -> bool {
512077×
    a.len() == b.len() && a.as_bytes().ct_eq(b.as_bytes()).into()
522077×
}
53
54140×
pub fn hash_password(password: &str) -> anyhow::Result<String> {
55140×
    let salt = SaltString::generate(&mut rand::rngs::OsRng);
56140×
    Ok(Argon2::default().hash_password(password.as_bytes(), &salt).map_err(|e| anyhow::anyhow!("{e}"))?.to_string())
57140×
}
58
5923×
pub fn verify_password(hash: &str, password: &str) -> bool {
6023×
    match PasswordHash::new(hash) {
6122×
        Ok(parsed) => Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok(),
621×
        Err(_) => false,
63
    }
6423×
}
65
66
/// A password policy that is honest rather than theatrical: length only.
67143×
pub fn password_ok(password: &str) -> Result<(), &'static str> {
68143×
    if password.chars().count() < 10 {
692×
        return Err("a password is at least 10 characters");
70141×
    }
71141×
    if password.len() > 256 {
720×
        return Err("a password is at most 256 bytes");
73141×
    }
74141×
    Ok(())
75143×
}
76
77954×
pub fn random_hex(bytes: usize) -> String {
78954×
    let mut b = vec![0u8; bytes];
79954×
    rand::rngs::OsRng.fill_bytes(&mut b);
80954×
    hex::encode(b)
81954×
}
82
83
/// A personal access token: `oxyhub_` plus 32 random bytes as hex. Stored
84
/// as its BLAKE3 hash.
8554×
pub fn new_token() -> (String, String) {
8654×
    let secret = format!("oxyhub_{}", random_hex(32));
8754×
    (secret.clone(), token_hash(&secret))
8854×
}
89
904161×
pub fn token_hash(secret: &str) -> String {
914161×
    hex::encode(blake3::hash(secret.as_bytes()).as_bytes())
924161×
}
93
94
/// A new session id for the cookie (oxygenhub#223): random, and kept on
95
/// the server only as its [`token_hash`].
96150×
pub fn new_session_id() -> String {
97150×
    random_hex(32)
98150×
}
99
100
/// Proof, for the code step of a sign-in with two-factor authentication,
101
/// that `username` gave the right password: `UNTIL.MAC`, good until `until`
102
/// (ms) and void as soon as the account's session salt changes (a new
103
/// password, or everyone signed out), so the code step need not ask for
104
/// the password again.
10533×
pub fn pending_login(key: &CookieKey, username: &str, session_salt: &str, until: i64) -> String {
10633×
    format!("{until}.{}", key.mac(format!("pending-login:{username}:{session_salt}:{until}").as_bytes()))
10733×
}
108
109
/// Whether `token` is a [`pending_login`] for this account still in time.
1109×
pub fn pending_login_ok(key: &CookieKey, username: &str, session_salt: &str, token: &str, now: i64) -> bool {
1119×
    let Some((until, _)) = token.split_once('.') else { return false };
1129×
    let Ok(until) = until.parse::<i64>() else { return false };
1139×
    until > now && mac_equal(token, &pending_login(key, username, session_salt, until))
1149×
}
115
116
/// The CSRF token bound to a session value.
1171319×
pub fn csrf_token(key: &CookieKey, session_value: &str) -> String {
1181319×
    key.mac(format!("csrf:{session_value}").as_bytes())
1191319×
}
120
121
pub const SESSION_COOKIE: &str = "oxyhub";
122
123
#[cfg(test)]
124
mod tests {
125
    use super::*;
126
127
    #[test]
1281×
    fn passwords_and_tokens() {
1291×
        let h = hash_password("correct horse battery").unwrap();
1301×
        assert!(verify_password(&h, "correct horse battery"));
1311×
        assert!(!verify_password(&h, "wrong"));
1321×
        assert!(!verify_password("garbage", "x"));
1331×
        assert!(password_ok("short").is_err());
1341×
        let (secret, hash) = new_token();
1351×
        assert!(secret.starts_with("oxyhub_"));
1361×
        assert_eq!(token_hash(&secret), hash);
1371×
        assert!(mac_equal("ab", "ab") && !mac_equal("ab", "ac") && !mac_equal("a", "ab"));
1381×
    }
139
140
    #[test]
1411×
    fn cookie_key_persists() {
1421×
        let dir = tempfile::tempdir().unwrap();
1431×
        let a = CookieKey::load_or_create(dir.path()).unwrap();
1441×
        let b = CookieKey::load_or_create(dir.path()).unwrap();
1451×
        assert_eq!(a.mac(b"x"), b.mac(b"x"));
1461×
        let v = new_session_id();
1471×
        assert_eq!(v.len(), 64);
1481×
        assert_ne!(v, new_session_id());
1491×
        assert_ne!(csrf_token(&a, &v), csrf_token(&a, "other"));
1501×
    }
151
}