authr_http 0.1.0

Actix Web integration for authr.
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
use std::{
    collections::HashMap,
    net::IpAddr,
    sync::{
        Mutex,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, Instant},
};

use actix_web::{
    Error, HttpResponse,
    body::{EitherBody, MessageBody},
    dev::{ServiceRequest, ServiceResponse},
    middleware::Next,
    web,
};
use authr_core::config::RateLimitConfig;

const MEMORY_STORE_MAX_ENTRIES: usize = 100_000;
const NO_TRUSTED_IP_KEY: &str = "no-trusted-ip";

static IP_WARNING_LOGGED: AtomicBool = AtomicBool::new(false);

#[derive(Debug, Clone, Copy)]
struct ResolvedRateLimitRule {
    window: Duration,
    max: u32,
}

#[derive(Debug, Clone)]
struct RateLimitEntry {
    count: u32,
    last_request: Instant,
    window: Duration,
}

/// Shared in-memory rate limiter.
///
/// Create one instance outside `HttpServer::new` and share it through
/// `web::Data` so all Actix workers use the same counters.
pub struct RateLimiter {
    config: RateLimitConfig,
    base_path: String,
    entries: Mutex<HashMap<String, RateLimitEntry>>,
}

impl RateLimiter {
    /// Creates a rate limiter with the supplied configuration and base path.
    ///
    /// The base path is normalized so request paths can be matched against
    /// configured rules independently of the application's mount point.
    pub fn new(config: RateLimitConfig, base_path: impl Into<String>) -> Self {
        Self {
            config,
            base_path: normalize_base_path(&base_path.into()),
            entries: Mutex::new(HashMap::new()),
        }
    }

    /// Returns whether rate limiting is enabled.
    pub fn enabled(&self) -> bool {
        self.config.enabled
    }

    /// Checks and consumes one request from the applicable rate-limit bucket.
    ///
    /// Returns `Some(retry_after_seconds)` when the request is rejected,
    /// or `None` when it is allowed.
    ///
    /// Requests are grouped by client IP and normalized route. When the
    /// client IP cannot be determined, requests share a fallback bucket
    /// for the route.
    #[tracing::instrument(target = "middleware::rate_limit::check", skip_all, err)]
    pub fn check(
        &self,
        ip: Option<IpAddr>,
        request_path: &str,
    ) -> Result<Option<u64>, &'static str> {
        let path = self.normalize_request_path(request_path);
        let rule = self.rule_for_path(&path)?;

        let ip = match ip {
            Some(ip) => ip.to_string(),
            None => {
                if !IP_WARNING_LOGGED.swap(true, Ordering::Relaxed) {
                    tracing::warn!(
                        "Could not determine client IP for rate limiting. \
                         Requests without a peer IP will share a per-route bucket. \
                         Configure trusted-proxy support when running behind a reverse proxy."
                    );
                }

                NO_TRUSTED_IP_KEY.to_owned()
            }
        };

        let key = format!("{ip}:{path}");

        self.consume(&key, rule)
    }

    // -------------------- Rule Resolution --------------------

    fn rule_for_path(&self, path: &str) -> Result<ResolvedRateLimitRule, &'static str> {
        // ----- Validate global configuration
        let window = self
            .config
            .window
            .to_std()
            .map_err(|_| "Rate-limit window must be positive")?;

        if window.is_zero() {
            return Err("Rate-limit window must be positive");
        }

        if self.config.max == 0 {
            return Err("Rate-limit maximum must be greater than zero");
        }

        // ----- Custom rules
        let custom_rule = self
            .config
            .custom_rules
            .iter()
            .filter_map(|(pattern, rule)| {
                let pattern = normalize_path(pattern);

                matches_path_or_subpath(path, &pattern).then_some((pattern.len(), rule))
            })
            .max_by_key(|(length, _)| *length);

        if let Some((_, rule)) = custom_rule {
            return Ok(ResolvedRateLimitRule {
                window: rule
                    .window
                    .to_std()
                    .map_err(|_| "Rate-limit window must be positive")?,
                max: rule.max,
            });
        }

        // ----- Built-in rules
        let mut rule = ResolvedRateLimitRule {
            window,
            max: self.config.max,
        };

        // ----- Sensitive authentication endpoints
        if matches_path_or_subpath(path, "/sign-in")
            || matches_path_or_subpath(path, "/sign-up")
            || matches_path_or_subpath(path, "/change-password")
            || matches_path_or_subpath(path, "/change-email")
        {
            rule = ResolvedRateLimitRule {
                window: Duration::from_secs(10),
                max: 3,
            };
        }

        // ----- Email delivery and verification endpoints
        if matches_path_or_subpath(path, "/request-password-reset")
            || matches_path_or_subpath(path, "/send-verification-email")
            || matches_path_or_subpath(path, "/forget-password")
            || matches_path_or_subpath(path, "/email-otp/send-verification-otp")
            || matches_path_or_subpath(path, "/email-otp/request-password-reset")
        {
            rule = ResolvedRateLimitRule {
                window: Duration::from_secs(60),
                max: 3,
            };
        }

        // ----- Email verification attempts
        if matches_path_or_subpath(path, "/verify-email") {
            rule = ResolvedRateLimitRule {
                window: Duration::from_secs(60),
                max: 5,
            };
        }

        // ----- OAuth callbacks
        if matches_path_or_subpath(path, "/callback") {
            rule = ResolvedRateLimitRule {
                window: Duration::from_secs(10),
                max: 10,
            };
        }

        Ok(rule)
    }

    // -------------------- Request Consumption --------------------

    /// Atomically checks and increments a rate-limit bucket.
    ///
    /// The mutex covers the entire read/decide/write operation, preventing
    /// concurrent requests from exceeding the configured maximum.
    ///
    /// Successful requests update the inactivity window. Rejected requests
    /// do not extend the lockout period.
    fn consume(&self, key: &str, rule: ResolvedRateLimitRule) -> Result<Option<u64>, &'static str> {
        let now = Instant::now();

        let mut entries = self
            .entries
            .lock()
            .map_err(|_| "Rate-limit storage lock is poisoned")?;

        prune_expired(&mut entries, now);

        match entries.get_mut(key) {
            None => {
                if entries.len() >= MEMORY_STORE_MAX_ENTRIES {
                    evict_oldest(&mut entries);
                }

                entries.insert(
                    key.to_owned(),
                    RateLimitEntry {
                        count: 1,
                        last_request: now,
                        window: rule.window,
                    },
                );

                Ok(None)
            }

            Some(entry) => {
                let elapsed = now.duration_since(entry.last_request);

                // ----- Reset inactive bucket
                if elapsed >= rule.window {
                    entry.count = 1;
                    entry.last_request = now;
                    entry.window = rule.window;

                    return Ok(None);
                }

                // ----- Reject requests exceeding the limit
                if entry.count >= rule.max {
                    return Ok(Some(retry_after(entry.last_request, rule.window, now)));
                }

                // ----- Consume request
                entry.count += 1;
                entry.last_request = now;
                entry.window = rule.window;

                Ok(None)
            }
        }
    }

    // -------------------- Path Normalization --------------------

    fn normalize_request_path(&self, request_path: &str) -> String {
        let path = request_path.split('?').next().unwrap_or(request_path);
        let path = normalize_path(path);

        if self.base_path.is_empty() {
            return path;
        }

        if path == self.base_path {
            return "/".to_owned();
        }

        if let Some(relative) = path.strip_prefix(&self.base_path)
            && relative.starts_with('/')
        {
            return relative.to_owned();
        }

        path
    }
}

