use sea_orm::entity::prelude::*;
use sea_orm::sea_query::Expr;
use sea_orm::{
ActiveValue::Set, ConnectionTrait, DatabaseConnection, DbErr, ExprTrait, QueryFilter,
QuerySelect, Schema, TransactionTrait, UpdateMany,
};
use sha2::{Digest, Sha256};
use std::{net::IpAddr, time::Duration};
pub mod login_attempts {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "login_attempts")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub key: String,
pub attempts: i32,
pub window_start: i64,
pub locked_until: i64,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
use login_attempts::{Column, Entity};
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("too many attempts, retry in {retry_after:?}")]
pub struct Locked {
pub retry_after: Duration,
}
#[derive(Clone)]
pub struct Throttle {
db: DatabaseConnection,
max_attempts: u32,
window: Duration,
lockout: Duration,
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
fn reset_q(key: &str, now: i64, window: i64) -> UpdateMany<Entity> {
Entity::update_many()
.col_expr(Column::Attempts, Expr::value(0))
.col_expr(Column::WindowStart, Expr::value(now))
.col_expr(Column::LockedUntil, Expr::value(0i64))
.filter(Column::Key.eq(key))
.filter(Column::LockedUntil.lte(now))
.filter(
Column::WindowStart
.lte(now - window)
.or(Column::LockedUntil.gt(0)),
)
}
fn incr_q(key: &str) -> UpdateMany<Entity> {
Entity::update_many()
.col_expr(Column::Attempts, Expr::col(Column::Attempts).add(1))
.filter(Column::Key.eq(key))
}
fn lock_q(key: &str, now: i64, max: i32, lockout: i64) -> UpdateMany<Entity> {
Entity::update_many()
.col_expr(Column::LockedUntil, Expr::value(now + lockout))
.filter(Column::Key.eq(key))
.filter(Column::Attempts.gte(max))
.filter(Column::LockedUntil.lte(now))
}
impl Throttle {
pub fn new(db: DatabaseConnection) -> Self {
Self {
db,
max_attempts: 5,
window: Duration::from_secs(900),
lockout: Duration::from_secs(900),
}
}
pub fn max_attempts(mut self, n: u32) -> Self {
self.max_attempts = n;
self
}
pub fn window(mut self, d: Duration) -> Self {
self.window = d;
self
}
pub fn lockout(mut self, d: Duration) -> Self {
self.lockout = d;
self
}
pub fn key(email: &str, ip: Option<IpAddr>) -> String {
let raw = format!(
"{}|{}",
email.trim().to_lowercase(),
ip.map(crate::proxy::ip_bucket).unwrap_or_default()
);
Sha256::digest(raw.as_bytes())
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
pub async fn ensure_tables(&self) -> Result<(), DbErr> {
let mut t = Schema::new(self.db.get_database_backend()).create_table_from_entity(Entity);
self.db.execute(t.if_not_exists()).await?;
Ok(())
}
pub async fn check(&self, key: &str) -> Result<(), Locked> {
let row = Entity::find_by_id(key).one(&self.db).await.map_err(|e| {
tracing::error!("throttle check: {e}");
Locked {
retry_after: Duration::from_secs(60),
}
})?;
match row {
Some(r) if r.locked_until > now() => Err(Locked {
retry_after: Duration::from_secs(std::cmp::max(r.locked_until - now(), 1) as u64),
}),
_ => Ok(()),
}
}
pub async fn hit(&self, key: &str) -> Result<(), DbErr> {
let t = now();
let max = std::cmp::min(self.max_attempts, i32::MAX as u32) as i32;
let fresh = login_attempts::ActiveModel {
key: Set(key.into()),
attempts: Set(0),
window_start: Set(t),
locked_until: Set(0),
};
Entity::insert(fresh)
.on_conflict_do_nothing()
.exec_without_returning(&self.db)
.await?;
reset_q(key, t, self.window.as_secs() as i64)
.exec(&self.db)
.await?;
incr_q(key).exec(&self.db).await?;
lock_q(key, t, max, self.lockout.as_secs() as i64)
.exec(&self.db)
.await?;
Ok(())
}
pub async fn attempt(&self, key: &str) -> Result<(), Locked> {
self.check(key).await?;
let fail = |e: DbErr| {
tracing::error!("throttle attempt: {e}");
Locked {
retry_after: Duration::from_secs(60),
}
};
let t = now();
let max = std::cmp::min(self.max_attempts, i32::MAX as u32 - 1) as i32;
let lockout = self.lockout.as_secs() as i64;
let fresh = login_attempts::ActiveModel {
key: Set(key.into()),
attempts: Set(0),
window_start: Set(t),
locked_until: Set(0),
};
Entity::insert(fresh)
.on_conflict_do_nothing()
.exec_without_returning(&self.db)
.await
.map_err(fail)?;
reset_q(key, t, self.window.as_secs() as i64)
.exec(&self.db)
.await
.map_err(fail)?;
let txn = self.db.begin().await.map_err(fail)?;
incr_q(key).exec(&txn).await.map_err(fail)?;
let row = Entity::find_by_id(key).one(&txn).await.map_err(fail)?;
txn.commit().await.map_err(fail)?;
if row.is_some_and(|r| r.attempts <= max) {
return Ok(());
}
lock_q(key, t, max + 1, lockout)
.exec(&self.db)
.await
.map_err(fail)?;
Err(Locked {
retry_after: Duration::from_secs(std::cmp::max(lockout, 1) as u64),
})
}
pub async fn prune(&self) -> Result<u64, DbErr> {
let t = now();
let over = std::cmp::min(self.window.as_secs(), i64::MAX as u64 / 4) as i64;
let mut n = 0u64;
loop {
let keys: Vec<String> = Entity::find()
.filter(Column::LockedUntil.lte(t))
.filter(Column::WindowStart.lte(t - over))
.limit(500)
.all(&self.db)
.await?
.into_iter()
.map(|r| r.key)
.collect();
n += keys.len() as u64;
let full = keys.len() == 500;
Entity::delete_many()
.filter(Column::Key.is_in(keys))
.filter(Column::LockedUntil.lte(t))
.filter(Column::WindowStart.lte(t - over))
.exec(&self.db)
.await?;
if !full {
return Ok(n);
}
}
}
pub async fn clear(&self, key: &str) -> Result<(), DbErr> {
Entity::delete_by_id(key).exec(&self.db).await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use sea_orm::{DbBackend, QueryTrait};
#[cfg(feature = "sqlite")]
async fn dbs() -> Vec<(&'static str, DatabaseConnection)> {
let path = std::env::temp_dir().join(format!(
"ryuk-throttle-{}.db",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let url = format!("sqlite://{}?mode=rwc", path.display());
let mut v = vec![("sqlite", sea_orm::Database::connect(url).await.unwrap())];
for (name, var) in [
("postgres", "TEST_POSTGRES_URL"),
("mysql", "TEST_MYSQL_URL"),
] {
if let Ok(url) = std::env::var(var) {
v.push((name, sea_orm::Database::connect(url).await.unwrap()));
}
}
v
}
#[cfg(feature = "sqlite")]
async fn age(db: &DatabaseConnection, key: &str, secs: i64) {
Entity::update_many()
.col_expr(
Column::WindowStart,
Expr::col(Column::WindowStart).sub(secs),
)
.col_expr(
Column::LockedUntil,
Expr::col(Column::LockedUntil).sub(secs),
)
.filter(Column::Key.eq(key))
.exec(db)
.await
.unwrap();
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn lockout_window_clear() {
for (name, db) in dbs().await {
let t = Throttle::new(db.clone())
.max_attempts(3)
.window(Duration::from_secs(60))
.lockout(Duration::from_secs(120));
t.ensure_tables().await.unwrap();
t.ensure_tables().await.unwrap(); let k = format!("k-{name}");
for _ in 0..2 {
t.hit(&k).await.unwrap();
}
assert!(t.check(&k).await.is_ok(), "{name}");
t.hit(&k).await.unwrap();
let l = t.check(&k).await.unwrap_err();
assert!(
(119..=120).contains(&l.retry_after.as_secs()),
"{name} {l:?}"
);
age(&db, &k, 121).await;
assert!(t.check(&k).await.is_ok());
t.hit(&k).await.unwrap();
assert!(t.check(&k).await.is_ok());
t.hit(&k).await.unwrap();
age(&db, &k, 61).await;
t.hit(&k).await.unwrap();
t.hit(&k).await.unwrap();
assert!(
t.check(&k).await.is_ok(),
"{name}: window should have reset"
);
t.hit(&k).await.unwrap();
assert!(t.check(&k).await.is_err());
t.clear(&k).await.unwrap();
assert!(t.check(&k).await.is_ok());
t.clear(&k).await.unwrap(); }
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn concurrent_hits_all_counted() {
for (name, db) in dbs().await {
let t = Throttle::new(db.clone()).max_attempts(1000);
t.ensure_tables().await.unwrap();
let k = format!("c-{name}-{}", now());
t.clear(&k).await.unwrap();
let hs: Vec<_> = (0..20)
.map(|_| {
let (t, k) = (t.clone(), k.clone());
tokio::spawn(async move { t.hit(&k).await })
})
.collect();
for h in hs {
h.await.unwrap().unwrap();
}
assert_eq!(
Entity::find_by_id(&k)
.one(&db)
.await
.unwrap()
.unwrap()
.attempts,
20,
"{name}"
);
}
}
#[cfg(feature = "sqlite")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn attempt_admits_exactly_max_under_concurrency() {
for (name, db) in dbs().await {
let t = Throttle::new(db.clone()).max_attempts(5);
t.ensure_tables().await.unwrap();
let k = format!("a-{name}-{}", now());
t.clear(&k).await.unwrap();
let hs: Vec<_> = (0..100)
.map(|_| {
let (t, k) = (t.clone(), k.clone());
tokio::spawn(async move { t.attempt(&k).await })
})
.collect();
let mut ok = 0;
for h in hs {
ok += h.await.unwrap().is_ok() as u32;
}
assert_eq!(ok, 5, "{name}");
assert!(t.check(&k).await.is_err(), "{name}: locked afterwards");
t.clear(&k).await.unwrap();
}
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn attempt_sequential_lock_clear_expiry() {
for (name, db) in dbs().await {
let t = Throttle::new(db.clone())
.max_attempts(5)
.window(Duration::from_secs(60))
.lockout(Duration::from_secs(120));
t.ensure_tables().await.unwrap();
let k = format!("as-{name}-{}", now());
for i in 0..5 {
assert!(t.attempt(&k).await.is_ok(), "{name} #{i}");
}
let l = t.attempt(&k).await.unwrap_err();
assert!(
(119..=120).contains(&l.retry_after.as_secs()),
"{name} {l:?}"
);
assert!(t.attempt(&k).await.is_err(), "{name}: stays locked");
age(&db, &k, 121).await;
for i in 0..5 {
assert!(t.attempt(&k).await.is_ok(), "{name} after expiry #{i}");
}
assert!(t.attempt(&k).await.is_err(), "{name}");
t.clear(&k).await.unwrap();
assert!(t.attempt(&k).await.is_ok(), "{name}");
for _ in 0..3 {
t.attempt(&k).await.unwrap();
}
age(&db, &k, 61).await;
for i in 0..5 {
assert!(t.attempt(&k).await.is_ok(), "{name} new window #{i}");
}
assert!(t.attempt(&k).await.is_err(), "{name}");
t.clear(&k).await.unwrap();
}
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn prune_removes_only_finished_rows() {
for (name, db) in dbs().await {
let t = Throttle::new(db.clone())
.max_attempts(2)
.window(Duration::from_secs(60))
.lockout(Duration::from_secs(120));
t.ensure_tables().await.unwrap();
let (fresh, stale, locked, lock_over) = (
format!("pf-{name}"),
format!("ps-{name}"),
format!("pl-{name}"),
format!("po-{name}"),
);
t.clear(&fresh).await.unwrap();
for k in [&fresh, &stale, &locked, &lock_over] {
t.clear(k).await.unwrap();
t.hit(k).await.unwrap();
}
for k in [&locked, &lock_over] {
t.hit(k).await.unwrap(); }
age(&db, &stale, 61).await;
age(&db, &lock_over, 200).await; assert!(t.prune().await.unwrap() >= 2, "{name}");
let there = |k: &str| {
let (db, k) = (db.clone(), k.to_string());
async move { Entity::find_by_id(k).one(&db).await.unwrap().is_some() }
};
assert!(there(&fresh).await && there(&locked).await, "{name}");
assert!(!there(&stale).await && !there(&lock_over).await, "{name}");
assert!(
t.check(&locked).await.is_err(),
"{name}: lock survives prune"
);
t.prune().await.unwrap();
}
}
#[test]
fn key_shares_v6_slash64() {
let k = |s: &str| Throttle::key("a@b.com", Some(s.parse().unwrap()));
assert_eq!(k("2001:db8:1:2::1"), k("2001:db8:1:2::2"));
assert_ne!(k("2001:db8:1:2::1"), k("2001:db8:1:3::1"));
assert_eq!(k("::ffff:1.2.3.4"), k("1.2.3.4"));
}
#[test]
fn key_is_normalized() {
let ip: IpAddr = "127.0.0.1".parse().unwrap();
assert_eq!(
Throttle::key(" A@B.com", Some(ip)),
Throttle::key("a@b.com ", Some(ip))
);
assert_ne!(
Throttle::key("a@b.com", Some(ip)),
Throttle::key("a@b.com", None)
);
assert_eq!(Throttle::key("a@b.com", None).len(), 64);
}
#[test]
fn sql_text_all_backends() {
for b in [DbBackend::Sqlite, DbBackend::Postgres, DbBackend::MySql] {
let inc = incr_q("k").build(b).to_string();
let q = if b == DbBackend::MySql {
"`attempts` = `attempts` + 1"
} else {
"\"attempts\" = \"attempts\" + 1"
};
assert!(inc.starts_with("UPDATE") && inc.contains(q), "{b:?}: {inc}");
let lock = lock_q("k", 10, 3, 5).build(b).to_string();
assert!(
lock.contains("15") && lock.contains(">= 3"),
"{b:?}: {lock}"
);
let reset = reset_q("k", 100, 60).build(b).to_string();
assert!(
reset.contains("<= 40") && reset.contains(" OR "),
"{b:?}: {reset}"
);
let ins = Entity::insert(login_attempts::ActiveModel {
key: Set("k".into()),
attempts: Set(1),
window_start: Set(1),
locked_until: Set(0),
})
.on_conflict_do_nothing()
.build(b)
.to_string();
let want = if b == DbBackend::MySql {
"ON DUPLICATE KEY UPDATE"
} else {
"ON CONFLICT (\"key\") DO NOTHING"
};
assert!(ins.contains(want), "{b:?}: {ins}");
}
}
}