Skip to main content

web/
rate_limit.rs

1//! Throttle for the unauthenticated auth endpoints.
2//!
3//! `POST /auth/login` verifies a password against a hash, so without this it is
4//! an unmetered online password oracle on a public site. The limiter keys on
5//! the resolved client address (see [`crate::client_ip`]) rather than on
6//! anything the request can choose.
7
8use crate::client_ip::{TrustedProxies, throttle_key};
9use crate::response::WebError;
10use axum::extract::{ConnectInfo, Request, State};
11use axum::middleware::Next;
12use axum::response::{IntoResponse, Response};
13use ratelimit::{Bucket, Decision, Limits};
14use std::net::{IpAddr, Ipv4Addr, SocketAddr};
15use std::sync::{Arc, Mutex};
16use std::time::Duration;
17
18#[cfg(test)]
19mod tests;
20
21const TOO_MANY_ATTEMPTS: &str = "Too many attempts, try again later";
22
23/// Attempts one address may make against the auth endpoints per window.
24/// Generous for a human typing a password, cheap against a guessing run.
25const MAX_ATTEMPTS: u32 = 10;
26
27const WINDOW: Duration = Duration::from_secs(60);
28
29/// Addresses tracked at once. Beyond this the least-recently-seen is dropped;
30/// see [`ratelimit`] for why eviction beats refusal.
31const TRACKED_ADDRESSES: usize = 8192;
32
33/// Auth attempts allowed across *all* clients per window.
34///
35/// This is what actually binds when the per-client key is cheap to change.
36/// Rotating addresses defeats the per-client bucket — and, past
37/// [`TRACKED_ADDRESSES`], evicts other clients' counters into fresh budgets —
38/// so without a ceiling on the total the throttle can be walked around by
39/// anyone holding an IPv6 allocation. Set well above real traffic: legitimate
40/// users share it, and exhausting it refuses logins site-wide.
41const GLOBAL_MAX_ATTEMPTS: u32 = 300;
42
43/// Token verifications one address may make per window.
44///
45/// Every authenticated request decodes a JWT, and decoding needs the signing
46/// key of whoever the token *claims* to be — an indexed lookup in the global
47/// directory, performed before anything is authenticated. Attacker-chosen
48/// subjects therefore reach the database freely, and the admin pool that serves
49/// them is five connections wide (ADR 0032).
50///
51/// Far above real traffic, because legitimate users share this with every page
52/// load and HTMX poll. It bounds one source, not a distributed flood; the
53/// remaining defence is that a verification is a single primary-key read.
54const MAX_VERIFICATIONS: u32 = 600;
55
56/// Key used when a request arrives with no peer address.
57///
58/// Should not happen — the server installs `ConnectInfo` — but an
59/// unidentifiable request must still be counted rather than waved through, so
60/// they all share one bucket.
61const UNIDENTIFIED: IpAddr = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
62
63/// Shared throttle state, built once at startup.
64pub struct AuthLimiter {
65    per_client: Mutex<Bucket<IpAddr>>,
66    global: Mutex<Bucket<()>>,
67    verification: Mutex<Bucket<IpAddr>>,
68    trusted: TrustedProxies,
69}
70
71impl AuthLimiter {
72    #[must_use]
73    pub fn new(trusted: TrustedProxies) -> Self {
74        Self {
75            per_client: Mutex::new(Bucket::new(Limits {
76                max_attempts: MAX_ATTEMPTS,
77                window: WINDOW,
78                capacity: TRACKED_ADDRESSES,
79            })),
80            global: Mutex::new(Bucket::new(Limits {
81                max_attempts: GLOBAL_MAX_ATTEMPTS,
82                window: WINDOW,
83                capacity: 1,
84            })),
85            verification: Mutex::new(Bucket::new(Limits {
86                max_attempts: MAX_VERIFICATIONS,
87                window: WINDOW,
88                capacity: TRACKED_ADDRESSES,
89            })),
90            trusted,
91        }
92    }
93
94    /// Records an attempt from `peer`, honouring `forwarded_for` only if the
95    /// peer is a trusted proxy.
96    ///
97    /// The per-client ceiling is charged first, and the global one only if the
98    /// client had budget left.
99    ///
100    /// That order is load-bearing. Charging global first spends it on requests
101    /// that are about to be refused anyway, so one address sitting on its own
102    /// exhausted bucket could drain the site-wide budget and deny login to
103    /// everyone — a cheaper attack than the identity rotation the global ceiling
104    /// exists to stop.
105    ///
106    /// A poisoned lock denies: the limiter failing open would silently restore
107    /// the unmetered oracle this exists to close.
108    pub fn check(&self, peer: Option<SocketAddr>, forwarded_for: Option<&str>) -> Decision {
109        let client = self.client_key(peer, forwarded_for);
110
111        let per_client = self
112            .per_client
113            .lock()
114            .map_or(Decision::Deny, |mut bucket| bucket.check(&client));
115
116        if per_client.is_denied() {
117            return Decision::Deny;
118        }
119
120        self.global
121            .lock()
122            .map_or(Decision::Deny, |mut bucket| bucket.check(&()))
123    }
124
125    /// Records a token verification from `peer`.
126    ///
127    /// Separate from the login budget: these are ordinary authenticated
128    /// requests, so the ceiling is far higher and exhausting it must not lock a
129    /// client out of logging in.
130    pub fn check_verification(
131        &self,
132        peer: Option<SocketAddr>,
133        forwarded_for: Option<&str>,
134    ) -> Decision {
135        let client = self.client_key(peer, forwarded_for);
136
137        self.verification
138            .lock()
139            .map_or(Decision::Deny, |mut bucket| bucket.check(&client))
140    }
141
142    fn client_key(&self, peer: Option<SocketAddr>, forwarded_for: Option<&str>) -> IpAddr {
143        peer.map_or(UNIDENTIFIED, |peer| {
144            throttle_key(self.trusted.client_ip(peer, forwarded_for))
145        })
146    }
147}
148
149/// Rejects auth requests from an address that has exceeded its window.
150pub async fn throttle_auth(
151    State(limiter): State<Arc<AuthLimiter>>,
152    request: Request,
153    next: Next,
154) -> Response {
155    let forwarded = crate::client_ip::forwarded_for(request.headers());
156    // Read rather than extracted: a request with no connect info must be
157    // counted, not rejected outright by a failing extractor.
158    let peer = request
159        .extensions()
160        .get::<ConnectInfo<SocketAddr>>()
161        .map(|ConnectInfo(peer)| *peer);
162
163    if limiter.check(peer, forwarded.as_deref()).is_denied() {
164        metrics::counter!(crate::telemetry::AUTH_THROTTLED).increment(1);
165        tracing::warn!("throttled auth attempt from {peer:?}");
166        return WebError::too_many_requests(TOO_MANY_ATTEMPTS).into_response();
167    }
168
169    next.run(request).await
170}
171
172/// Rejects requests from an address making more token verifications than any
173/// real client would.
174pub async fn throttle_verification(
175    State(limiter): State<Arc<AuthLimiter>>,
176    request: Request,
177    next: Next,
178) -> Response {
179    let forwarded = crate::client_ip::forwarded_for(request.headers());
180    let peer = request
181        .extensions()
182        .get::<ConnectInfo<SocketAddr>>()
183        .map(|ConnectInfo(peer)| *peer);
184
185    if limiter
186        .check_verification(peer, forwarded.as_deref())
187        .is_denied()
188    {
189        metrics::counter!(crate::telemetry::AUTH_THROTTLED).increment(1);
190        tracing::warn!("throttled token verification from {peer:?}");
191        return WebError::too_many_requests(TOO_MANY_ATTEMPTS).into_response();
192    }
193
194    next.run(request).await
195}