Skip to main content

bnspell_api/
guard.rs

1use std::collections::HashMap;
2use std::net::IpAddr;
3use std::sync::{Arc, Mutex};
4use std::time::{Duration, Instant};
5
6use axum::http::{HeaderMap, HeaderValue, Method};
7use tower_http::cors::{AllowOrigin, Any, CorsLayer};
8
9pub(crate) const DEFAULT_MAX_BODY_BYTES: usize = 1024 * 1024;
10const MAX_CONFIGURABLE_BODY_BYTES: u64 = 8 * 1024 * 1024;
11const DEFAULT_TIMEOUT_SECS: u64 = 30;
12const DEFAULT_RATE_LIMIT: u32 = 60;
13const DEFAULT_RATE_WINDOW_SECS: u64 = 60;
14const MAX_WINDOW_SECS: u64 = 24 * 60 * 60;
15const MAX_RATE_KEYS: usize = 10_000;
16
17/// HTTP limits for one process. Defaults allow localhost browser callers and a
18/// modest per-IP rate. `from_env` is what the binary uses.
19pub struct ServerConfig {
20    pub(crate) max_body_bytes: usize,
21    pub(crate) request_timeout: Duration,
22    pub(crate) cors: CorsPolicy,
23    pub(crate) rate_limit_requests: u32,
24    pub(crate) rate_limit_window: Duration,
25    pub(crate) trust_proxy: bool,
26}
27
28#[derive(Clone)]
29pub(crate) enum CorsPolicy {
30    /// Any http(s) origin whose host is localhost, 127.0.0.1, or ::1.
31    Localhost,
32    Allowlist(Vec<HeaderValue>),
33}
34
35impl Default for ServerConfig {
36    fn default() -> Self {
37        Self {
38            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
39            request_timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
40            cors: CorsPolicy::Localhost,
41            rate_limit_requests: DEFAULT_RATE_LIMIT,
42            rate_limit_window: Duration::from_secs(DEFAULT_RATE_WINDOW_SECS),
43            trust_proxy: false,
44        }
45    }
46}
47
48struct EnvSettings<'a> {
49    cors_origins: Option<&'a str>,
50    trusted_proxy: Option<&'a str>,
51    max_body_bytes: Option<&'a str>,
52    request_timeout_secs: Option<&'a str>,
53    rate_limit: Option<&'a str>,
54    rate_window_secs: Option<&'a str>,
55}
56
57impl ServerConfig {
58    pub fn from_env() -> Result<Self, String> {
59        let cors_origins = optional_var("BNSPELL_CORS_ORIGINS")?;
60        let trusted_proxy = optional_var("BNSPELL_TRUSTED_PROXY")?;
61        let max_body_bytes = optional_var("BNSPELL_MAX_BODY_BYTES")?;
62        let request_timeout_secs = optional_var("BNSPELL_REQUEST_TIMEOUT_SECS")?;
63        let rate_limit = optional_var("BNSPELL_RATE_LIMIT")?;
64        let rate_window_secs = optional_var("BNSPELL_RATE_WINDOW_SECS")?;
65        Self::from_settings(EnvSettings {
66            cors_origins: cors_origins.as_deref(),
67            trusted_proxy: trusted_proxy.as_deref(),
68            max_body_bytes: max_body_bytes.as_deref(),
69            request_timeout_secs: request_timeout_secs.as_deref(),
70            rate_limit: rate_limit.as_deref(),
71            rate_window_secs: rate_window_secs.as_deref(),
72        })
73    }
74
75    fn from_settings(settings: EnvSettings<'_>) -> Result<Self, String> {
76        let max_body = parse_u64(
77            "BNSPELL_MAX_BODY_BYTES",
78            settings.max_body_bytes,
79            DEFAULT_MAX_BODY_BYTES as u64,
80        )?;
81        if max_body == 0 {
82            return Err("BNSPELL_MAX_BODY_BYTES must be at least 1".to_string());
83        }
84        if max_body > MAX_CONFIGURABLE_BODY_BYTES {
85            return Err(format!(
86                "BNSPELL_MAX_BODY_BYTES must be at most {MAX_CONFIGURABLE_BODY_BYTES}"
87            ));
88        }
89        let max_body_bytes = usize::try_from(max_body)
90            .map_err(|_| "BNSPELL_MAX_BODY_BYTES does not fit in usize".to_string())?;
91        let timeout_secs = parse_u64(
92            "BNSPELL_REQUEST_TIMEOUT_SECS",
93            settings.request_timeout_secs,
94            DEFAULT_TIMEOUT_SECS,
95        )?;
96        let rate_window_secs = parse_u64(
97            "BNSPELL_RATE_WINDOW_SECS",
98            settings.rate_window_secs,
99            DEFAULT_RATE_WINDOW_SECS,
100        )?;
101        let rate_limit = parse_u64(
102            "BNSPELL_RATE_LIMIT",
103            settings.rate_limit,
104            u64::from(DEFAULT_RATE_LIMIT),
105        )?;
106        let rate_limit_requests = u32::try_from(rate_limit)
107            .map_err(|_| format!("BNSPELL_RATE_LIMIT must be at most {}", u32::MAX))?;
108        Ok(Self {
109            max_body_bytes,
110            request_timeout: window_secs("BNSPELL_REQUEST_TIMEOUT_SECS", timeout_secs)?,
111            cors: parse_cors(settings.cors_origins)?,
112            rate_limit_requests,
113            rate_limit_window: window_secs("BNSPELL_RATE_WINDOW_SECS", rate_window_secs)?,
114            trust_proxy: parse_flag("BNSPELL_TRUSTED_PROXY", settings.trusted_proxy)?,
115        })
116    }
117
118    pub(crate) fn cors_layer(&self) -> CorsLayer {
119        let origin = match &self.cors {
120            CorsPolicy::Localhost => {
121                AllowOrigin::predicate(|origin, _| origin.to_str().is_ok_and(is_localhost_origin))
122            }
123            CorsPolicy::Allowlist(origins) => AllowOrigin::list(origins.clone()),
124        };
125        CorsLayer::new()
126            .allow_origin(origin)
127            .allow_methods([
128                Method::GET,
129                Method::HEAD,
130                Method::PUT,
131                Method::POST,
132                Method::DELETE,
133                Method::PATCH,
134            ])
135            .allow_headers(Any)
136    }
137
138    pub(crate) fn rate_limiter(&self) -> RateLimiter {
139        RateLimiter {
140            max_requests: self.rate_limit_requests,
141            window: self.rate_limit_window,
142            trust_proxy: self.trust_proxy,
143            hits: Arc::new(Mutex::new(HashMap::new())),
144        }
145    }
146}
147
148#[derive(Clone)]
149pub(crate) struct RateLimiter {
150    max_requests: u32,
151    window: Duration,
152    trust_proxy: bool,
153    hits: Arc<Mutex<HashMap<String, Window>>>,
154}
155
156struct Window {
157    start: Instant,
158    count: u32,
159}
160
161impl RateLimiter {
162    /// `Ok` when the request may proceed. `Err` is the Retry-After delay in seconds.
163    /// `/health` and `/api/health` are not counted.
164    pub(crate) fn check(
165        &self,
166        path: &str,
167        headers: &HeaderMap,
168        peer: Option<IpAddr>,
169    ) -> Result<(), u64> {
170        if self.max_requests == 0 || path == "/health" || path == "/api/health" {
171            return Ok(());
172        }
173        let key = client_key(headers, peer, self.trust_proxy);
174        let mut hits = self.hits.lock().unwrap_or_else(|err| err.into_inner());
175        let now = Instant::now();
176        if hits.len() >= MAX_RATE_KEYS {
177            let window = self.window;
178            hits.retain(|_, entry| now.saturating_duration_since(entry.start) < window);
179        }
180        if !hits.contains_key(&key) && hits.len() >= MAX_RATE_KEYS {
181            return Err(retry_after_secs(self.window));
182        }
183        let entry = hits.entry(key).or_insert(Window {
184            start: now,
185            count: 0,
186        });
187        if now.saturating_duration_since(entry.start) >= self.window {
188            entry.start = now;
189            entry.count = 0;
190        }
191        if entry.count >= self.max_requests {
192            let remaining = self
193                .window
194                .saturating_sub(now.saturating_duration_since(entry.start));
195            return Err(retry_after_secs(remaining));
196        }
197        entry.count += 1;
198        Ok(())
199    }
200}
201
202/// With one trusted reverse proxy, the rightmost X-Forwarded-For entry is the
203/// peer that proxy accepted. Entries to its left are whatever the client sent.
204fn client_key(headers: &HeaderMap, peer: Option<IpAddr>, trust_proxy: bool) -> String {
205    let from_proxy = if trust_proxy {
206        forwarded_ip(headers)
207    } else {
208        None
209    };
210    match from_proxy.or(peer) {
211        Some(ip) => ip.to_string(),
212        None => "unknown".to_string(),
213    }
214}
215
216fn retry_after_secs(remaining: Duration) -> u64 {
217    let whole = remaining.as_secs();
218    if remaining.subsec_nanos() == 0 {
219        whole.max(1)
220    } else {
221        whole.saturating_add(1)
222    }
223}
224
225fn forwarded_ip(headers: &HeaderMap) -> Option<IpAddr> {
226    let value = headers.get("x-forwarded-for")?.to_str().ok()?;
227    value
228        .split(',')
229        .rev()
230        .map(str::trim)
231        .find_map(parse_ip_token)
232}
233
234fn parse_ip_token(token: &str) -> Option<IpAddr> {
235    let token = token.trim_matches(|ch| ch == '"' || ch == '[' || ch == ']');
236    if let Ok(ip) = token.parse::<IpAddr>() {
237        return Some(ip);
238    }
239    let (host, port) = token.rsplit_once(':')?;
240    if port.is_empty() || !port.bytes().all(|byte| byte.is_ascii_digit()) {
241        return None;
242    }
243    host.parse().ok()
244}
245
246fn optional_var(name: &str) -> Result<Option<String>, String> {
247    match std::env::var(name) {
248        Ok(value) => Ok(Some(value)),
249        Err(std::env::VarError::NotPresent) => Ok(None),
250        Err(std::env::VarError::NotUnicode(_)) => Err(format!("{name} is not valid Unicode")),
251    }
252}
253
254fn parse_cors(value: Option<&str>) -> Result<CorsPolicy, String> {
255    let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
256        return Ok(CorsPolicy::Localhost);
257    };
258    let mut origins = Vec::new();
259    for entry in value.split(',') {
260        let entry = entry.trim();
261        if entry.is_empty() {
262            continue;
263        }
264        origins.push(parse_origin(entry)?);
265    }
266    if origins.is_empty() {
267        return Err("BNSPELL_CORS_ORIGINS is empty".to_string());
268    }
269    Ok(CorsPolicy::Allowlist(origins))
270}
271
272fn parse_origin(value: &str) -> Result<HeaderValue, String> {
273    if value.contains('*') {
274        return Err(
275            "BNSPELL_CORS_ORIGINS must list exact origins; a wildcard is not allowed".to_string(),
276        );
277    }
278    if !(value.starts_with("http://") || value.starts_with("https://")) {
279        return Err(format!("invalid BNSPELL_CORS_ORIGINS entry: {value}"));
280    }
281    let rest = value.split_once("://").map(|(_, rest)| rest).unwrap_or("");
282    if rest.is_empty()
283        || rest.contains('/')
284        || rest.contains('?')
285        || rest.contains('#')
286        || rest.contains('@')
287        || rest.contains(' ')
288    {
289        return Err(format!("invalid BNSPELL_CORS_ORIGINS entry: {value}"));
290    }
291    HeaderValue::from_str(value).map_err(|_| format!("invalid BNSPELL_CORS_ORIGINS entry: {value}"))
292}
293
294fn is_localhost_origin(origin: &str) -> bool {
295    let Some(authority) = origin
296        .strip_prefix("http://")
297        .or_else(|| origin.strip_prefix("https://"))
298    else {
299        return false;
300    };
301    if authority.is_empty()
302        || authority.contains('/')
303        || authority.contains('@')
304        || authority.contains('?')
305        || authority.contains('#')
306    {
307        return false;
308    }
309    matches!(host_of(authority), "localhost" | "127.0.0.1" | "::1")
310}
311
312fn host_of(authority: &str) -> &str {
313    if let Some(rest) = authority.strip_prefix('[') {
314        let Some((host, after)) = rest.split_once(']') else {
315            return "";
316        };
317        if after.is_empty()
318            || (after.starts_with(':')
319                && !after[1..].is_empty()
320                && after[1..].bytes().all(|byte| byte.is_ascii_digit()))
321        {
322            return host;
323        }
324        return "";
325    }
326    match authority.rsplit_once(':') {
327        Some((host, port))
328            if !host.is_empty()
329                && !host.contains(':')
330                && !port.is_empty()
331                && port.bytes().all(|byte| byte.is_ascii_digit()) =>
332        {
333            host
334        }
335        _ => authority,
336    }
337}
338
339fn parse_flag(name: &str, value: Option<&str>) -> Result<bool, String> {
340    match value.map(str::trim) {
341        None | Some("") | Some("0") | Some("false") => Ok(false),
342        Some("1") | Some("true") => Ok(true),
343        Some(other) => Err(format!("invalid {name}: {other}")),
344    }
345}
346
347fn parse_u64(name: &str, value: Option<&str>, default: u64) -> Result<u64, String> {
348    match value.map(str::trim) {
349        None | Some("") => Ok(default),
350        Some(text) => text
351            .parse::<u64>()
352            .map_err(|_| format!("invalid {name}: {text}")),
353    }
354}
355
356fn window_secs(name: &str, value: u64) -> Result<Duration, String> {
357    if value == 0 {
358        return Err(format!("{name} must be at least 1"));
359    }
360    if value > MAX_WINDOW_SECS {
361        return Err(format!("{name} must be at most {MAX_WINDOW_SECS}"));
362    }
363    Ok(Duration::from_secs(value))
364}
365
366#[cfg(test)]
367mod tests {
368    use super::{
369        ServerConfig, client_key, is_localhost_origin, parse_cors, parse_flag, parse_ip_token,
370    };
371    use axum::http::{HeaderMap, HeaderValue};
372    use std::net::IpAddr;
373    use std::time::Duration;
374
375    fn settings_default() -> ServerConfig {
376        ServerConfig::from_settings(super::EnvSettings {
377            cors_origins: None,
378            trusted_proxy: None,
379            max_body_bytes: None,
380            request_timeout_secs: None,
381            rate_limit: None,
382            rate_window_secs: None,
383        })
384        .unwrap()
385    }
386
387    #[test]
388    fn unset_env_matches_the_defaults() {
389        let config = settings_default();
390        assert_eq!(config.max_body_bytes, super::DEFAULT_MAX_BODY_BYTES);
391        assert_eq!(config.request_timeout, Duration::from_secs(30));
392        assert_eq!(config.rate_limit_requests, 60);
393        assert_eq!(config.rate_limit_window, Duration::from_secs(60));
394        assert!(!config.trust_proxy);
395        assert!(matches!(config.cors, super::CorsPolicy::Localhost));
396    }
397
398    #[test]
399    fn cors_allowlist_rejects_a_wildcard_and_a_path() {
400        assert!(parse_cors(Some("*")).is_err());
401        assert!(parse_cors(Some("https://example.com/app")).is_err());
402        assert!(parse_cors(Some("example.com")).is_err());
403        let policy = parse_cors(Some(" https://app.example.com, http://localhost:3000 ")).unwrap();
404        match policy {
405            super::CorsPolicy::Allowlist(origins) => {
406                assert_eq!(
407                    origins,
408                    vec![
409                        HeaderValue::from_static("https://app.example.com"),
410                        HeaderValue::from_static("http://localhost:3000"),
411                    ]
412                );
413            }
414            super::CorsPolicy::Localhost => panic!("expected an allowlist"),
415        }
416    }
417
418    #[test]
419    fn localhost_origins_allow_loopback_hosts_only() {
420        for origin in [
421            "http://localhost:3000",
422            "https://localhost",
423            "http://127.0.0.1:8787",
424            "http://[::1]:3000",
425        ] {
426            assert!(is_localhost_origin(origin), "{origin}");
427        }
428        for origin in [
429            "https://hoppscotch.io",
430            "http://localhost.evil.com",
431            "http://evil.com@localhost",
432            "http://127.0.0.1.example.com",
433            "null",
434        ] {
435            assert!(!is_localhost_origin(origin), "{origin}");
436        }
437    }
438
439    #[test]
440    fn numeric_settings_reject_zero_and_garbage() {
441        let err = ServerConfig::from_settings(super::EnvSettings {
442            cors_origins: None,
443            trusted_proxy: Some("yes"),
444            max_body_bytes: Some("0"),
445            request_timeout_secs: None,
446            rate_limit: None,
447            rate_window_secs: None,
448        });
449        assert!(err.is_err());
450        assert!(parse_flag("BNSPELL_TRUSTED_PROXY", Some("true")).unwrap());
451        assert!(!parse_flag("BNSPELL_TRUSTED_PROXY", Some("false")).unwrap());
452        let config = ServerConfig::from_settings(super::EnvSettings {
453            cors_origins: None,
454            trusted_proxy: Some("1"),
455            max_body_bytes: Some("4096"),
456            request_timeout_secs: Some("5"),
457            rate_limit: Some("0"),
458            rate_window_secs: Some("10"),
459        })
460        .unwrap();
461        assert!(config.trust_proxy);
462        assert_eq!(config.max_body_bytes, 4096);
463        assert_eq!(config.request_timeout, Duration::from_secs(5));
464        assert_eq!(config.rate_limit_requests, 0);
465        assert_eq!(config.rate_limit_window, Duration::from_secs(10));
466    }
467
468    #[test]
469    fn forwarded_for_is_the_rightmost_address_and_only_when_trusted() {
470        let mut headers = HeaderMap::new();
471        headers.insert(
472            "x-forwarded-for",
473            HeaderValue::from_static("9.9.9.9, 203.0.113.8"),
474        );
475        let peer: IpAddr = "198.51.100.4".parse().unwrap();
476        assert_eq!(client_key(&headers, Some(peer), false), "198.51.100.4");
477        assert_eq!(client_key(&headers, Some(peer), true), "203.0.113.8");
478        assert_eq!(
479            parse_ip_token("203.0.113.8:443").unwrap().to_string(),
480            "203.0.113.8"
481        );
482        assert_eq!(client_key(&HeaderMap::new(), None, false), "unknown");
483    }
484
485    #[test]
486    fn rate_limiter_resets_per_key_and_skips_health() {
487        let limiter = ServerConfig {
488            rate_limit_requests: 1,
489            trust_proxy: true,
490            ..ServerConfig::default()
491        }
492        .rate_limiter();
493        let mut first = HeaderMap::new();
494        first.insert("x-forwarded-for", HeaderValue::from_static("203.0.113.1"));
495        let mut second = HeaderMap::new();
496        second.insert("x-forwarded-for", HeaderValue::from_static("203.0.113.2"));
497        assert!(limiter.check("/api/check", &first, None).is_ok());
498        assert!(limiter.check("/api/check", &first, None).is_err());
499        assert!(limiter.check("/health", &first, None).is_ok());
500        assert!(limiter.check("/api/health", &first, None).is_ok());
501        assert!(limiter.check("/api/suggest", &second, None).is_ok());
502    }
503}