GITv
master
throttle.rs292 lines, 12.6 KB
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
//! Brute-force protection for sign-in, by client, so one attacker can't lock the owner out.
//!
//! Each client (an IPv4 address, or an IPv6 /64, which one machine usually controls whole) gets
//! [`FREE_FAILURES`] failed attempts; each one after that locks that client out for longer,
//! from a minute up to [`LONGEST_LOCK`]. A client's failures are forgotten after
//! [`FORGET_AFTER`] without one, so an old attack never turns a later typo into a long lock.
//!
//! On top of that, every client together may fail at most [`GLOBAL_PER_HOUR`] times an hour.
//! That caps how fast a distributed attack can guess. One client, held back by its own lock,
//! can never reach it alone. Browsers that have signed in before carry a trusted-device token
//! (see `gitv_web::auth::Credentials::device_token`) and aren't held to this cap, so many
//! addresses together can't lock the owner out; their own per-client lock still applies.
//!
//! Every method takes the current time, so the rules can be tested without waiting.

use std::collections::{HashMap, VecDeque};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::time::{Duration, Instant};

use axum::extract::{ConnectInfo, FromRequestParts};
use axum::http::request::Parts;
use axum::http::{Extensions, HeaderMap};

/// Failed attempts a client may make before it is locked out.
pub const FREE_FAILURES: u32 = 5;
/// The longest a client's lock lasts; it starts at a minute and doubles with each failure.
pub const LONGEST_LOCK: Duration = Duration::from_secs(15 * 60);
/// How long without a failure before a client's count starts again.
pub const FORGET_AFTER: Duration = Duration::from_secs(60 * 60);
/// Failures allowed per hour from every client together.
pub const GLOBAL_PER_HOUR: usize = 60;
/// Clients remembered at once. Past this, the one quiet longest is forgotten first.
const MAX_CLIENTS: usize = 4096;
const HOUR: Duration = Duration::from_secs(60 * 60);

/// Who is signing in, as far as throttling is concerned: their address, or their IPv6 /64.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Client(IpAddr);

impl Client {
    pub fn new(address: IpAddr) -> Client {
        Client(match address {
            IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
                Some(v4) => IpAddr::V4(v4),
                None => {
                    let prefix = u128::from(v6) & !((1u128 << 64) - 1);
                    IpAddr::V6(Ipv6Addr::from(prefix))
                }
            },
            v4 => v4,
        })
    }

    /// The client a request came from. gitv-web listens on loopback behind Caddy, which puts
    /// the real client's address last in `X-Forwarded-For`; that header is believed only from
    /// a loopback peer, since anyone else could write anything there. Without connection
    /// details (as in unit tests) every request is one unknown client.
    pub fn of(headers: &HeaderMap, extensions: &Extensions) -> Client {
        let peer = extensions.get::<ConnectInfo<SocketAddr>>().map(|ConnectInfo(addr)| addr.ip());
        let forwarded = || {
            let header = headers.get_all("x-forwarded-for").iter().next_back()?.to_str().ok()?;
            header.rsplit(',').next()?.trim().parse::<IpAddr>().ok()
        };
        let address = match peer {
            Some(peer) if peer.is_loopback() => forwarded().unwrap_or(peer),
            Some(peer) => peer,
            None => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
        };
        Client::new(address)
    }
}

/// The address, or the /64 for IPv6, as the logs show it.
impl std::fmt::Display for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0 {
            IpAddr::V4(v4) => write!(f, "{v4}"),
            IpAddr::V6(v6) => write!(f, "{v6}/64"),
        }
    }
}

impl<S: Send + Sync> FromRequestParts<S> for Client {
    type Rejection = std::convert::Infallible;

    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Client, Self::Rejection> {
        Ok(Client::of(&parts.headers, &parts.extensions))
    }
}

/// One client's record.
#[derive(Default)]
struct Record {
    failures: u32,
    last_failure: Option<Instant>,
    locked_until: Option<Instant>,
}

impl Record {
    fn locked_for(&self, now: Instant) -> Option<Duration> {
        self.locked_until.and_then(|until| until.checked_duration_since(now)).filter(|d| !d.is_zero())
    }

    fn forgotten(&self, now: Instant) -> bool {
        self.locked_for(now).is_none() && self.last_failure.is_none_or(|t| now.duration_since(t) >= FORGET_AFTER)
    }

