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;
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()
}
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,
),
};
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
}
pub fn needs_rehash(digest: &str) -> bool {
let Ok(parsed) = PasswordHash::new(digest) else {
return true;
};
let current = Argon2::default();
if parsed.algorithm != argon2::Algorithm::Argon2id.ident() {
return true;
}
let Ok(params) = argon2::Params::try_from(&parsed) else {
return true;
};
let now = current.params();
(params.m_cost(), params.t_cost(), params.p_cost())
!= (now.m_cost(), now.t_cost(), now.p_cost())
}
pub fn token_for(
purpose: &str,
id: i64,
fingerprint: &str,
expires_in: impl crate::jobs::Delay,
) -> String {
let expires = crate::time::now() + expires_in.delay();
let payload = format!(
"{purpose}|{id}|{}|{}",
expires.timestamp(),
fingerprint_hash(fingerprint)
);
let encoded = URL_SAFE_NO_PAD.encode(&payload);
let signature = URL_SAFE_NO_PAD.encode(hmac::Mac::finalize(token_hmac(&encoded)).into_bytes());
format!("{encoded}{signature}")
}
const SIGNATURE_LEN: usize = 43;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedToken {
pub id: i64,
fingerprint: String,
}
impl SignedToken {
pub fn matches(&self, fingerprint: &str) -> bool {
self.fingerprint == fingerprint_hash(fingerprint)
}
}
pub fn read_token(purpose: &str, token: &str) -> Option<SignedToken> {
let split = token.len().checked_sub(SIGNATURE_LEN)?;
if split == 0 || !token.is_char_boundary(split) {
return None;
}
let (encoded, signature) = token.split_at(split);
let signature = URL_SAFE_NO_PAD.decode(signature).ok()?;
let current = crate::request::signing_key();
let signed = std::iter::once((*current).clone())
.chain(crate::request::previous_keys())
.any(|key| hmac::Mac::verify_slice(token_hmac_with(&key, encoded), &signature).is_ok());
if !signed {
return None;
}
let payload = String::from_utf8(URL_SAFE_NO_PAD.decode(encoded).ok()?).ok()?;
let mut parts = payload.splitn(4, '|');
let (made_for, id, expires, fingerprint) =
(parts.next()?, parts.next()?, parts.next()?, parts.next()?);
if made_for != purpose || expires.parse::<i64>().ok()? < crate::time::now().timestamp() {
return None;
}
Some(SignedToken {
id: id.parse().ok()?,
fingerprint: fingerprint.to_owned(),
})
}
fn fingerprint_hash(fingerprint: &str) -> String {
let digest = Sha256::digest(fingerprint.as_bytes());
URL_SAFE_NO_PAD.encode(&digest[..12])
}
fn token_hmac(payload: &str) -> hmac::Hmac<Sha256> {
token_hmac_with(&crate::request::signing_key(), payload)
}
fn token_hmac_with(key: &cookie::Key, payload: &str) -> hmac::Hmac<Sha256> {
use hmac::Mac;
let mut mac = hmac::Hmac::<Sha256>::new_from_slice(key.signing()).expect("HMAC takes any key");
mac.update(b"glacier token|");
mac.update(payload.as_bytes());
mac
}
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)
}
pub fn token_digest(token: &str) -> String {
Sha256::digest(token.as_bytes())
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
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)
}
pub mod totp;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scopes(pub Vec<String>);
pub fn limit_to_scopes(ctx: &mut Context, scopes: Vec<String>) {
ctx.extensions_mut().insert(Scopes(scopes));
}
pub fn require_scope(ctx: &Context, scope: &str) -> crate::Result<()> {
let Some(Scopes(granted)) = ctx.extensions().get::<Scopes>() else {
return Ok(());
};
let allowed = granted.iter().any(|g| {
g == "*"
|| g == scope
|| g.strip_suffix('*')
.is_some_and(|prefix| prefix.ends_with(':') && scope.starts_with(prefix))
});
if allowed {
Ok(())
} else {
Err(crate::Error::new(
http::StatusCode::FORBIDDEN,
format!("this token doesn't have the `{scope}` scope"),
))
}
}
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;
#[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")
}
pub fn sign(claims: &Value, secret: &[u8]) -> String {
let empty = Map::new();
encode(claims.as_object().unwrap_or(&empty), secret)
}
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}")
}
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 <= crate::time::now().timestamp() {
return Err(JwtError::Expired);
}
}
Ok(claims)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tokens_are_for_one_purpose_one_fingerprint_and_a_while() {
let token = token_for(
"password_reset",
7,
"digest-1",
std::time::Duration::from_secs(3600),
);
let signed = read_token("password_reset", &token).unwrap();
assert_eq!(signed.id, 7);
assert!(signed.matches("digest-1"));
assert!(!signed.matches("digest-2"), "the password changed");
assert!(
read_token("magic_link", &token).is_none(),
"another purpose"
);
let mut forged = token.clone();
forged.replace_range(0..1, if token.starts_with('a') { "b" } else { "a" });
assert!(read_token("password_reset", &forged).is_none());
assert!(read_token("password_reset", "junk").is_none());
let gone = token_for(
"password_reset",
7,
"digest-1",
chrono::TimeDelta::seconds(-1),
);
assert!(read_token("password_reset", &gone).is_none(), "expired");
}
#[test]
fn old_hashes_need_rehashing() {
assert!(!needs_rehash(&hash_password("correct horse")));
let bcrypt = bcrypt::hash("correct horse", 4).unwrap();
assert!(needs_rehash(&bcrypt));
assert!(needs_rehash("not a hash"));
}
#[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")));
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};
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"
);
}
}