use std::fmt;
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use secrecy::{ExposeSecret, SecretString};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use zeroize::Zeroize;
use crate::error::GuardError;
pub const TOKEN_LEN: usize = 43;
pub struct SessionToken(SecretString);
impl SessionToken {
pub fn generate() -> Result<Self, GuardError> {
let mut bytes = [0_u8; 32];
getrandom::fill(&mut bytes).map_err(|_| GuardError::Random)?;
let encoded = URL_SAFE_NO_PAD.encode(bytes);
bytes.zeroize();
Ok(Self(SecretString::from(encoded)))
}
pub fn expose(&self) -> &str {
self.0.expose_secret()
}
pub fn hash(&self) -> TokenHash {
TokenHash::of(self.expose())
}
}
impl fmt::Debug for SessionToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SessionToken(<redacted>)")
}
}
#[derive(Clone, Copy, Eq, Hash)]
#[allow(
clippy::derived_hash_with_manual_eq,
reason = "constant-time eq agrees with byte-wise Hash"
)]
pub struct TokenHash([u8; 32]);
impl TokenHash {
pub fn of(token: &str) -> Self {
Self(Sha256::digest(token.as_bytes()).into())
}
pub fn from_presented(presented: &str) -> Option<Self> {
is_well_formed(presented).then(|| Self::of(presented))
}
pub const fn from_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
pub const fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
pub fn to_hex(&self) -> String {
use fmt::Write as _;
self.0.iter().fold(String::with_capacity(64), |mut out, byte| {
let _ = write!(out, "{byte:02x}");
out
})
}
pub fn from_hex(hex: &str) -> Option<Self> {
if hex.len() != 64 || !hex.is_ascii() {
return None;
}
let mut bytes = [0_u8; 32];
for (slot, pair) in bytes.iter_mut().zip(hex.as_bytes().as_chunks::<2>().0) {
let pair = std::str::from_utf8(pair).ok()?;
*slot = u8::from_str_radix(pair, 16).ok()?;
}
Some(Self(bytes))
}
}
impl PartialEq for TokenHash {
fn eq(&self, other: &Self) -> bool {
self.0.ct_eq(&other.0).into()
}
}
impl fmt::Debug for TokenHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "TokenHash({}…)", &self.to_hex()[..8])
}
}
pub fn is_well_formed(value: &str) -> bool {
value.len() == TOKEN_LEN
&& value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::*;
#[test]
fn generated_tokens_are_43_base64url_chars_and_unique() {
let a = SessionToken::generate().unwrap();
let b = SessionToken::generate().unwrap();
assert_eq!(a.expose().len(), TOKEN_LEN);
assert!(is_well_formed(a.expose()));
assert_ne!(a.expose(), b.expose());
assert_eq!(URL_SAFE_NO_PAD.decode(a.expose()).unwrap().len(), 32);
}
#[test]
fn debug_output_never_contains_the_token() {
let token = SessionToken::generate().unwrap();
assert!(!format!("{token:?}").contains(token.expose()));
assert!(!format!("{:?}", token.hash()).contains(&token.hash().to_hex()));
}
#[test]
fn presented_tokens_are_validated_before_hashing() {
let token = SessionToken::generate().unwrap();
assert_eq!(TokenHash::from_presented(token.expose()), Some(token.hash()));
assert_eq!(TokenHash::from_presented(""), None);
assert_eq!(TokenHash::from_presented(&"a".repeat(42)), None);
assert_eq!(TokenHash::from_presented(&"a".repeat(44)), None);
assert_eq!(TokenHash::from_presented(&format!("{}=", "a".repeat(42))), None);
assert_eq!(TokenHash::from_presented(&format!("{}é", "a".repeat(41))), None);
}
#[test]
fn hash_matches_sha256() {
assert_eq!(
TokenHash::of("abc").to_hex(),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
proptest! {
#[test]
fn hex_round_trips(bytes in any::<[u8; 32]>()) {
let hash = TokenHash::from_bytes(bytes);
prop_assert_eq!(TokenHash::from_hex(&hash.to_hex()), Some(hash));
}
#[test]
fn from_hex_never_panics(s in ".{0,80}") {
let _ = TokenHash::from_hex(&s);
}
#[test]
fn from_presented_accepts_only_well_formed(s in "[A-Za-z0-9_=+/ -]{40,46}") {
prop_assert_eq!(TokenHash::from_presented(&s).is_some(), is_well_formed(&s));
}
}
}