    fn fail(&mut self, now: Instant) {
        if self.forgotten(now) {
            self.failures = 0;
        }
        self.failures += 1;
        self.last_failure = Some(now);
        if let Some(over) = self.failures.checked_sub(FREE_FAILURES + 1) {
            let lock = Duration::from_secs(60).saturating_mul(1 << over.min(10)).min(LONGEST_LOCK);
            self.locked_until = Some(now + lock);
        }
    }
}

#[derive(Default)]
pub struct Throttle {
    clients: HashMap<Client, Record>,
    /// When the failures of the last hour happened, oldest first, at most [`GLOBAL_PER_HOUR`].
    recent: VecDeque<Instant>,
}

impl Throttle {
    /// How long `client` must wait before trying again, if at all. A `trusted` browser (one that
    /// has signed in before) waits only for its own lock, never the global cap.
    pub fn locked_for(&self, client: Client, now: Instant, trusted: bool) -> Option<Duration> {
        let own = self.clients.get(&client).and_then(|r| r.locked_for(now));
        let global = (!trusted && self.recent.len() >= GLOBAL_PER_HOUR)
            .then(|| self.recent.front().and_then(|first| (*first + HOUR).checked_duration_since(now)))
            .flatten()
            .filter(|d| !d.is_zero());
        own.max(global)
    }

    /// Count a failed attempt by `client`.
    pub fn fail(&mut self, client: Client, now: Instant) {
        while self.recent.front().is_some_and(|t| now.duration_since(*t) >= HOUR) {
            self.recent.pop_front();
        }
        if self.recent.len() >= GLOBAL_PER_HOUR {
            self.recent.pop_front();
        }
        self.recent.push_back(now);

        self.clients.retain(|_, record| !record.forgotten(now));
        if self.clients.len() >= MAX_CLIENTS && !self.clients.contains_key(&client) {
            let quietest = self.clients.iter().min_by_key(|(_, r)| r.last_failure).map(|(c, _)| *c);
            if let Some(quietest) = quietest {
                self.clients.remove(&quietest);
            }
        }
        self.clients.entry(client).or_default().fail(now);
    }

    /// `client` got everything right: its own record is cleared. Other clients' are not, and
    /// neither is the global count, which other clients' failures still make up.
    pub fn succeed(&mut self, client: Client) {
        self.clients.remove(&client);
    }

