Skip to main content

mcp_server_core/
guards.rs

1//! Abuse limits: failed sign-in attempts per address, per wider block and overall, and one-time
2//! codes.
3
4use std::collections::{HashMap, VecDeque};
5use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
6use std::sync::Mutex;
7use std::time::{Duration, Instant};
8
9/// Rejections across all clients within one window that reach the global ceiling; what happens
10/// then is the limiter's [`Ceiling`]. Only settled rejections count here; checks still in flight
11/// do not, so a busy server never trips it by itself.
12pub const GLOBAL_MAX_FAILURES: usize = 30;
13/// Attempts (rejected or in flight) one wider block, an IPv6 /48 or IPv4 /24, may have in a
14/// window, so one allocation cannot spread over thousands of addresses.
15pub const BLOCK_MAX_ATTEMPTS: usize = 25;
16/// Addresses, and separately blocks, tracked at once.
17const MAX_TRACKED: usize = 10_000;
18const SWEEP_INTERVAL: Duration = Duration::from_secs(1);
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21enum Kind {
22    /// Counted while its check runs; dropped again unless it is rejected.
23    Pending,
24    Failure,
25}
26
27#[derive(Default)]
28struct Bucket {
29    attempts: Vec<(Instant, Kind)>,
30}
31
32impl Bucket {
33    fn prune(&mut self, now: Instant, window: Duration) {
34        self.attempts
35            .retain(|(t, _)| now.duration_since(*t) < window);
36    }
37
38    fn has_failure(&self) -> bool {
39        self.attempts.iter().any(|(_, k)| *k == Kind::Failure)
40    }
41
42    fn take(&mut self, at: Instant) -> bool {
43        match self
44            .attempts
45            .iter()
46            .rposition(|(t, k)| *t == at && *k == Kind::Pending)
47        {
48            Some(i) => {
49                self.attempts.remove(i);
50                true
51            }
52            None => false,
53        }
54    }
55}
56
57/// What happens once rejections across all clients reach [`GLOBAL_MAX_FAILURES`] in a window.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum Ceiling {
61    /// Every client is refused until the window passes, the owner too. Right for one shared
62    /// secret, such as the owner's password, where a single right guess gives everything away:
63    /// the total guessing rate stays bounded however many addresses an attacker has.
64    BlockEveryone,
65    /// Only clients with a rejection of their own in the window are refused, so other people's
66    /// failures never lock out someone who has not failed. Once the ceiling is reached while so
67    /// many addresses are tracked that the table is full, an untracked address is judged by its
68    /// block, and refused as [`Refusal::Busy`] when that is untracked too. Right when each person
69    /// signs in with their own credential.
70    BlockFailing,
71}
72
73/// Why an attempt was refused.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75#[non_exhaustive]
76pub enum Refusal {
77    /// This client, or its block, has too many rejected or concurrent attempts.
78    TooMany,
79    /// So many addresses are failing that new, untracked ones cannot be told apart: the server
80    /// is under attack and refuses them until it calms down.
81    Busy,
82}
83
84/// Limits credential attempts per client address (IPv4 address, IPv6 /64) and per wider block
85/// (IPv4 /24, IPv6 /48), plus a ceiling on rejections across all clients.
86pub struct LoginLimiter {
87    max: usize,
88    window: Duration,
89    ceiling: Ceiling,
90    state: Mutex<LimiterState>,
91}
92
93struct LimiterState {
94    addresses: HashMap<IpAddr, Bucket>,
95    blocks: HashMap<IpAddr, Bucket>,
96    failures: VecDeque<Instant>,
97    last_sweep: Instant,
98}
99
100/// The client an address belongs to: the address itself for IPv4, its /64 for IPv6.
101fn address_key(ip: IpAddr) -> IpAddr {
102    match ip.to_canonical() {
103        IpAddr::V6(v6) => {
104            let s = v6.segments();
105            IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], s[3], 0, 0, 0, 0))
106        }
107        v4 => v4,
108    }
109}
110
111/// The wider block an address belongs to: its IPv4 /24 or IPv6 /48.
112fn block_key(ip: IpAddr) -> IpAddr {
113    match ip.to_canonical() {
114        IpAddr::V6(v6) => {
115            let s = v6.segments();
116            IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], 0, 0, 0, 0, 0))
117        }
118        IpAddr::V4(v4) => {
119            let o = v4.octets();
120            IpAddr::V4(Ipv4Addr::new(o[0], o[1], o[2], 0))
121        }
122    }
123}
124
125impl LimiterState {
126    fn prune(&mut self, now: Instant, window: Duration) {
127        while self
128            .failures
129            .front()
130            .is_some_and(|t| now.duration_since(*t) >= window)
131        {
132            self.failures.pop_front();
133        }
134        if now.duration_since(self.last_sweep) < SWEEP_INTERVAL {
135            return;
136        }
137        self.last_sweep = now;
138        for map in [&mut self.addresses, &mut self.blocks] {
139            map.retain(|_, b| {
140                b.prune(now, window);
141                !b.attempts.is_empty()
142            });
143        }
144    }
145}
146
147fn push(map: &mut HashMap<IpAddr, Bucket>, key: IpAddr, at: Instant, kind: Kind) -> Option<IpAddr> {
148    if map.len() >= MAX_TRACKED && !map.contains_key(&key) {
149        return None;
150    }
151    map.entry(key).or_default().attempts.push((at, kind));
152    Some(key)
153}
154
155impl LoginLimiter {
156    /// At most `max` attempts per address and [`BLOCK_MAX_ATTEMPTS`] per block within `window`,
157    /// and `ceiling` once rejections across all addresses reach [`GLOBAL_MAX_FAILURES`].
158    pub fn new(max: usize, window: Duration, ceiling: Ceiling) -> Self {
159        Self {
160            max,
161            window,
162            ceiling,
163            state: Mutex::new(LimiterState {
164                addresses: HashMap::new(),
165                blocks: HashMap::new(),
166                failures: VecDeque::new(),
167                last_sweep: Instant::now(),
168            }),
169        }
170    }
171
172    /// Whether a new attempt from `ip` would be refused.
173    pub fn is_blocked(&self, ip: IpAddr) -> bool {
174        self.refusal(ip).is_some()
175    }
176
177    /// Why a new attempt from `ip` would be refused, if it would.
178    pub fn refusal(&self, ip: IpAddr) -> Option<Refusal> {
179        let mut state = self.state.lock().expect("limiter lock");
180        self.blocked(&mut state, ip, Instant::now())
181    }
182
183    fn blocked(&self, state: &mut LimiterState, ip: IpAddr, now: Instant) -> Option<Refusal> {
184        state.prune(now, self.window);
185        let window = self.window;
186        let ceiling = state.failures.len() >= GLOBAL_MAX_FAILURES;
187        if ceiling && self.ceiling == Ceiling::BlockEveryone {
188            return Some(Refusal::TooMany);
189        }
190        let LimiterState {
191            addresses, blocks, ..
192        } = state;
193        let addresses_full = addresses.len() >= MAX_TRACKED;
194        let blocks_full = blocks.len() >= MAX_TRACKED;
195        let block = blocks.get_mut(&block_key(ip)).map(|b| {
196            b.prune(now, window);
197            &*b
198        });
199        if block.is_some_and(|b| b.attempts.len() >= BLOCK_MAX_ATTEMPTS) {
200            return Some(Refusal::TooMany);
201        }
202        match addresses.get_mut(&address_key(ip)) {
203            Some(b) => {
204                b.prune(now, window);
205                if b.attempts.len() >= self.max || (ceiling && b.has_failure()) {
206                    return Some(Refusal::TooMany);
207                }
208            }
209            // Untracked because the table is full: judge the address by its block instead.
210            None if addresses_full => match block {
211                Some(b) if ceiling && b.has_failure() => return Some(Refusal::TooMany),
212                None if blocks_full && ceiling => return Some(Refusal::Busy),
213                _ => {}
214            },
215            None => {}
216        }
217        None
218    }
219
220    /// Records a rejected attempt from `ip` that was not reserved first.
221    pub fn record_failure(&self, ip: IpAddr) {
222        let mut state = self.state.lock().expect("limiter lock");
223        let now = Instant::now();
224        state.prune(now, self.window);
225        state.failures.push_back(now);
226        push(&mut state.addresses, address_key(ip), now, Kind::Failure);
227        push(&mut state.blocks, block_key(ip), now, Kind::Failure);
228    }
229
230    /// Counts an attempt before it is checked, so concurrent attempts share the per-client and
231    /// per-block limits. Settle it with [`Self::fail`] if the credential is rejected, otherwise
232    /// with [`Self::refund`]. Until then it does not count toward the global ceiling.
233    pub fn try_reserve(&self, ip: IpAddr) -> Result<Reservation, Refusal> {
234        let mut state = self.state.lock().expect("limiter lock");
235        let now = Instant::now();
236        if let Some(refusal) = self.blocked(&mut state, ip, now) {
237            return Err(refusal);
238        }
239        let address = push(&mut state.addresses, address_key(ip), now, Kind::Pending);
240        let block = push(&mut state.blocks, block_key(ip), now, Kind::Pending);
241        Ok(Reservation {
242            address,
243            block,
244            at: now,
245        })
246    }
247
248    /// Gives a reserved attempt back: it was accepted, or could not be checked.
249    pub fn refund(&self, reservation: Reservation) {
250        let mut state = self.state.lock().expect("limiter lock");
251        Self::take(&mut state, &reservation);
252    }
253
254    /// Keeps a reserved attempt as a rejection, counted toward the global ceiling too.
255    pub fn fail(&self, reservation: Reservation) {
256        let mut state = self.state.lock().expect("limiter lock");
257        let now = Instant::now();
258        Self::take(&mut state, &reservation);
259        state.failures.push_back(now);
260        if let Some(k) = reservation.address {
261            state
262                .addresses
263                .entry(k)
264                .or_default()
265                .attempts
266                .push((reservation.at, Kind::Failure));
267        }
268        if let Some(k) = reservation.block {
269            state
270                .blocks
271                .entry(k)
272                .or_default()
273                .attempts
274                .push((reservation.at, Kind::Failure));
275        }
276    }
277
278    fn take(state: &mut LimiterState, r: &Reservation) {
279        if let Some(b) = r.address.and_then(|k| state.addresses.get_mut(&k)) {
280            b.take(r.at);
281        }
282        if let Some(b) = r.block.and_then(|k| state.blocks.get_mut(&k)) {
283            b.take(r.at);
284        }
285    }
286}
287
288/// An attempt counted by [`LoginLimiter::try_reserve`] until it is settled.
289#[derive(Debug)]
290#[must_use = "settle the reservation with fail or refund"]
291pub struct Reservation {
292    address: Option<IpAddr>,
293    block: Option<IpAddr>,
294    at: Instant,
295}
296
297/// Remembers the ids (`jti`) of one-time tokens until they expire, so each is used once.
298pub struct ReplayGuard {
299    used: Mutex<HashMap<String, u64>>,
300}
301
302impl ReplayGuard {
303    /// Remembers nothing yet.
304    pub fn new() -> Self {
305        Self {
306            used: Mutex::new(HashMap::new()),
307        }
308    }
309
310    /// Whether this is the first use of `jti`, a token expiring at `exp_unix`.
311    pub fn first_use(&self, jti: &str, exp_unix: u64) -> bool {
312        let now = jsonwebtoken::get_current_timestamp();
313        let mut used = self.used.lock().expect("replay lock");
314        // Tokens stay valid for the JWT leeway after `exp`, so remember them that long too.
315        used.retain(|_, exp| *exp + crate::jwt::LEEWAY_SECS >= now);
316        used.insert(jti.to_string(), exp_unix).is_none()
317    }
318
319    #[cfg(test)]
320    fn len(&self) -> usize {
321        self.used.lock().unwrap().len()
322    }
323}
324
325impl Default for ReplayGuard {
326    fn default() -> Self {
327        Self::new()
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    #[test]
336    fn limiter_blocks_after_max_failures() {
337        let l = LoginLimiter::new(3, Duration::from_secs(60), Ceiling::BlockFailing);
338        let ip: IpAddr = "10.0.0.1".parse().unwrap();
339        let other: IpAddr = "10.0.0.2".parse().unwrap();
340        for _ in 0..3 {
341            assert!(!l.is_blocked(ip));
342            l.record_failure(ip);
343        }
344        assert!(l.is_blocked(ip));
345        assert!(!l.is_blocked(other));
346    }
347
348    #[test]
349    fn limiter_forgets_after_window() {
350        let l = LoginLimiter::new(1, Duration::from_millis(20), Ceiling::BlockFailing);
351        let ip: IpAddr = "10.0.0.1".parse().unwrap();
352        l.record_failure(ip);
353        assert!(l.is_blocked(ip));
354        std::thread::sleep(Duration::from_millis(40));
355        assert!(!l.is_blocked(ip));
356    }
357
358    #[test]
359    fn ipv6_addresses_in_one_slash_64_share_a_bucket() {
360        let l = LoginLimiter::new(2, Duration::from_secs(60), Ceiling::BlockFailing);
361        let a: IpAddr = "2001:db8:1:2::1".parse().unwrap();
362        let b: IpAddr = "2001:db8:1:2:ffff:ffff:ffff:ffff".parse().unwrap();
363        let other: IpAddr = "2001:db8:1:3::1".parse().unwrap();
364        l.record_failure(a);
365        l.record_failure(b);
366        assert!(l.is_blocked(a));
367        assert!(l.is_blocked(b));
368        assert!(!l.is_blocked(other));
369    }
370
371    #[test]
372    fn ipv4_mapped_ipv6_is_keyed_as_ipv4() {
373        let l = LoginLimiter::new(1, Duration::from_secs(60), Ceiling::BlockFailing);
374        l.record_failure("::ffff:10.0.0.1".parse().unwrap());
375        assert!(l.is_blocked("10.0.0.1".parse().unwrap()));
376        assert!(!l.is_blocked("::ffff:10.0.0.2".parse().unwrap()));
377    }
378
379    #[test]
380    fn global_ceiling_blocks_only_clients_that_failed_too() {
381        let l = LoginLimiter::new(5, Duration::from_secs(60), Ceiling::BlockFailing);
382        for i in 0..GLOBAL_MAX_FAILURES {
383            let ip = IpAddr::from([10, (i / 20) as u8, (i % 20) as u8, 1]);
384            assert!(!l.is_blocked(ip));
385            l.record_failure(ip);
386        }
387        assert!(
388            !l.is_blocked("192.0.2.1".parse().unwrap()),
389            "a clean client is never blocked by other people's failures"
390        );
391        assert!(l.is_blocked("10.0.0.1".parse().unwrap()));
392        let ip: IpAddr = "192.0.2.2".parse().unwrap();
393        l.record_failure(ip);
394        assert!(
395            l.is_blocked(ip),
396            "one failure is enough once the ceiling is reached"
397        );
398    }
399
400    #[test]
401    fn a_shared_secret_ceiling_blocks_everyone_until_the_window_passes() {
402        let l = LoginLimiter::new(5, Duration::from_millis(200), Ceiling::BlockEveryone);
403        for i in 0..GLOBAL_MAX_FAILURES {
404            l.record_failure(IpAddr::from([10, (i / 20) as u8, (i % 20) as u8, 1]));
405        }
406        let clean: IpAddr = "192.0.2.1".parse().unwrap();
407        assert!(l.is_blocked(clean), "the owner waits too");
408        assert_eq!(l.try_reserve(clean).unwrap_err(), Refusal::TooMany);
409        std::thread::sleep(Duration::from_millis(250));
410        assert!(!l.is_blocked(clean));
411    }
412
413    #[test]
414    fn checks_in_flight_never_count_toward_the_ceiling() {
415        let l = LoginLimiter::new(5, Duration::from_secs(60), Ceiling::BlockFailing);
416        let held: Vec<_> = (0..40u8)
417            .map(|i| l.try_reserve(IpAddr::from([10, i, 0, 1])).expect("allowed"))
418            .collect();
419        assert_eq!(l.state.lock().unwrap().failures.len(), 0);
420        let failed: IpAddr = "192.0.2.3".parse().unwrap();
421        l.record_failure(failed);
422        assert!(
423            !l.is_blocked(failed),
424            "40 checks in flight are not 30 rejections"
425        );
426        for r in held {
427            l.refund(r);
428        }
429    }
430
431    #[test]
432    fn a_rejected_reservation_becomes_a_failure() {
433        let l = LoginLimiter::new(5, Duration::from_secs(60), Ceiling::BlockFailing);
434        let ip: IpAddr = "10.0.0.9".parse().unwrap();
435        let r = l.try_reserve(ip).unwrap();
436        l.fail(r);
437        let state = l.state.lock().unwrap();
438        assert_eq!(state.failures.len(), 1);
439        assert!(state.addresses[&address_key(ip)].has_failure());
440        assert_eq!(state.addresses[&address_key(ip)].attempts.len(), 1);
441    }
442
443    #[test]
444    fn one_wider_block_cannot_spread_over_many_addresses() {
445        let l = LoginLimiter::new(5, Duration::from_secs(60), Ceiling::BlockFailing);
446        for i in 0..BLOCK_MAX_ATTEMPTS as u16 {
447            let ip = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 1, i, 0, 0, 0, 1));
448            let _ = l.try_reserve(ip).expect("each /64 tries once");
449        }
450        let same_block = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 1, 999, 0, 0, 0, 1));
451        assert_eq!(l.try_reserve(same_block).unwrap_err(), Refusal::TooMany);
452        let other_block = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 2, 0, 0, 0, 0, 1));
453        assert!(l.try_reserve(other_block).is_ok());
454        let v4: Vec<_> = (0..BLOCK_MAX_ATTEMPTS as u8)
455            .map(|i| l.try_reserve(IpAddr::from([198, 51, 100, i])).unwrap())
456            .collect();
457        assert_eq!(
458            l.try_reserve("198.51.100.250".parse().unwrap())
459                .unwrap_err(),
460            Refusal::TooMany,
461            "an IPv4 /24 is one block"
462        );
463        for r in v4 {
464            l.refund(r);
465        }
466    }
467
468    #[test]
469    fn a_full_table_judges_new_addresses_by_their_block() {
470        let l = LoginLimiter::new(5, Duration::from_secs(60), Ceiling::BlockFailing);
471        // 10,000 failing addresses in 40 /24s fill the address table and reach the ceiling.
472        for i in 0..MAX_TRACKED as u32 {
473            l.record_failure(IpAddr::from(i.to_be_bytes()));
474        }
475        assert!(
476            !l.is_blocked("203.0.113.7".parse().unwrap()),
477            "a new address in a clean block still gets in"
478        );
479        assert_eq!(
480            l.refusal("0.0.39.200".parse().unwrap()),
481            Some(Refusal::TooMany),
482            "a new address in a failing block does not"
483        );
484        // 10,000 failing blocks fill the block table too: new blocks can't be told apart.
485        let l = LoginLimiter::new(5, Duration::from_secs(60), Ceiling::BlockFailing);
486        for i in 0..MAX_TRACKED as u32 {
487            l.record_failure(IpAddr::from((i << 8).to_be_bytes()));
488        }
489        assert_eq!(
490            l.refusal("203.0.113.7".parse().unwrap()),
491            Some(Refusal::Busy)
492        );
493    }
494
495    #[test]
496    fn reservations_count_at_once_and_refunds_give_them_back() {
497        let l = LoginLimiter::new(3, Duration::from_secs(60), Ceiling::BlockFailing);
498        let ip: IpAddr = "10.0.0.1".parse().unwrap();
499        let held: Vec<_> = (0..3)
500            .map(|_| l.try_reserve(ip).expect("allowed"))
501            .collect();
502        assert_eq!(
503            l.try_reserve(ip).unwrap_err(),
504            Refusal::TooMany,
505            "in-flight attempts count"
506        );
507        for r in held {
508            l.refund(r);
509        }
510        assert!(!l.is_blocked(ip));
511        let r = l.try_reserve(ip).unwrap();
512        l.refund(r);
513        let state = l.state.lock().unwrap();
514        assert!(state.addresses.values().all(|b| b.attempts.is_empty()));
515        assert!(state.failures.is_empty());
516    }
517
518    #[test]
519    fn tracked_addresses_are_capped_but_still_count_globally() {
520        let l = LoginLimiter::new(1, Duration::from_secs(60), Ceiling::BlockFailing);
521        for i in 0..MAX_TRACKED as u32 + 5 {
522            let ip = IpAddr::from(i.to_be_bytes());
523            l.record_failure(ip);
524        }
525        let state = l.state.lock().unwrap();
526        assert_eq!(state.addresses.len(), MAX_TRACKED);
527        assert_eq!(state.failures.len(), MAX_TRACKED + 5);
528    }
529
530    #[test]
531    fn replay_guard_allows_first_use_only() {
532        let g = ReplayGuard::new();
533        let exp = jsonwebtoken::get_current_timestamp() + 60;
534        assert!(g.first_use("jti-1", exp));
535        assert!(!g.first_use("jti-1", exp));
536        assert!(g.first_use("jti-2", exp));
537    }
538
539    #[test]
540    fn replay_guard_remembers_tokens_through_the_leeway() {
541        let g = ReplayGuard::new();
542        let just_expired = jsonwebtoken::get_current_timestamp() - 2;
543        assert!(g.first_use("late", just_expired));
544        assert!(!g.first_use("late", just_expired));
545    }
546
547    #[test]
548    fn replay_guard_prunes_expired() {
549        let g = ReplayGuard::new();
550        let past = jsonwebtoken::get_current_timestamp() - 10;
551        assert!(g.first_use("old", past));
552        g.first_use("trigger-prune", past + 1000);
553        assert_eq!(g.len(), 1);
554    }
555}