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;
pub const MEMORY_THROTTLE_STORE_POSTURE: &str = "id_effect_auth::MemoryThrottleStore::memory_only";
#[derive(Clone)]
pub struct MemoryThrottleStore {
inner: Arc<Mutex<HashMap<String, Failures>>>,
}
impl Default for MemoryThrottleStore {
fn default() -> Self {
id_effect::observability::posture::record_dangerous(
MEMORY_THROTTLE_STORE_POSTURE,
"H5, H6: login and TOTP failure counts are memory-only; each instance allows its own \
budget of guesses",
);
Self {
inner: Arc::default(),
}
}
}
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(())
})
}
}
#[cfg(feature = "pg")]
mod pg {
use std::fmt;
use std::time::Duration;
use id_effect::{Effect, UtcDateTime, fail, succeed};
use id_effect_sql::{SqlClient, SqlClientService, SqlError, SqlRow, params};
use super::{Failures, ThrottleStore};
use crate::error::AuthError;
use crate::session::statements;
const SCHEMA: &str = include_str!("../migrations/0003_id_effect_auth_state.up.sql");
pub(super) const GET: &str = "SELECT count, last_at FROM id_effect_auth_failures WHERE key = $1";
pub(super) const RECORD: &str = "INSERT INTO id_effect_auth_failures AS f (key, count, last_at) \
VALUES ($1, 1, $2) \
ON CONFLICT (key) DO UPDATE SET \
count = CASE WHEN f.last_at >= $3 THEN f.count + 1 ELSE 1 END, last_at = EXCLUDED.last_at \
RETURNING count, last_at";
pub(super) const CLEAR: &str = "DELETE FROM id_effect_auth_failures WHERE key = $1";
pub(super) const PURGE: &str = "DELETE FROM id_effect_auth_failures WHERE last_at < $1";
#[derive(Clone)]
pub struct PgThrottleStore {
client: SqlClientService,
}
impl fmt::Debug for PgThrottleStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PgThrottleStore")
.field("table", &"id_effect_auth_failures")
.finish_non_exhaustive()
}
}
impl PgThrottleStore {
#[inline]
pub fn new(client: impl SqlClient) -> Self {
Self::from_service(SqlClientService::new(client))
}
#[inline]
pub fn from_service(client: SqlClientService) -> Self {
Self { client }
}
pub fn ensure_schema(&self) -> Effect<(), AuthError> {
let client = self.client.clone();
statements(SCHEMA)
.into_iter()
.fold(succeed(()), move |done, sql| {
let client = client.clone();
done.flat_map(move |()| client.execute(&sql, &[]).map(|_| ()).map_err(storage))
})
}
pub fn purge_forgotten(&self, cutoff: UtcDateTime) -> Effect<u64, AuthError> {
self
.client
.execute(PURGE, ¶ms![cutoff.0])
.map_err(storage)
}
}
fn storage(e: SqlError) -> AuthError {
AuthError::Unavailable(format!("login throttle store: {e}"))
}
fn decode(row: &SqlRow) -> Result<Failures, SqlError> {
let count = row.get::<i64>("count")?;
Ok(Failures {
count: u32::try_from(count).unwrap_or(u32::MAX),
last: UtcDateTime(row.get::<jiff::Timestamp>("last_at")?),
})
}
fn first(rows: &[SqlRow]) -> Effect<Option<Failures>, AuthError> {
match rows.first().map(decode) {
None => succeed(None),
Some(Ok(f)) => succeed(Some(f)),
Some(Err(e)) => fail(storage(e)),
}
}
impl ThrottleStore for PgThrottleStore {
fn get(&self, key: &str) -> Effect<Option<Failures>, AuthError> {
self
.client
.query(GET, ¶ms![key])
.map_err(storage)
.flat_map(|rows| first(&rows))
}
fn record_failure(
&self,
key: &str,
at: UtcDateTime,
forget_after: Duration,
) -> Effect<Failures, AuthError> {
let cutoff = at
.0
.checked_sub(forget_after)
.unwrap_or(jiff::Timestamp::MIN);
self
.client
.query(RECORD, ¶ms![key, at.0, cutoff])
.map_err(storage)
.flat_map(|rows| {
first(&rows).flat_map(|found| match found {
Some(f) => succeed(f),
None => fail(AuthError::Unavailable(
"login throttle store: the upsert returned no row".into(),
)),
})
})
}
fn clear(&self, key: &str) -> Effect<(), AuthError> {
self
.client
.execute(CLEAR, ¶ms![key])
.map(|_| ())
.map_err(storage)
}
}
}
#[cfg(feature = "pg")]
pub use pg::PgThrottleStore;
#[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 h5_memory_throttle_store_is_recorded() {
let _ = LoginThrottle::default();
let found = id_effect::observability::posture::dangerous_opt_outs();
let (_, reopens) = found
.iter()
.find(|(id, _)| *id == MEMORY_THROTTLE_STORE_POSTURE)
.expect("recorded");
assert!(reopens.starts_with("H5, H6: login and TOTP failure counts are memory-only"));
assert!(MEMORY_THROTTLE_STORE_POSTURE.ends_with("::memory_only"));
}
#[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");
}
#[cfg(feature = "pg")]
#[test]
fn the_pg_store_counts_in_one_upsert() {
use id_effect_sql::{SqlClient, SqlRow, SqlValue, TestSqlClient};
fn unavailable<A>(r: Result<A, AuthError>) -> bool {
matches!(r, Err(AuthError::Unavailable(_)))
}
let client = TestSqlClient::new();
let store = PgThrottleStore::new(client.clone());
let hour = Duration::from_secs(3600);
assert!(unavailable(run(store.get("k"))));
assert!(unavailable(run(store.ensure_schema())));
assert!(matches!(client.connect().block_on(), Exit::Success(())));
let row = SqlRow::from_pairs([
("count", SqlValue::I64(3)),
("last_at", SqlValue::Timestamp(at(7200).0)),
]);
client.script_query(pg::RECORD, vec![row.clone()]);
let counted = run(store.record_failure("k", at(7200), hour)).unwrap();
assert_eq!(
counted,
Failures {
count: 3,
last: at(7200)
}
);
let (sql, params) = &client.recorded_queries()[0];
assert_eq!(sql, pg::RECORD);
assert_eq!(
params,
&[
SqlValue::Text("k".into()),
SqlValue::Timestamp(at(7200).0),
SqlValue::Timestamp(at(3600).0),
],
"the cutoff is `at - forget_after`"
);
assert_eq!(run(store.get("k")), Ok(None));
client.script_query(pg::GET, vec![row]);
assert_eq!(run(store.get("k")), Ok(Some(counted)));
run(store.clear("k")).unwrap();
client.script_execute(pg::PURGE, 2);
assert_eq!(run(store.purge_forgotten(at(0))), Ok(2));
let executes = client.recorded_executes();
assert_eq!(
executes[0],
(pg::CLEAR.to_owned(), vec![SqlValue::Text("k".into())])
);
assert_eq!(executes[1].1, [SqlValue::Timestamp(at(0).0)]);
client.script_query(pg::RECORD, vec![]);
assert!(unavailable(run(store.record_failure("k", at(1), hour))));
let bad = SqlRow::from_pairs([("count", SqlValue::Text("x".into()))]);
client.script_query(pg::GET, vec![bad]);
assert!(unavailable(run(store.get("k"))));
run(store.ensure_schema()).unwrap();
let ddl = client.recorded_executes();
assert_eq!(ddl.len(), 5, "{ddl:?}");
assert!(
ddl[3]
.0
.starts_with("CREATE TABLE IF NOT EXISTS id_effect_auth_failures")
);
assert!(format!("{store:?}").contains("id_effect_auth_failures"));
}
}