use std::collections::HashMap;
use std::fmt;
use std::net::IpAddr;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use id_effect::{Effect, UtcDateTime, WallClock, fail, succeed, suspend};
use crate::error::AuthError;
pub const DEFAULT_FREE_ATTEMPTS: u32 = 5;
pub const DEFAULT_BASE_DELAY: Duration = Duration::from_secs(1);
pub const DEFAULT_MAX_DELAY: Duration = Duration::from_secs(15 * 60);
pub const DEFAULT_FORGET_AFTER: Duration = Duration::from_secs(60 * 60);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Failures {
pub count: u32,
pub last: UtcDateTime,
}
pub(crate) fn elapsed(earlier: UtcDateTime, later: UtcDateTime) -> Duration {
if later <= earlier {
return Duration::ZERO;
}
Duration::try_from(later.0.duration_since(earlier.0)).unwrap_or(Duration::ZERO)
}
pub trait ThrottleStore: Send + Sync + 'static {
fn get(&self, key: &str) -> Effect<Option<Failures>, AuthError>;
fn record_failure(
&self,
key: &str,
at: UtcDateTime,
forget_after: Duration,
) -> Effect<Failures, AuthError>;
fn clear(&self, key: &str) -> Effect<(), AuthError>;
}
const MEMORY_PRUNE_AT: usize = 10_000;
#[derive(Clone, Default)]
pub struct MemoryThrottleStore {
inner: Arc<Mutex<HashMap<String, Failures>>>,
}
impl fmt::Debug for MemoryThrottleStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MemoryThrottleStore")
.field("keys", &self.state().len())
.finish()
}
}
impl MemoryThrottleStore {
#[inline]
pub fn new() -> Self {
Self::default()
}
fn state(&self) -> MutexGuard<'_, HashMap<String, Failures>> {
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl ThrottleStore for MemoryThrottleStore {
fn get(&self, key: &str) -> Effect<Option<Failures>, AuthError> {
let (this, key) = (self.clone(), key.to_owned());
suspend(move || succeed(this.state().get(&key).copied()))
}
fn record_failure(
&self,
key: &str,
at: UtcDateTime,
forget_after: Duration,
) -> Effect<Failures, AuthError> {
let (this, key) = (self.clone(), key.to_owned());
suspend(move || {
let mut st = this.state();
if st.len() >= MEMORY_PRUNE_AT {
st.retain(|_, f| elapsed(f.last, at) <= forget_after);
}
let count = match st.get(&key) {
Some(f) if elapsed(f.last, at) <= forget_after => f.count.saturating_add(1),
_ => 1,
};
let failures = Failures { count, last: at };
st.insert(key, failures);
succeed(failures)
})
}
fn clear(&self, key: &str) -> Effect<(), AuthError> {
let (this, key) = (self.clone(), key.to_owned());
suspend(move || {
this.state().remove(&key);
succeed(())
})
}
}
#[derive(Clone)]
pub struct LoginThrottle {
store: Arc<dyn ThrottleStore>,
free_attempts: u32,
base_delay: Duration,
max_delay: Duration,
forget_after: Duration,
clock: WallClock,
}
impl fmt::Debug for LoginThrottle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LoginThrottle")
.field("free_attempts", &self.free_attempts)
.field("base_delay", &self.base_delay)
.field("max_delay", &self.max_delay)
.field("forget_after", &self.forget_after)
.finish_non_exhaustive()
}
}
impl Default for LoginThrottle {
fn default() -> Self {
Self::new(MemoryThrottleStore::new())
}
}
fn account_key(account: &str) -> String {
format!("account:{}", account.to_lowercase())
}
fn client_key(client: IpAddr) -> String {
format!("ip:{client}")
}
impl LoginThrottle {
pub fn new(store: impl ThrottleStore) -> Self {
Self {
store: Arc::new(store),
free_attempts: DEFAULT_FREE_ATTEMPTS,
base_delay: DEFAULT_BASE_DELAY,
max_delay: DEFAULT_MAX_DELAY,
forget_after: DEFAULT_FORGET_AFTER,
clock: WallClock::system(),
}
}
#[must_use]
pub fn free_attempts(mut self, attempts: u32) -> Self {
self.free_attempts = attempts;
self
}
#[must_use]
pub fn base_delay(mut self, delay: Duration) -> Self {
self.base_delay = delay;
self
}
#[must_use]
pub fn max_delay(mut self, delay: Duration) -> Self {
self.max_delay = delay;
self
}
#[must_use]
pub fn forget_after(mut self, after: Duration) -> Self {
self.forget_after = after;
self
}
#[must_use]
pub fn with_clock(mut self, clock: WallClock) -> Self {
self.clock = clock;
self
}
pub fn delay_after(&self, failures: u32) -> Duration {
let Some(past) = failures
.checked_sub(self.free_attempts)
.filter(|_| failures > 0)
else {
return Duration::ZERO;
};
let factor = 1_u32.checked_shl(past).unwrap_or(u32::MAX);
self.base_delay.saturating_mul(factor).min(self.max_delay)
}
fn remaining(&self, failures: Option<Failures>, now: UtcDateTime) -> Duration {
let Some(f) = failures else {
return Duration::ZERO;
};
let since = elapsed(f.last, now);
if since > self.forget_after {
return Duration::ZERO;
}
self.delay_after(f.count).saturating_sub(since)
}
pub fn check(&self, account: &str, client: Option<IpAddr>) -> Effect<(), AuthError> {
let this = self.clone();
let store = Arc::clone(&self.store);
let account = account_key(account);
self.clock.now().flat_map(move |now| {
store.get(&account).flat_map(move |by_account| {
let by_client = match client {
Some(ip) => this.store.get(&client_key(ip)),
None => succeed(None),
};
by_client.flat_map(move |by_client| {
let wait = this
.remaining(by_account, now)
.max(this.remaining(by_client, now));
if wait.is_zero() {
succeed(())
} else {
fail(AuthError::TooManyAttempts { retry_after: wait })
}
})
})
})
}
pub fn record_failure(&self, account: &str, client: Option<IpAddr>) -> Effect<(), AuthError> {
let this = self.clone();
let account = account_key(account);
self.clock.now().flat_map(move |now| {
let forget = this.forget_after;
let store = Arc::clone(&this.store);
this
.store
.record_failure(&account, now, forget)
.flat_map(move |_| match client {
Some(ip) => store
.record_failure(&client_key(ip), now, forget)
.map(|_| ()),
None => succeed(()),
})
})
}
pub fn record_success(&self, account: &str) -> Effect<(), AuthError> {
self.store.clear(&account_key(account))
}
}
#[cfg(test)]
mod tests {
use std::net::Ipv4Addr;
use std::time::Instant;
use id_effect::{Cause, Exit};
use super::*;
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 at(secs: i64) -> UtcDateTime {
UtcDateTime::unsafe_make(secs * 1000)
}
#[test]
fn delays_double_from_the_base_up_to_the_cap() {
let t = LoginThrottle::default();
assert_eq!(t.delay_after(0), Duration::ZERO);
assert_eq!(t.delay_after(4), Duration::ZERO);
assert_eq!(t.delay_after(5), Duration::from_secs(1));
assert_eq!(t.delay_after(6), Duration::from_secs(2));
assert_eq!(t.delay_after(10), Duration::from_secs(32));
assert_eq!(t.delay_after(15), DEFAULT_MAX_DELAY);
assert_eq!(t.delay_after(u32::MAX), DEFAULT_MAX_DELAY);
assert_eq!(
LoginThrottle::default().free_attempts(0).delay_after(0),
Duration::ZERO
);
assert!(format!("{t:?}").contains("free_attempts: 5"));
}
#[test]
fn the_memory_store_counts_forgets_and_prunes() {
let s = MemoryThrottleStore::new();
let hour = Duration::from_secs(3600);
assert_eq!(run(s.get("k")), Ok(None));
assert_eq!(run(s.record_failure("k", at(0), hour)).unwrap().count, 1);
assert_eq!(run(s.record_failure("k", at(10), hour)).unwrap().count, 2);
assert_eq!(
run(s.record_failure("k", at(10 + 3601), hour))
.unwrap()
.count,
1,
"forgotten after an hour without a failure"
);
run(s.clear("k")).unwrap();
assert_eq!(run(s.get("k")), Ok(None));
for i in 0..MEMORY_PRUNE_AT {
run(s.record_failure(&format!("old{i}"), at(0), hour)).unwrap();
}
run(s.record_failure("new", at(7200), hour)).unwrap();
assert_eq!(s.state().len(), 1, "forgotten keys were pruned");
assert!(format!("{s:?}").contains("keys: 1"));
assert_eq!(elapsed(at(5), at(1)), Duration::ZERO);
}
#[test]
fn a_lock_runs_from_the_last_failure_and_success_clears_the_account() {
let clock = WallClock::anchored(Instant::now(), at(1_000));
let t = LoginThrottle::default()
.free_attempts(2)
.base_delay(Duration::from_secs(10))
.max_delay(Duration::from_secs(25))
.forget_after(Duration::from_secs(600))
.with_clock(clock.clone());
let ip = Some(IpAddr::V4(Ipv4Addr::LOCALHOST));
for _ in 0..2 {
run(t.check("Alice", ip)).unwrap();
run(t.record_failure("alice", ip)).unwrap();
}
let Err(AuthError::TooManyAttempts { retry_after }) = run(t.check("ALICE", None)) else {
panic!("the account is locked whatever the case of its name")
};
assert!(retry_after <= Duration::from_secs(10) && retry_after > Duration::from_secs(9));
assert!(
run(t.check("bob", ip)).is_err(),
"the address is locked too"
);
assert!(run(t.check("bob", None)).is_ok());
clock.jump(Duration::from_secs(10));
run(t.check("alice", ip)).unwrap();
run(t.record_failure("alice", None)).unwrap();
clock.jump(Duration::from_secs(19));
assert!(run(t.check("alice", None)).is_err(), "20 s after the third");
clock.jump(Duration::from_secs(1));
run(t.check("alice", None)).unwrap();
run(t.record_success("alice")).unwrap();
run(t.record_failure("alice", None)).unwrap();
assert!(
run(t.check("alice", None)).is_ok(),
"the count started over"
);
clock.jump(Duration::from_secs(601));
assert!(run(t.check("bob", ip)).is_ok(), "the address was forgotten");
}
}