glacier-web 0.1.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! The pieces `glacier generate authentication` builds on: password
//! hashing, session tokens and bearer tokens. The generated app code (a
//! `User` and `Session` model, a sessions controller and an
//! `Authentication` middleware) is yours to read and change, as with Rails'
//! and Phoenix's generators.
//!
//! Passwords are hashed with Argon2id; bcrypt hashes (from Devise or
//! `has_secure_password`) verify too, so an existing app's users can sign
//! in. Session tokens are 32 random bytes;
//! the client holds the token and the database only its SHA-256 digest, so
//! a leaked database can't be used to sign in.

use argon2::Argon2;
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use sha2::{Digest, Sha256};

use crate::context::Context;

/// The password's Argon2id hash, in PHC string format, for a
/// `password_digest` column.
///
/// # Panics
///
/// If the system's random number generator fails.
pub fn hash_password(password: &str) -> String {
    let mut salt = [0u8; 16];
    getrandom::fill(&mut salt).expect("the system's random number generator failed");
    let salt = SaltString::encode_b64(&salt).expect("16 bytes is a valid salt");
    Argon2::default()
        .hash_password(password.as_bytes(), &salt)
        .expect("Argon2 hashes any password")
        .to_string()
}

/// Whether `password` matches `digest`. With no digest (no such user) it
/// still spends the time of a check, so response times don't reveal which
/// email addresses have accounts.
pub fn verify_password(password: &str, digest: Option<&str>) -> bool {
    static DUMMY: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    let (digest, real) = match digest {
        Some(digest) => (digest, true),
        None => (
            DUMMY
                .get_or_init(|| hash_password("dummy password"))
                .as_str(),
            false,
        ),
    };
    // Devise and has_secure_password store bcrypt: `$2a$10$…`.
    if ["$2a$", "$2b$", "$2y$"]
        .iter()
        .any(|v| digest.starts_with(v))
    {
        return real && bcrypt::verify(password, digest).unwrap_or(false);
    }
    let Ok(parsed) = PasswordHash::new(digest) else {
        return false;
    };
    let matches = Argon2::default()
        .verify_password(password.as_bytes(), &parsed)
        .is_ok();
    real && matches
}

/// A new random token for a session (or a password reset link): 32 bytes,
/// base64url-encoded.
///
/// # Panics
///
/// If the system's random number generator fails.
pub fn new_token() -> String {
    let mut bytes = [0u8; 32];
    getrandom::fill(&mut bytes).expect("the system's random number generator failed");
    URL_SAFE_NO_PAD.encode(bytes)
}

