use base64::prelude::*;
pub const NONCE_COOKIE_PREFIX: &str = "obMatJos2";
pub const NONCE_COOKIE_LEN: usize = 13;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct SecurityFeatures(u32);
impl SecurityFeatures {
pub const NONE: Self = Self(0);
pub const PASSWORD_ALGORITHMS: Self = Self(1);
pub const USERNAME_ANONYMITY: Self = Self(1 << 1);
#[must_use]
pub fn from_nonce(nonce: &str) -> Option<Self> {
let encoded = nonce
.strip_prefix(NONCE_COOKIE_PREFIX)?
.as_bytes()
.get(..NONCE_COOKIE_LEN - NONCE_COOKIE_PREFIX.len())?;
let bits = BASE64_STANDARD.decode(encoded).ok()?;
let bits: [u8; 3] = bits.try_into().ok()?;
Some(Self(u32::from_be_bytes([0, bits[0], bits[1], bits[2]])))
}
#[must_use]
pub const fn with(self, other: Self) -> Self {
Self(self.0 | other.0)
}
#[must_use]
pub const fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
#[must_use]
pub const fn password_algorithms(self) -> bool {
self.contains(Self::PASSWORD_ALGORITHMS)
}
#[must_use]
pub const fn username_anonymity(self) -> bool {
self.contains(Self::USERNAME_ANONYMITY)
}
#[must_use]
pub const fn bits(self) -> u32 {
self.0
}
#[must_use]
pub fn cookie(self) -> String {
let bytes = self.0.to_be_bytes();
format!(
"{NONCE_COOKIE_PREFIX}{}",
BASE64_STANDARD.encode(&bytes[1..])
)
}
}
#[cfg(test)]
mod nonce_cookie_test {
use super::*;
#[test]
fn test_security_features_are_read_from_the_nonce_cookie() {
let password = SecurityFeatures::from_nonce("obMatJos2AAABserver-part").unwrap();
assert!(password.password_algorithms() && !password.username_anonymity());
let anonymity =
SecurityFeatures::from_nonce("obMatJos2AAACf//499k954d6OL34oL9FSTvy64sA").unwrap();
assert!(!anonymity.password_algorithms() && anonymity.username_anonymity());
let both = SecurityFeatures::from_nonce("obMatJos2AAAD").unwrap();
assert!(both.password_algorithms() && both.username_anonymity());
let other = SecurityFeatures::from_nonce("obMatJos2gAAAserver-part").unwrap();
assert!(!other.password_algorithms() && !other.username_anonymity());
assert_eq!(other.bits(), 0x80_0000);
let none = SecurityFeatures::from_nonce("obMatJos2AAAAf//499k954d6OL34oL9FSTvy64sA");
assert_eq!(none, Some(SecurityFeatures::NONE));
assert_eq!(
SecurityFeatures::PASSWORD_ALGORITHMS.cookie(),
"obMatJos2AAAB"
);
assert_eq!(
SecurityFeatures::PASSWORD_ALGORITHMS
.with(SecurityFeatures::USERNAME_ANONYMITY)
.cookie(),
"obMatJos2AAAD"
);
assert_eq!(SecurityFeatures::NONE.cookie().len(), NONCE_COOKIE_LEN);
}
#[test]
fn test_a_nonce_without_the_cookie_has_no_security_features() {
for nonce in [
"",
"f//499k954d6OL34oL9FSTvy64sA",
"obMatJos2",
"obMatJos2AAA",
"obMatJos2A*ABxyz",
"xobMatJos2AAAB",
] {
assert_eq!(SecurityFeatures::from_nonce(nonce), None, "{nonce:?}");
}
}
}