// -------------------- Middleware --------------------

/// Enforces the configured rate limits for authentication requests.
///
/// Requests without a matching limiter in application data fail with an
/// internal server error. When rate limiting is disabled, requests pass
/// through without consuming a bucket.
#[tracing::instrument(target = "middleware::rate_limit::rate_limit", skip_all, err)]
pub async fn rate_limit<B>(
    req: ServiceRequest,
    next: Next<B>,
) -> Result<ServiceResponse<EitherBody<B>>, Error>
where
    B: MessageBody + 'static,
{
    let Some(limiter) = req.app_data::<web::Data<RateLimiter>>().cloned() else {
        tracing::error!("RateLimiter is missing from application data");

        return Ok(req
            .into_response(HttpResponse::InternalServerError().finish())
            .map_into_right_body());
    };

    if !limiter.enabled() {
        return next
            .call(req)
            .await
            .map(ServiceResponse::map_into_left_body);
    }

    let ip = req.peer_addr().map(|address| address.ip());
    let path = req.path().to_owned();

    match limiter.check(ip, &path) {
        Ok(None) => next
            .call(req)
            .await
            .map(ServiceResponse::map_into_left_body),

        Ok(Some(retry_after)) => {
            tracing::debug!(retry_after, "Request rejected by rate limiter");

            let response = HttpResponse::TooManyRequests()
                .insert_header(("Retry-After", retry_after.to_string()))
                .json(serde_json::json!({
                    "message": "Too many requests. Please try again later."
                }));

            Ok(req.into_response(response).map_into_right_body())
        }

        Err(error) => {
            tracing::error!(error, "Rate limiter failed");

            Ok(req
                .into_response(HttpResponse::InternalServerError().finish())
                .map_into_right_body())
        }
    }
}

// -------------------- Helpers --------------------

/// Removes entries whose inactivity window has expired.
fn prune_expired(entries: &mut HashMap<String, RateLimitEntry>, now: Instant) {
    entries.retain(|_, entry| now.duration_since(entry.last_request) < entry.window);
}

/// Evicts the entry with the oldest recorded request.
fn evict_oldest(entries: &mut HashMap<String, RateLimitEntry>) {
    if let Some(oldest_key) = entries
        .iter()
        .min_by_key(|(_, entry)| entry.last_request)
        .map(|(key, _)| key.clone())
    {
        entries.remove(&oldest_key);
    }
}

/// Calculates the remaining window duration, rounded up to whole seconds.
fn retry_after(last_request: Instant, window: Duration, now: Instant) -> u64 {
    let remaining = window.saturating_sub(now.duration_since(last_request));

    remaining
        .as_secs()
        .saturating_add(u64::from(remaining.subsec_nanos() > 0))
        .max(1)
}

/// Returns whether a path matches a prefix or one of its subpaths.
///
/// The slash boundary prevents `/sign-in-extra` from matching `/sign-in`.
fn matches_path_or_subpath(path: &str, prefix: &str) -> bool {
    path == prefix
        || path
            .strip_prefix(prefix)
            .is_some_and(|suffix| suffix.starts_with('/'))
}

/// Normalizes an application base path.
fn normalize_base_path(path: &str) -> String {
    if path.is_empty() || path == "/" {
        return String::new();
    }

    normalize_path(path)
}

/// Ensures a path starts with `/` and has no trailing slash,
/// except when the path is the root path.
fn normalize_path(path: &str) -> String {
    let path = if path.starts_with('/') {
        path.to_owned()
    } else {
        format!("/{path}")
    };

    if path.len() > 1 {
        path.trim_end_matches('/').to_owned()
    } else {
        path
    }
}