/// The SHA-256 digest of a token, hex-encoded: what the database stores.
pub fn token_digest(token: &str) -> String {
    Sha256::digest(token.as_bytes())
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// The token from an `Authorization: Bearer <token>` header.
pub fn bearer_token(ctx: &Context) -> Option<&str> {
    let header = ctx.header(http::header::AUTHORIZATION)?;
    let (scheme, token) = header.split_once(' ')?;
    let token = token.trim();
    (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token)
}

/// JSON Web Tokens signed with HMAC-SHA256 (`HS256`), as Rails apps using
/// the `jwt` gem issue them.
pub mod jwt {
    use base64::Engine;
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use hmac::{Hmac, Mac};
    use serde_json::{Map, Value};
    use sha2::Sha256;

    /// Why a token was rejected.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum JwtError {
        Malformed,
        Algorithm,
        Signature,
        Expired,
    }

    impl std::fmt::Display for JwtError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str(match self {
                JwtError::Malformed => "malformed token",
                JwtError::Algorithm => "token not signed with HS256",
                JwtError::Signature => "invalid token signature",
                JwtError::Expired => "token expired",
            })
        }
    }

    impl std::error::Error for JwtError {}

    fn mac(secret: &[u8]) -> Hmac<Sha256> {
        Hmac::<Sha256>::new_from_slice(secret).expect("HMAC takes a key of any length")
    }

    /// A token carrying `claims` (`{"user_id": 1, "exp": …}`), keys in
    /// the order given.
    pub fn encode(claims: &Map<String, Value>, secret: &[u8]) -> String {
        let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256"}"#);
        let payload = URL_SAFE_NO_PAD.encode(Value::Object(claims.clone()).to_string());
        let signing_input = format!("{header}.{payload}");
        let mut mac = mac(secret);
        mac.update(signing_input.as_bytes());
        let signature = URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes());
        format!("{signing_input}.{signature}")
    }

    /// The claims of a token signed with `secret`, after checking its
    /// signature (in constant time) and its `exp`, if it has one.
    pub fn decode(token: &str, secret: &[u8]) -> Result<Map<String, Value>, JwtError> {
        let mut parts = token.trim().split('.');
        let (Some(header), Some(payload), Some(signature), None) =
            (parts.next(), parts.next(), parts.next(), parts.next())
        else {
            return Err(JwtError::Malformed);
        };
        let json = |part: &str| -> Result<Map<String, Value>, JwtError> {
            let bytes = URL_SAFE_NO_PAD
                .decode(part)
                .map_err(|_| JwtError::Malformed)?;
            match serde_json::from_slice(&bytes) {
                Ok(Value::Object(map)) => Ok(map),
                _ => Err(JwtError::Malformed),
            }
        };
        if json(header)?.get("alg").and_then(Value::as_str) != Some("HS256") {
            return Err(JwtError::Algorithm);
        }
        let signature = URL_SAFE_NO_PAD
            .decode(signature)
            .map_err(|_| JwtError::Malformed)?;
        let mut mac = mac(secret);
        mac.update(format!("{header}.{payload}").as_bytes());
        mac.verify_slice(&signature)
            .map_err(|_| JwtError::Signature)?;
        let claims = json(payload)?;
        if let Some(exp) = claims.get("exp") {
            let exp = exp.as_i64().ok_or(JwtError::Malformed)?;
            if exp <= chrono::Utc::now().timestamp() {
                return Err(JwtError::Expired);
            }
        }
        Ok(claims)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hashes_and_verifies_passwords() {
        let digest = hash_password("correct horse");
        assert!(digest.starts_with("$argon2id$"));
        assert_ne!(digest, hash_password("correct horse"), "salted");
        assert!(verify_password("correct horse", Some(&digest)));
        assert!(!verify_password("wrong horse", Some(&digest)));
        assert!(!verify_password("correct horse", None));
        assert!(!verify_password("x", Some("not a hash")));
        // Ruby's BCrypt::Password.create("secret", cost: 4).
        let devise = "$2a$04$KJY25RprEuJvbxVtp0EL6OAwC3ZAHpva.goKBL6bcCq6/HLxIEkUu";
        assert!(
            verify_password("secret", Some(devise)),
            "bcrypt hashes are checked as bcrypt"
        );
        assert!(!verify_password("wrong", Some(devise)));
    }

    #[test]
    fn signs_and_checks_json_web_tokens() {
        use jwt::{JwtError, decode, encode};
        // As Ruby's `JWT.encode({user_id: 1, email: "a@b.c", exp: 4102444800}, "s", "HS256")`.
        let ruby = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJlbWFpbCI6ImFAYi5jIiwiZXhwIjo0MTAyNDQ0ODAwfQ.6DVTKEZh7vTr7ohSSxZEV8iyMg6REQCYy7-nCjR3oVk";
        let mut claims = serde_json::Map::new();
        claims.insert("user_id".into(), 1.into());
        claims.insert("email".into(), "a@b.c".into());
        claims.insert("exp".into(), 4_102_444_800i64.into());
        let token = encode(&claims, b"s");
        assert_eq!(token, ruby, "the same token Ruby's jwt gem makes");
        assert_eq!(decode(&token, b"s").unwrap(), claims);
        assert_eq!(decode(&token, b"other"), Err(JwtError::Signature));
        assert_eq!(decode("a.b", b"s"), Err(JwtError::Malformed));
        claims.insert("exp".into(), 1.into());
        assert_eq!(decode(&encode(&claims, b"s"), b"s"), Err(JwtError::Expired));
    }

    #[test]
    fn makes_tokens_and_digests() {
        let token = new_token();
        assert_eq!(token.len(), 43);
        assert_ne!(token, new_token());
        assert_eq!(
            token_digest("abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }
}