OXYGENHUB
◆ main oxygenhub / crates / hub / src / auth / mod.rs
5.2 KiB · Rust · last changed A phone as the second factor: Keystore keys approve sign-ins by the number the browser shows, and the sudo step asks a stale session again before sensitive changes (closes #356) 3 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
a22e4aec Andy McCall ↶ 5
pub mod phone;
19bb31ff Andy McCall ↶ 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 {
24
    pub fn load_or_create(keys: &Path) -> anyhow::Result<CookieKey> {
25
        std::fs::create_dir_all(keys)?;
26
        let path = keys.join("cookie.key");
27
        if let Ok(bytes) = std::fs::read(&path) {
28
            if bytes.len() == 32 {
29
                return Ok(CookieKey(bytes.try_into().unwrap()));
30
            }
31
        }
32
        let mut k = [0u8; 32];
33
        rand::rngs::OsRng.fill_bytes(&mut k);
34
        std::fs::write(&path, k)?;
35
        #[cfg(unix)]
36
        {
37
            use std::os::unix::fs::PermissionsExt;
38
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
39
        }
40
        Ok(CookieKey(k))
41
    }
42
43
    /// Keyed BLAKE3 over `message`, as hex.
44
    pub fn mac(&self, message: &[u8]) -> String {
45
        hex::encode(blake3::keyed_hash(&self.0, message).as_bytes())
46
    }
47
}
48
49
/// Constant-time equality of two hex MACs.
50
pub fn mac_equal(a: &str, b: &str) -> bool {
51
    a.len() == b.len() && a.as_bytes().ct_eq(b.as_bytes()).into()
52
}
53
54
pub fn hash_password(password: &str) -> anyhow::Result<String> {
55
    let salt = SaltString::generate(&mut rand::rngs::OsRng);
56
    Ok(Argon2::default().hash_password(password.as_bytes(), &salt).map_err(|e| anyhow::anyhow!("{e}"))?.to_string())
57
}
58
59
pub fn verify_password(hash: &str, password: &str) -> bool {
60
    match PasswordHash::new(hash) {
61
        Ok(parsed) => Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok(),
62
        Err(_) => false,
63
    }
64
}
65
66
/// A password policy that is honest rather than theatrical: length only.
67
pub fn password_ok(password: &str) -> Result<(), &'static str> {
68
    if password.chars().count() < 10 {
69
        return Err("a password is at least 10 characters");
70
    }
71
    if password.len() > 256 {
72
        return Err("a password is at most 256 bytes");
73
    }
74
    Ok(())
75
}
76
77
pub fn random_hex(bytes: usize) -> String {
78
    let mut b = vec![0u8; bytes];
79
    rand::rngs::OsRng.fill_bytes(&mut b);
80
    hex::encode(b)
81
}
82
83
/// A personal access token: `oxyhub_` plus 32 random bytes as hex. Stored
84
/// as its BLAKE3 hash.
85
pub fn new_token() -> (String, String) {
86
    let secret = format!("oxyhub_{}", random_hex(32));
87
    (secret.clone(), token_hash(&secret))
88
}
89
90
pub fn token_hash(secret: &str) -> String {
91
    hex::encode(blake3::hash(secret.as_bytes()).as_bytes())
92
}
93
0024ccb1 Andy McCall ↶ 94
/// A new session id for the cookie (oxygenhub#223): random, and kept on
95
/// the server only as its [`token_hash`].
96
pub fn new_session_id() -> String {
97
    random_hex(32)
19bb31ff Andy McCall ↶ 98
}
99
bff9106e Andy McCall ↶ 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.
105
pub fn pending_login(key: &CookieKey, username: &str, session_salt: &str, until: i64) -> String {
106
    format!("{until}.{}", key.mac(format!("pending-login:{username}:{session_salt}:{until}").as_bytes()))
107
}
108
109
/// Whether `token` is a [`pending_login`] for this account still in time.
110
pub fn pending_login_ok(key: &CookieKey, username: &str, session_salt: &str, token: &str, now: i64) -> bool {
111
    let Some((until, _)) = token.split_once('.') else { return false };
112
    let Ok(until) = until.parse::<i64>() else { return false };
113
    until > now && mac_equal(token, &pending_login(key, username, session_salt, until))
114
}
115
19bb31ff Andy McCall ↶ 116
/// The CSRF token bound to a session value.
117
pub fn csrf_token(key: &CookieKey, session_value: &str) -> String {
118
    key.mac(format!("csrf:{session_value}").as_bytes())
119
}
120
121
pub const SESSION_COOKIE: &str = "oxyhub";
122
123
#[cfg(test)]
124
mod tests {
125
    use super::*;
126
127
    #[test]
128
    fn passwords_and_tokens() {
129
        let h = hash_password("correct horse battery").unwrap();
130
        assert!(verify_password(&h, "correct horse battery"));
131
        assert!(!verify_password(&h, "wrong"));
132
        assert!(!verify_password("garbage", "x"));
133
        assert!(password_ok("short").is_err());
134
        let (secret, hash) = new_token();
135
        assert!(secret.starts_with("oxyhub_"));
136
        assert_eq!(token_hash(&secret), hash);
137
        assert!(mac_equal("ab", "ab") && !mac_equal("ab", "ac") && !mac_equal("a", "ab"));
138
    }
139
140
    #[test]
141
    fn cookie_key_persists() {
142
        let dir = tempfile::tempdir().unwrap();
143
        let a = CookieKey::load_or_create(dir.path()).unwrap();
144
        let b = CookieKey::load_or_create(dir.path()).unwrap();
145
        assert_eq!(a.mac(b"x"), b.mac(b"x"));
0024ccb1 Andy McCall ↶ 146
        let v = new_session_id();
147
        assert_eq!(v.len(), 64);
148
        assert_ne!(v, new_session_id());
19bb31ff Andy McCall ↶ 149
        assert_ne!(csrf_token(&a, &v), csrf_token(&a, "other"));
150
    }
151
}