    #[cfg(test)]
    pub fn failures(&self, client: Client) -> u32 {
        self.clients.get(&client).map_or(0, |r| r.failures)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ip(text: &str) -> Client {
        Client::new(text.parse().unwrap())
    }

    #[test]
    fn a_client_is_locked_after_its_free_failures_and_longer_each_time() {
        let (mut throttle, now, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7"));
        (0..FREE_FAILURES).for_each(|_| throttle.fail(a, now));
        assert_eq!(throttle.locked_for(a, now, false), None);
        throttle.fail(a, now);
        assert_eq!(throttle.locked_for(a, now, false), Some(Duration::from_secs(60)));
        throttle.fail(a, now);
        assert_eq!(throttle.locked_for(a, now, false), Some(Duration::from_secs(120)));
        (0..20).for_each(|_| throttle.fail(a, now));
        assert_eq!(throttle.locked_for(a, now, false), Some(LONGEST_LOCK));
    }

    #[test]
    fn one_clients_lock_leaves_the_others_alone() {
        let (mut throttle, now) = (Throttle::default(), Instant::now());
        (0..20).for_each(|_| throttle.fail(ip("203.0.113.7"), now));
        assert!(throttle.locked_for(ip("203.0.113.7"), now, false).is_some());
        assert_eq!(throttle.locked_for(ip("198.51.100.1"), now, false), None, "the owner elsewhere isn't locked");
    }

    #[test]
    fn failures_are_forgotten_after_a_quiet_hour() {
        let (mut throttle, start, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7"));
        (0..12).for_each(|_| throttle.fail(a, start));
        // Long after the lock ran out and an hour after the last failure, one typo is free.
        let later = start + LONGEST_LOCK + FORGET_AFTER;
        throttle.fail(a, later);
        assert_eq!(throttle.locked_for(a, later, false), None);
        assert_eq!(throttle.failures(a), 1);
    }

    #[test]
    fn failures_inside_the_hour_still_count() {
        let (mut throttle, start, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7"));
        (0..=FREE_FAILURES).for_each(|_| throttle.fail(a, start));
        // The minute's lock is over, but the next failure comes well inside the hour.
        let later = start + Duration::from_secs(120);
        assert_eq!(throttle.locked_for(a, later, false), None);
        throttle.fail(a, later);
        assert_eq!(throttle.locked_for(a, later, false), Some(Duration::from_secs(120)));
    }

    #[test]
    fn success_clears_only_that_client() {
        let (mut throttle, now) = (Throttle::default(), Instant::now());
        (0..20).for_each(|_| throttle.fail(ip("203.0.113.7"), now));
        (0..3).for_each(|_| throttle.fail(ip("198.51.100.1"), now));
        throttle.succeed(ip("198.51.100.1"));
        assert_eq!(throttle.failures(ip("198.51.100.1")), 0);
        assert!(throttle.locked_for(ip("203.0.113.7"), now, false).is_some(), "the attacker stays locked");
    }

    #[test]
    fn many_clients_together_are_held_to_the_hourly_rate() {
        let (mut throttle, start) = (Throttle::default(), Instant::now());
        let owner = ip("198.51.100.1");
        // Each attacker address stays within its own free failures.
        for i in 0..GLOBAL_PER_HOUR {
            let at = start + Duration::from_secs(i as u64);
            throttle.fail(Client::new(IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + i as u32))), at);
        }
        let now = start + Duration::from_secs(GLOBAL_PER_HOUR as u64);
        let wait = throttle.locked_for(owner, now, false).expect("the hourly budget is spent");
        assert!(wait <= HOUR && wait > HOUR - Duration::from_secs(61), "{wait:?}");
        assert_eq!(throttle.locked_for(owner, now, true), None, "a browser that signed in before isn't held");
        // As the oldest failures age out of the hour, attempts are allowed again.
        assert_eq!(throttle.locked_for(owner, start + HOUR, false), None);
    }

    #[test]
    fn a_trusted_browser_is_still_held_by_its_own_lock() {
        let (mut throttle, now, typist) = (Throttle::default(), Instant::now(), ip("198.51.100.2"));
        (0..=FREE_FAILURES).for_each(|_| throttle.fail(typist, now));
        assert!(throttle.locked_for(typist, now, true).is_some());
    }

    #[test]
    fn ipv6_clients_are_grouped_by_their_64_and_mapped_ipv4_is_ipv4() {
        assert_eq!(ip("2001:db8:1:2:aaaa::1"), ip("2001:db8:1:2:ffff::9"));
        assert_ne!(ip("2001:db8:1:2::1"), ip("2001:db8:1:3::1"));
        assert_eq!(ip("::ffff:203.0.113.7"), ip("203.0.113.7"));
    }

    #[test]
    fn clients_show_as_their_address_or_64() {
        assert_eq!(ip("203.0.113.7").to_string(), "203.0.113.7");
        assert_eq!(ip("2001:db8:1:2:aaaa::1").to_string(), "2001:db8:1:2::/64");
    }

    #[test]
    fn forwarded_addresses_are_believed_only_from_loopback() {
        let parts = |peer: &str, forwarded: Option<&str>| {
            let mut request = axum::http::Request::builder();
            if let Some(value) = forwarded {
                request = request.header("x-forwarded-for", value);
            }
            let (mut parts, ()) = request.body(()).unwrap().into_parts();
            parts.extensions.insert(ConnectInfo(peer.parse::<SocketAddr>().unwrap()));
            parts
        };
        let of = |peer, forwarded| {
            let parts = parts(peer, forwarded);
            Client::of(&parts.headers, &parts.extensions)
        };
        assert_eq!(of("127.0.0.1:5000", Some("203.0.113.7")), ip("203.0.113.7"), "Caddy's word is taken");
        assert_eq!(of("127.0.0.1:5000", Some("1.2.3.4, 203.0.113.7")), ip("203.0.113.7"), "the last hop is Caddy's");
        assert_eq!(of("127.0.0.1:5000", Some("not an address")), ip("127.0.0.1"));
        assert_eq!(of("127.0.0.1:5000", None), ip("127.0.0.1"));
        assert_eq!(of("[::1]:5000", Some("2001:db8::1")), ip("2001:db8::1"));
        assert_eq!(of("192.0.2.5:5000", Some("203.0.113.7")), ip("192.0.2.5"), "nobody else's is");
    }
}