ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! DB-backed login throttling (table `login_attempts`, self-created, SQLite/PostgreSQL/MySQL).
//!
//! ```ignore
//! let throttle = Throttle::new(db).max_attempts(5);
//! throttle.ensure_tables().await?;
//! let key = Throttle::key(&email, Some(ip));
//! if let Err(locked) = throttle.check(&key).await { /* 429, Retry-After: locked.retry_after */ }
//! if !password_ok { throttle.hit(&key).await?; } else { throttle.clear(&key).await?; }
//! ```
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};

/// `login_attempts` table.
pub mod login_attempts {
    use sea_orm::entity::prelude::*;
    /// Failure counter for one throttle key.
    #[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,
        /// Unix seconds when the current counting window began.
        pub window_start: i64,
        /// Unix seconds until which the key is locked; 0 = not locked.
        pub locked_until: i64,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}
use login_attempts::{Column, Entity};

/// Returned by [`Throttle::check`] while a key is locked out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("too many attempts, retry in {retry_after:?}")]
pub struct Locked {
    /// Time left until the lockout ends (at least 1s).
    pub retry_after: Duration,
}

/// Login attempt limiter.
#[derive(Clone)]
pub struct Throttle {
    db: DatabaseConnection,
    max_attempts: u32,
    window: Duration,
    lockout: Duration,
}

fn now() -> i64 {
    chrono::Utc::now().timestamp()
}

// Statement builders are free functions so the SQL-text tests render exactly what runs.

/// Start a fresh window (attempts = 0, the increment that follows makes it 1) when no lock is active
/// and the window is stale or a lock just ended.
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)),
        )
}

/// `attempts = attempts + 1` as one atomic statement.
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))
}

/// Lock once the counter has reached the maximum.
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 {
    /// 5 attempts per 15 minutes, then a 15 minute lockout.
    pub fn new(db: DatabaseConnection) -> Self {
        Self {
            db,
            max_attempts: 5,
            window: Duration::from_secs(900),
            lockout: Duration::from_secs(900),
        }
    }
    /// Failures within the window that trigger a lockout.
    pub fn max_attempts(mut self, n: u32) -> Self {
        self.max_attempts = n;
        self
    }
    /// Counting window.
    pub fn window(mut self, d: Duration) -> Self {
        self.window = d;
        self
    }
    /// Lockout length.
    pub fn lockout(mut self, d: Duration) -> Self {
        self.lockout = d;
        self
    }

    /// Throttle key for a login: sha256 of lowercased email and IP, so length is bounded and
    /// no email is stored in the table.
    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()
    }

    /// Create `login_attempts` if missing.
    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(())
    }

    /// `Err(Locked)` while the key is locked out. A database error fails closed (60s lock).
    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(()),
        }
    }

    /// Record a failed attempt; locks the key when attempts reach the maximum within the window.
    ///
    /// Four single statements, each atomic: insert-if-absent (attempts 0), reset a stale window or an
    /// ended lock to 0, `attempts = attempts + 1`, lock. Nothing depends on affected-row counts
    /// (MySQL reports matched rows, so "was it inserted?" cannot be read from them) or on the order
    /// MySQL evaluates SET assignments in.
    ///
    /// shortcut: not one transaction. Concurrent failures are never lost (increment is
    /// `attempts = attempts + 1`); worst case under a race around a window boundary is one
    /// attempt counted in the old or new window. Upgrade to SELECT ... FOR UPDATE if that matters.
    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(())
    }

    /// Count this attempt and admit it, race-free: `Err(Locked)` when the key is locked or this attempt
    /// exceeds `max_attempts`. Call it *before* verifying credentials (and [`clear`](Throttle::clear) on
    /// success); unlike `check` + `hit`, parallel requests cannot all pass the check first.
    ///
    /// Every contender increments, then reads the counter back in the same transaction (the row lock keeps
    /// its own rank), so exactly `max_attempts` attempts pass per window whatever the concurrency. A
    /// database error fails closed (60s lock).
    ///
    /// shortcut: a lock expiring at the very instant of a burst can let that burst count in two windows;
    /// upgrade to SELECT ... FOR UPDATE if that matters.
    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),
        })
    }

    /// Delete rows whose counting window and lock are both over (they behave like absent rows);
    /// returns how many were selected for deletion.
    ///
    /// shortcut: a `hit` that inserted its row just before this delete loses that one count
    /// (its increment finds nothing); harmless for a stale-window row, which resets anyway.
    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);
            }
        }
    }

    /// Forget a key (call after a successful login).
    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")]
    /// A SQLite file DB (several pooled connections, so concurrency is real) plus external servers when configured.
    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(); // idempotent
            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:?}"
            );
            // lock expires -> fresh window, not instantly re-locked
            age(&db, &k, 121).await;
            assert!(t.check(&k).await.is_ok());
            t.hit(&k).await.unwrap();
            assert!(t.check(&k).await.is_ok());
            // stale window resets the counter
            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"
            );
            // clear
            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(); // clearing nothing is fine
        }
    }

    #[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}"
            );
        }
    }

    /// `attempt` is the race-free entry point: 100 parallel attempts let exactly `max` through.
    #[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");
            // lock over: a fresh window, 5 more pass
            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}");
            // clear resets
            t.clear(&k).await.unwrap();
            assert!(t.attempt(&k).await.is_ok(), "{name}");
            // stale window resets the counter
            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(); // reaches the max -> locked
            }
            age(&db, &stale, 61).await;
            age(&db, &lock_over, 200).await; // window and lock both over
            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}");
        }
    }
}