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

            
8
use crate::client_ip::{TrustedProxies, throttle_key};
9
use crate::response::WebError;
10
use axum::extract::{ConnectInfo, Request, State};
11
use axum::middleware::Next;
12
use axum::response::{IntoResponse, Response};
13
use ratelimit::{Bucket, Decision, Limits};
14
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
15
use std::sync::{Arc, Mutex};
16
use std::time::Duration;
17

            
18
#[cfg(test)]
19
mod tests;
20

            
21
const 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.
25
const MAX_ATTEMPTS: u32 = 10;
26

            
27
const 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.
31
const 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.
41
const 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.
54
const 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.
61
const UNIDENTIFIED: IpAddr = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
62

            
63
/// Shared throttle state, built once at startup.
64
pub struct AuthLimiter {
65
    per_client: Mutex<Bucket<IpAddr>>,
66
    global: Mutex<Bucket<()>>,
67
    verification: Mutex<Bucket<IpAddr>>,
68
    trusted: TrustedProxies,
69
}
70

            
71
impl AuthLimiter {
72
    #[must_use]
73
51
    pub fn new(trusted: TrustedProxies) -> Self {
74
51
        Self {
75
51
            per_client: Mutex::new(Bucket::new(Limits {
76
51
                max_attempts: MAX_ATTEMPTS,
77
51
                window: WINDOW,
78
51
                capacity: TRACKED_ADDRESSES,
79
51
            })),
80
51
            global: Mutex::new(Bucket::new(Limits {
81
51
                max_attempts: GLOBAL_MAX_ATTEMPTS,
82
51
                window: WINDOW,
83
51
                capacity: 1,
84
51
            })),
85
51
            verification: Mutex::new(Bucket::new(Limits {
86
51
                max_attempts: MAX_VERIFICATIONS,
87
51
                window: WINDOW,
88
51
                capacity: TRACKED_ADDRESSES,
89
51
            })),
90
51
            trusted,
91
51
        }
92
51
    }
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
2101
    pub fn check(&self, peer: Option<SocketAddr>, forwarded_for: Option<&str>) -> Decision {
109
2101
        let client = self.client_key(peer, forwarded_for);
110

            
111
2101
        let per_client = self
112
2101
            .per_client
113
2101
            .lock()
114
2101
            .map_or(Decision::Deny, |mut bucket| bucket.check(&client));
115

            
116
2101
        if per_client.is_denied() {
117
1217
            return Decision::Deny;
118
884
        }
119

            
120
884
        self.global
121
884
            .lock()
122
884
            .map_or(Decision::Deny, |mut bucket| bucket.check(&()))
123
2101
    }
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
4816
    pub fn check_verification(
131
4816
        &self,
132
4816
        peer: Option<SocketAddr>,
133
4816
        forwarded_for: Option<&str>,
134
4816
    ) -> Decision {
135
4816
        let client = self.client_key(peer, forwarded_for);
136

            
137
4816
        self.verification
138
4816
            .lock()
139
4816
            .map_or(Decision::Deny, |mut bucket| bucket.check(&client))
140
4816
    }
141

            
142
6917
    fn client_key(&self, peer: Option<SocketAddr>, forwarded_for: Option<&str>) -> IpAddr {
143
6917
        peer.map_or(UNIDENTIFIED, |peer| {
144
6860
            throttle_key(self.trusted.client_ip(peer, forwarded_for))
145
6860
        })
146
6917
    }
147
}
148

            
149
/// Rejects auth requests from an address that has exceeded its window.
150
103
pub async fn throttle_auth(
151
103
    State(limiter): State<Arc<AuthLimiter>>,
152
103
    request: Request,
153
103
    next: Next,
154
103
) -> Response {
155
103
    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
103
    let peer = request
159
103
        .extensions()
160
103
        .get::<ConnectInfo<SocketAddr>>()
161
68
        .map(|ConnectInfo(peer)| *peer);
162

            
163
103
    if limiter.check(peer, forwarded.as_deref()).is_denied() {
164
9
        metrics::counter!(crate::telemetry::AUTH_THROTTLED).increment(1);
165
9
        tracing::warn!("throttled auth attempt from {peer:?}");
166
9
        return WebError::too_many_requests(TOO_MANY_ATTEMPTS).into_response();
167
94
    }
168

            
169
94
    next.run(request).await
170
103
}
171

            
172
/// Rejects requests from an address making more token verifications than any
173
/// real client would.
174
1204
pub async fn throttle_verification(
175
1204
    State(limiter): State<Arc<AuthLimiter>>,
176
1204
    request: Request,
177
1204
    next: Next,
178
1204
) -> Response {
179
1204
    let forwarded = crate::client_ip::forwarded_for(request.headers());
180
1204
    let peer = request
181
1204
        .extensions()
182
1204
        .get::<ConnectInfo<SocketAddr>>()
183
1204
        .map(|ConnectInfo(peer)| *peer);
184

            
185
1204
    if limiter
186
1204
        .check_verification(peer, forwarded.as_deref())
187
1204
        .is_denied()
188
    {
189
2
        metrics::counter!(crate::telemetry::AUTH_THROTTLED).increment(1);
190
2
        tracing::warn!("throttled token verification from {peer:?}");
191
2
        return WebError::too_many_requests(TOO_MANY_ATTEMPTS).into_response();
192
1202
    }
193

            
194
1202
    next.run(request).await
195
1204
}