use std::collections::HashMap;
use std::fmt;
use std::net::IpAddr;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use id_effect::{Effect, fail, succeed, suspend};
use crate::error::AuthError;
use crate::password::{
MAX_PASSWORD_LEN, Password, PasswordError, PasswordHash, PasswordHasher, Verification,
};
use crate::principal::{AuthPrincipal, AuthScheme};
use crate::throttle::LoginThrottle;
#[derive(Clone, Debug, PartialEq)]
pub struct UserCredentials {
pub password_hash: PasswordHash,
pub principal: AuthPrincipal,
}
pub trait UserLookup: Send + Sync + 'static {
fn find_user(&self, username: &str) -> Effect<Option<UserCredentials>, AuthError>;
fn update_password_hash(&self, username: &str, hash: PasswordHash) -> Effect<(), AuthError> {
let _ = (username, hash);
succeed(())
}
}
#[derive(Default)]
struct MemoryUsersState {
users: HashMap<String, UserCredentials>,
fail: Option<String>,
}
#[derive(Clone, Default)]
pub struct MemoryUsers {
inner: Arc<Mutex<MemoryUsersState>>,
}
impl fmt::Debug for MemoryUsers {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MemoryUsers")
.field("len", &self.state().users.len())
.finish()
}
}
impl MemoryUsers {
#[inline]
pub fn new() -> Self {
Self::default()
}
fn state(&self) -> MutexGuard<'_, MemoryUsersState> {
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn insert(
&self,
username: impl Into<String>,
password_hash: PasswordHash,
principal: AuthPrincipal,
) {
self.state().users.insert(
username.into(),
UserCredentials {
password_hash,
principal,
},
);
}
pub fn password_hash(&self, username: &str) -> Option<PasswordHash> {
self
.state()
.users
.get(username)
.map(|u| u.password_hash.clone())
}
pub fn fail_with(&self, message: Option<&str>) {
self.state().fail = message.map(str::to_owned);
}
}
impl UserLookup for MemoryUsers {
fn find_user(&self, username: &str) -> Effect<Option<UserCredentials>, AuthError> {
let (this, username) = (self.clone(), username.to_owned());
suspend(move || {
let st = this.state();
match &st.fail {
Some(m) => fail(AuthError::Unavailable(m.clone())),
None => succeed(st.users.get(&username).cloned()),
}
})
}
fn update_password_hash(&self, username: &str, hash: PasswordHash) -> Effect<(), AuthError> {
let (this, username) = (self.clone(), username.to_owned());
suspend(move || {
if let Some(user) = this.state().users.get_mut(&username) {
user.password_hash = hash;
}
succeed(())
})
}
}
#[derive(Clone)]
pub struct BasicAuth {
users: Arc<dyn UserLookup>,
hasher: PasswordHasher,
throttle: Option<LoginThrottle>,
}
impl fmt::Debug for BasicAuth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BasicAuth")
.field("hasher", &self.hasher)
.field("throttle", &self.throttle)
.finish_non_exhaustive()
}
}
fn hashing(e: PasswordError) -> AuthError {
AuthError::Unavailable(e.to_string())
}
impl BasicAuth {
pub fn new(users: impl UserLookup, hasher: PasswordHasher) -> Self {
Self {
users: Arc::new(users),
hasher,
throttle: Some(LoginThrottle::default()),
}
}
#[must_use]
pub fn with_throttle(mut self, throttle: LoginThrottle) -> Self {
self.throttle = Some(throttle);
self
}
#[must_use]
pub fn without_throttle_dangerous(mut self) -> Self {
self.throttle = None;
self
}
pub fn authenticate(
&self,
username: &str,
password: impl Into<Password>,
) -> Effect<AuthPrincipal, AuthError> {
self.authenticate_from(username, password, None)
}
pub fn authenticate_from(
&self,
username: &str,
password: impl Into<Password>,
client: Option<IpAddr>,
) -> Effect<AuthPrincipal, AuthError> {
let password = password.into();
if password.expose().len() > MAX_PASSWORD_LEN {
return fail(AuthError::Malformed(format!(
"the password is longer than {MAX_PASSWORD_LEN} bytes"
)));
}
let (this, username) = (self.clone(), username.to_owned());
let allowed = match &self.throttle {
Some(t) => t.check(&username, client),
None => succeed(()),
};
allowed.flat_map(move |()| {
let users = Arc::clone(&this.users);
users.find_user(&username).flat_map(move |found| {
let stored = found.as_ref().map(|u| u.password_hash.clone());
let (users, throttle) = (Arc::clone(&this.users), this.throttle.clone());
this
.hasher
.verify_or_dummy(password, stored.as_ref())
.map_err(hashing)
.flat_map(move |verification| {
let principal = match (verification, found) {
(Verification::Valid, Some(user)) => {
succeed(user.principal.with_scheme(AuthScheme::Basic))
}
(Verification::ValidNeedsRehash(upgraded), Some(user)) => users
.update_password_hash(&username, upgraded)
.map(move |()| user.principal.with_scheme(AuthScheme::Basic)),
_ => {
return match throttle {
Some(t) => t
.record_failure(&username, client)
.flat_map(|()| fail(AuthError::InvalidCredentials)),
None => fail(AuthError::InvalidCredentials),
};
}
};
match throttle {
Some(t) => principal.flat_map(move |p| t.record_success(&username).map(move |()| p)),
None => principal,
}
})
})
})
}
pub fn authenticate_encoded(&self, encoded: &str) -> Effect<AuthPrincipal, AuthError> {
self.authenticate_encoded_from(encoded, None)
}
pub fn authenticate_encoded_from(
&self,
encoded: &str,
client: Option<IpAddr>,
) -> Effect<AuthPrincipal, AuthError> {
match basic_credentials(encoded) {
Ok((username, password)) => self.authenticate_from(&username, password, client),
Err(e) => fail(e),
}
}
}
pub fn basic_credentials(encoded: &str) -> Result<(String, Password), AuthError> {
let bytes = STANDARD
.decode(encoded.trim())
.map_err(|_| AuthError::Malformed("basic credentials are not base64".into()))?;
let text = String::from_utf8(bytes)
.map_err(|_| AuthError::Malformed("basic credentials are not UTF-8".into()))?;
let (user, password) = text
.split_once(':')
.ok_or_else(|| AuthError::Malformed("basic credentials have no ':'".into()))?;
Ok((user.to_owned(), Password::new(password)))
}
pub fn basic_header(username: &str, password: &str) -> String {
format!(
"Basic {}",
STANDARD.encode(format!("{username}:{password}"))
)
}
#[cfg(test)]
mod tests {
use id_effect::{Cause, Exit};
use super::*;
use crate::password::PasswordParams;
fn run<A: Send + 'static>(eff: Effect<A, AuthError>) -> Result<A, AuthError> {
match eff.block_on() {
Exit::Success(a) => Ok(a),
Exit::Failure(Cause::Fail(e)) => Err(e),
Exit::Failure(c) => panic!("unexpected cause: {c:?}"),
}
}
fn hasher(m: u32) -> PasswordHasher {
PasswordHasher::new(PasswordParams::new(m, 1, 1).unwrap())
}
fn hash(h: &PasswordHasher, pw: &str) -> PasswordHash {
match h.hash(pw).block_on() {
Exit::Success(x) => x,
other => panic!("{other:?}"),
}
}
#[test]
fn valid_wrong_and_unknown() {
let h = hasher(8);
let users = MemoryUsers::new();
users.insert(
"alice",
hash(&h, "pw"),
AuthPrincipal::new("u1").with_role("r"),
);
let basic = BasicAuth::new(users.clone(), h);
let p = run(basic.authenticate("alice", "pw")).unwrap();
assert_eq!(
p,
AuthPrincipal::new("u1")
.with_role("r")
.with_scheme(AuthScheme::Basic)
);
assert_eq!(
run(basic.authenticate("alice", "bad")),
Err(AuthError::InvalidCredentials)
);
assert_eq!(
run(basic.authenticate("nobody", "pw")),
Err(AuthError::InvalidCredentials)
);
assert!(format!("{basic:?}").contains("BasicAuth"));
assert!(format!("{users:?}").contains("len: 1"));
}
#[test]
fn outdated_hash_is_upgraded_on_login() {
let users = MemoryUsers::new();
let old = hash(&hasher(8), "pw");
users.insert("alice", old.clone(), AuthPrincipal::new("u1"));
let basic = BasicAuth::new(users.clone(), hasher(16));
run(basic.authenticate("alice", "pw")).unwrap();
let new = users.password_hash("alice").unwrap();
assert_ne!(new, old);
assert!(new.as_str().contains("m=16"), "{new}");
assert_eq!(users.password_hash("nobody"), None);
}
#[test]
fn store_outage_and_default_rehash_hook() {
struct NoRehash(MemoryUsers);
impl UserLookup for NoRehash {
fn find_user(&self, username: &str) -> Effect<Option<UserCredentials>, AuthError> {
self.0.find_user(username)
}
}
let users = MemoryUsers::new();
users.insert("alice", hash(&hasher(8), "pw"), AuthPrincipal::new("u1"));
let basic = BasicAuth::new(NoRehash(users.clone()), hasher(16));
assert!(run(basic.authenticate("alice", "pw")).is_ok());
users.fail_with(Some("db down"));
assert_eq!(
run(basic.authenticate("alice", "pw")),
Err(AuthError::Unavailable("db down".into()))
);
users.fail_with(None);
assert!(run(basic.authenticate("alice", "pw")).is_ok());
assert_eq!(
hashing(PasswordError::Blocking),
AuthError::Unavailable(PasswordError::Blocking.to_string())
);
}
#[derive(Clone, Default)]
struct Counting {
users: MemoryUsers,
lookups: Arc<std::sync::atomic::AtomicUsize>,
}
impl Counting {
fn lookups(&self) -> usize {
self.lookups.load(std::sync::atomic::Ordering::SeqCst)
}
}
impl UserLookup for Counting {
fn find_user(&self, username: &str) -> Effect<Option<UserCredentials>, AuthError> {
self
.lookups
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
self.users.find_user(username)
}
}
#[test]
fn h5_throttle_checked_before_hashing() {
let h = hasher(8);
let users = Counting::default();
users
.users
.insert("alice", hash(&h, "pw"), AuthPrincipal::new("u1"));
let basic = BasicAuth::new(users.clone(), h);
for i in 1..=5 {
assert_eq!(
run(basic.authenticate("alice", "guess")),
Err(AuthError::InvalidCredentials)
);
assert_eq!(users.lookups(), i);
}
for pw in ["guess", "pw"] {
assert!(matches!(
run(basic.authenticate("alice", pw)),
Err(AuthError::TooManyAttempts { .. })
));
}
assert_eq!(users.lookups(), 5, "no lookup, so no hashing, while locked");
assert_eq!(
run(basic.authenticate("bob", "x")),
Err(AuthError::InvalidCredentials)
);
let open = basic.clone().without_throttle_dangerous();
assert!(run(open.authenticate("alice", "pw")).is_ok());
assert!(format!("{open:?}").contains("throttle: None"));
}
#[test]
fn success_clears_the_account_and_a_custom_throttle_applies() {
let h = hasher(8);
let users = MemoryUsers::new();
users.insert("alice", hash(&h, "pw"), AuthPrincipal::new("u1"));
let ip = Some(IpAddr::from([198, 51, 100, 4]));
let basic = BasicAuth::new(users, h).with_throttle(LoginThrottle::default().free_attempts(2));
assert!(run(basic.authenticate_from("alice", "bad", ip)).is_err());
assert!(run(basic.authenticate_from("alice", "pw", ip)).is_ok());
assert!(run(basic.authenticate_from("alice", "bad", None)).is_err());
assert!(run(basic.authenticate_from("alice", "pw", None)).is_ok());
assert_eq!(
run(basic.authenticate_from("carol", "bad", ip)),
Err(AuthError::InvalidCredentials)
);
assert!(matches!(
run(basic.authenticate_encoded_from(
basic_header("dave", "x").strip_prefix("Basic ").unwrap(),
ip
)),
Err(AuthError::TooManyAttempts { .. })
));
}
#[test]
fn l4_long_basic_password_rejected() {
let h = hasher(8);
let users = Counting::default();
let long = "p".repeat(MAX_PASSWORD_LEN);
users
.users
.insert("alice", hash(&h, &long), AuthPrincipal::new("u1"));
let basic = BasicAuth::new(users.clone(), h);
assert!(
run(basic.authenticate("alice", long.as_str())).is_ok(),
"256 bytes is fine"
);
for too_long in [format!("{long}p"), "é".repeat(129)] {
assert!(matches!(
run(basic.authenticate("alice", too_long.as_str())),
Err(AuthError::Malformed(m)) if m.contains("256 bytes")
));
}
let encoded = basic_header("alice", &"x".repeat(10_000));
assert!(matches!(
run(basic.authenticate_encoded(encoded.strip_prefix("Basic ").unwrap())),
Err(AuthError::Malformed(_))
));
assert_eq!(users.lookups(), 1, "rejected before the lookup and hashing");
}
#[test]
fn header_encoding_round_trips() {
let header = basic_header("alice", "p:w");
let encoded = header.strip_prefix("Basic ").unwrap();
let (user, pw) = basic_credentials(encoded).unwrap();
assert_eq!((user.as_str(), pw.expose()), ("alice", "p:w"));
assert!(matches!(
basic_credentials("%%%"),
Err(AuthError::Malformed(_))
));
assert!(matches!(
basic_credentials(&STANDARD.encode([0xff, 0xfe])),
Err(AuthError::Malformed(_))
));
assert!(matches!(
basic_credentials(&STANDARD.encode("nocolon")),
Err(AuthError::Malformed(_))
));
let users = MemoryUsers::new();
users.insert("alice", hash(&hasher(8), "p:w"), AuthPrincipal::new("u1"));
let basic = BasicAuth::new(users, hasher(8));
assert!(run(basic.authenticate_encoded(encoded)).is_ok());
assert!(matches!(
run(basic.authenticate_encoded("%%%")),
Err(AuthError::Malformed(_))
));
}
}