bnspell-api 0.1.0

HTTP API for the Bengali spell checker
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use axum::http::{HeaderMap, HeaderValue, Method};
use tower_http::cors::{AllowOrigin, Any, CorsLayer};

pub(crate) const DEFAULT_MAX_BODY_BYTES: usize = 1024 * 1024;
const MAX_CONFIGURABLE_BODY_BYTES: u64 = 8 * 1024 * 1024;
const DEFAULT_TIMEOUT_SECS: u64 = 30;
const DEFAULT_RATE_LIMIT: u32 = 60;
const DEFAULT_RATE_WINDOW_SECS: u64 = 60;
const MAX_WINDOW_SECS: u64 = 24 * 60 * 60;
const MAX_RATE_KEYS: usize = 10_000;

/// HTTP limits for one process. Defaults allow localhost browser callers and a
/// modest per-IP rate. `from_env` is what the binary uses.
pub struct ServerConfig {
    pub(crate) max_body_bytes: usize,
    pub(crate) request_timeout: Duration,
    pub(crate) cors: CorsPolicy,
    pub(crate) rate_limit_requests: u32,
    pub(crate) rate_limit_window: Duration,
    pub(crate) trust_proxy: bool,
}

#[derive(Clone)]
pub(crate) enum CorsPolicy {
    /// Any http(s) origin whose host is localhost, 127.0.0.1, or ::1.
    Localhost,
    Allowlist(Vec<HeaderValue>),
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
            request_timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
            cors: CorsPolicy::Localhost,
            rate_limit_requests: DEFAULT_RATE_LIMIT,
            rate_limit_window: Duration::from_secs(DEFAULT_RATE_WINDOW_SECS),
            trust_proxy: false,
        }
    }
}

struct EnvSettings<'a> {
    cors_origins: Option<&'a str>,
    trusted_proxy: Option<&'a str>,
    max_body_bytes: Option<&'a str>,
    request_timeout_secs: Option<&'a str>,
    rate_limit: Option<&'a str>,
    rate_window_secs: Option<&'a str>,
}

impl ServerConfig {
    pub fn from_env() -> Result<Self, String> {
        let cors_origins = optional_var("BNSPELL_CORS_ORIGINS")?;
        let trusted_proxy = optional_var("BNSPELL_TRUSTED_PROXY")?;
        let max_body_bytes = optional_var("BNSPELL_MAX_BODY_BYTES")?;
        let request_timeout_secs = optional_var("BNSPELL_REQUEST_TIMEOUT_SECS")?;
        let rate_limit = optional_var("BNSPELL_RATE_LIMIT")?;
        let rate_window_secs = optional_var("BNSPELL_RATE_WINDOW_SECS")?;
        Self::from_settings(EnvSettings {
            cors_origins: cors_origins.as_deref(),
            trusted_proxy: trusted_proxy.as_deref(),
            max_body_bytes: max_body_bytes.as_deref(),
            request_timeout_secs: request_timeout_secs.as_deref(),
            rate_limit: rate_limit.as_deref(),
            rate_window_secs: rate_window_secs.as_deref(),
        })
    }

    fn from_settings(settings: EnvSettings<'_>) -> Result<Self, String> {
        let max_body = parse_u64(
            "BNSPELL_MAX_BODY_BYTES",
            settings.max_body_bytes,
            DEFAULT_MAX_BODY_BYTES as u64,
        )?;
        if max_body == 0 {
            return Err("BNSPELL_MAX_BODY_BYTES must be at least 1".to_string());
        }
        if max_body > MAX_CONFIGURABLE_BODY_BYTES {
            return Err(format!(
                "BNSPELL_MAX_BODY_BYTES must be at most {MAX_CONFIGURABLE_BODY_BYTES}"
            ));
        }
        let max_body_bytes = usize::try_from(max_body)
            .map_err(|_| "BNSPELL_MAX_BODY_BYTES does not fit in usize".to_string())?;
        let timeout_secs = parse_u64(
            "BNSPELL_REQUEST_TIMEOUT_SECS",
            settings.request_timeout_secs,
            DEFAULT_TIMEOUT_SECS,
        )?;
        let rate_window_secs = parse_u64(
            "BNSPELL_RATE_WINDOW_SECS",
            settings.rate_window_secs,
            DEFAULT_RATE_WINDOW_SECS,
        )?;
        let rate_limit = parse_u64(
            "BNSPELL_RATE_LIMIT",
            settings.rate_limit,
            u64::from(DEFAULT_RATE_LIMIT),
        )?;
        let rate_limit_requests = u32::try_from(rate_limit)
            .map_err(|_| format!("BNSPELL_RATE_LIMIT must be at most {}", u32::MAX))?;
        Ok(Self {
            max_body_bytes,
            request_timeout: window_secs("BNSPELL_REQUEST_TIMEOUT_SECS", timeout_secs)?,
            cors: parse_cors(settings.cors_origins)?,
            rate_limit_requests,
            rate_limit_window: window_secs("BNSPELL_RATE_WINDOW_SECS", rate_window_secs)?,
            trust_proxy: parse_flag("BNSPELL_TRUSTED_PROXY", settings.trusted_proxy)?,
        })
    }

    pub(crate) fn cors_layer(&self) -> CorsLayer {
        let origin = match &self.cors {
            CorsPolicy::Localhost => {
                AllowOrigin::predicate(|origin, _| origin.to_str().is_ok_and(is_localhost_origin))
            }
            CorsPolicy::Allowlist(origins) => AllowOrigin::list(origins.clone()),
        };
        CorsLayer::new()
            .allow_origin(origin)
            .allow_methods([
                Method::GET,
                Method::HEAD,
                Method::PUT,
                Method::POST,
                Method::DELETE,
                Method::PATCH,
            ])
            .allow_headers(Any)
    }

    pub(crate) fn rate_limiter(&self) -> RateLimiter {
        RateLimiter {
            max_requests: self.rate_limit_requests,
            window: self.rate_limit_window,
            trust_proxy: self.trust_proxy,
            hits: Arc::new(Mutex::new(HashMap::new())),
        }
    }
}

#[derive(Clone)]
pub(crate) struct RateLimiter {
    max_requests: u32,
    window: Duration,
    trust_proxy: bool,
    hits: Arc<Mutex<HashMap<String, Window>>>,
}

struct Window {
    start: Instant,
    count: u32,
}

impl RateLimiter {
    /// `Ok` when the request may proceed. `Err` is the Retry-After delay in seconds.
    /// `/health` and `/api/health` are not counted.
    pub(crate) fn check(
        &self,
        path: &str,
        headers: &HeaderMap,
        peer: Option<IpAddr>,
    ) -> Result<(), u64> {
        if self.max_requests == 0 || path == "/health" || path == "/api/health" {
            return Ok(());
        }
        let key = client_key(headers, peer, self.trust_proxy);
        let mut hits = self.hits.lock().unwrap_or_else(|err| err.into_inner());
        let now = Instant::now();
        if hits.len() >= MAX_RATE_KEYS {
            let window = self.window;
            hits.retain(|_, entry| now.saturating_duration_since(entry.start) < window);
        }
        if !hits.contains_key(&key) && hits.len() >= MAX_RATE_KEYS {
            return Err(retry_after_secs(self.window));
        }
        let entry = hits.entry(key).or_insert(Window {
            start: now,
            count: 0,
        });
        if now.saturating_duration_since(entry.start) >= self.window {
            entry.start = now;
            entry.count = 0;
        }
        if entry.count >= self.max_requests {
            let remaining = self
                .window
                .saturating_sub(now.saturating_duration_since(entry.start));
            return Err(retry_after_secs(remaining));
        }
        entry.count += 1;
        Ok(())
    }
}

/// With one trusted reverse proxy, the rightmost X-Forwarded-For entry is the
/// peer that proxy accepted. Entries to its left are whatever the client sent.
fn client_key(headers: &HeaderMap, peer: Option<IpAddr>, trust_proxy: bool) -> String {
    let from_proxy = if trust_proxy {
        forwarded_ip(headers)
    } else {
        None
    };
    match from_proxy.or(peer) {
        Some(ip) => ip.to_string(),
        None => "unknown".to_string(),
    }
}

fn retry_after_secs(remaining: Duration) -> u64 {
    let whole = remaining.as_secs();
    if remaining.subsec_nanos() == 0 {
        whole.max(1)
    } else {
        whole.saturating_add(1)
    }
}

fn forwarded_ip(headers: &HeaderMap) -> Option<IpAddr> {
    let value = headers.get("x-forwarded-for")?.to_str().ok()?;
    value
        .split(',')
        .rev()
        .map(str::trim)
        .find_map(parse_ip_token)
}

fn parse_ip_token(token: &str) -> Option<IpAddr> {
    let token = token.trim_matches(|ch| ch == '"' || ch == '[' || ch == ']');
    if let Ok(ip) = token.parse::<IpAddr>() {
        return Some(ip);
    }
    let (host, port) = token.rsplit_once(':')?;
    if port.is_empty() || !port.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    host.parse().ok()
}

fn optional_var(name: &str) -> Result<Option<String>, String> {
    match std::env::var(name) {
        Ok(value) => Ok(Some(value)),
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(std::env::VarError::NotUnicode(_)) => Err(format!("{name} is not valid Unicode")),
    }
}

fn parse_cors(value: Option<&str>) -> Result<CorsPolicy, String> {
    let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
        return Ok(CorsPolicy::Localhost);
    };
    let mut origins = Vec::new();
    for entry in value.split(',') {
        let entry = entry.trim();
        if entry.is_empty() {
            continue;
        }
        origins.push(parse_origin(entry)?);
    }
    if origins.is_empty() {
        return Err("BNSPELL_CORS_ORIGINS is empty".to_string());
    }
    Ok(CorsPolicy::Allowlist(origins))
}

fn parse_origin(value: &str) -> Result<HeaderValue, String> {
    if value.contains('*') {
        return Err(
            "BNSPELL_CORS_ORIGINS must list exact origins; a wildcard is not allowed".to_string(),
        );
    }
    if !(value.starts_with("http://") || value.starts_with("https://")) {
        return Err(format!("invalid BNSPELL_CORS_ORIGINS entry: {value}"));
    }
    let rest = value.split_once("://").map(|(_, rest)| rest).unwrap_or("");
    if rest.is_empty()
        || rest.contains('/')
        || rest.contains('?')
        || rest.contains('#')
        || rest.contains('@')
        || rest.contains(' ')
    {
        return Err(format!("invalid BNSPELL_CORS_ORIGINS entry: {value}"));
    }
    HeaderValue::from_str(value).map_err(|_| format!("invalid BNSPELL_CORS_ORIGINS entry: {value}"))
}

fn is_localhost_origin(origin: &str) -> bool {
    let Some(authority) = origin
        .strip_prefix("http://")
        .or_else(|| origin.strip_prefix("https://"))
    else {
        return false;
    };
    if authority.is_empty()
        || authority.contains('/')
        || authority.contains('@')
        || authority.contains('?')
        || authority.contains('#')
    {
        return false;
    }
    matches!(host_of(authority), "localhost" | "127.0.0.1" | "::1")
}

fn host_of(authority: &str) -> &str {
    if let Some(rest) = authority.strip_prefix('[') {
        let Some((host, after)) = rest.split_once(']') else {
            return "";
        };
        if after.is_empty()
            || (after.starts_with(':')
                && !after[1..].is_empty()
                && after[1..].bytes().all(|byte| byte.is_ascii_digit()))
        {
            return host;
        }
        return "";
    }
    match authority.rsplit_once(':') {
        Some((host, port))
            if !host.is_empty()
                && !host.contains(':')
                && !port.is_empty()
                && port.bytes().all(|byte| byte.is_ascii_digit()) =>
        {
            host
        }
        _ => authority,
    }
}

fn parse_flag(name: &str, value: Option<&str>) -> Result<bool, String> {
    match value.map(str::trim) {
        None | Some("") | Some("0") | Some("false") => Ok(false),
        Some("1") | Some("true") => Ok(true),
        Some(other) => Err(format!("invalid {name}: {other}")),
    }
}

fn parse_u64(name: &str, value: Option<&str>, default: u64) -> Result<u64, String> {
    match value.map(str::trim) {
        None | Some("") => Ok(default),
        Some(text) => text
            .parse::<u64>()
            .map_err(|_| format!("invalid {name}: {text}")),
    }
}

fn window_secs(name: &str, value: u64) -> Result<Duration, String> {
    if value == 0 {
        return Err(format!("{name} must be at least 1"));
    }
    if value > MAX_WINDOW_SECS {
        return Err(format!("{name} must be at most {MAX_WINDOW_SECS}"));
    }
    Ok(Duration::from_secs(value))
}

#[cfg(test)]
mod tests {
    use super::{
        ServerConfig, client_key, is_localhost_origin, parse_cors, parse_flag, parse_ip_token,
    };
    use axum::http::{HeaderMap, HeaderValue};
    use std::net::IpAddr;
    use std::time::Duration;

    fn settings_default() -> ServerConfig {
        ServerConfig::from_settings(super::EnvSettings {
            cors_origins: None,
            trusted_proxy: None,
            max_body_bytes: None,
            request_timeout_secs: None,
            rate_limit: None,
            rate_window_secs: None,
        })
        .unwrap()
    }

    #[test]
    fn unset_env_matches_the_defaults() {
        let config = settings_default();
        assert_eq!(config.max_body_bytes, super::DEFAULT_MAX_BODY_BYTES);
        assert_eq!(config.request_timeout, Duration::from_secs(30));
        assert_eq!(config.rate_limit_requests, 60);
        assert_eq!(config.rate_limit_window, Duration::from_secs(60));
        assert!(!config.trust_proxy);
        assert!(matches!(config.cors, super::CorsPolicy::Localhost));
    }

    #[test]
    fn cors_allowlist_rejects_a_wildcard_and_a_path() {
        assert!(parse_cors(Some("*")).is_err());
        assert!(parse_cors(Some("https://example.com/app")).is_err());
        assert!(parse_cors(Some("example.com")).is_err());
        let policy = parse_cors(Some(" https://app.example.com, http://localhost:3000 ")).unwrap();
        match policy {
            super::CorsPolicy::Allowlist(origins) => {
                assert_eq!(
                    origins,
                    vec![
                        HeaderValue::from_static("https://app.example.com"),
                        HeaderValue::from_static("http://localhost:3000"),
                    ]
                );
            }
            super::CorsPolicy::Localhost => panic!("expected an allowlist"),
        }
    }

    #[test]
    fn localhost_origins_allow_loopback_hosts_only() {
        for origin in [
            "http://localhost:3000",
            "https://localhost",
            "http://127.0.0.1:8787",
            "http://[::1]:3000",
        ] {
            assert!(is_localhost_origin(origin), "{origin}");
        }
        for origin in [
            "https://hoppscotch.io",
            "http://localhost.evil.com",
            "http://evil.com@localhost",
            "http://127.0.0.1.example.com",
            "null",
        ] {
            assert!(!is_localhost_origin(origin), "{origin}");
        }
    }

    #[test]
    fn numeric_settings_reject_zero_and_garbage() {
        let err = ServerConfig::from_settings(super::EnvSettings {
            cors_origins: None,
            trusted_proxy: Some("yes"),
            max_body_bytes: Some("0"),
            request_timeout_secs: None,
            rate_limit: None,
            rate_window_secs: None,
        });
        assert!(err.is_err());
        assert!(parse_flag("BNSPELL_TRUSTED_PROXY", Some("true")).unwrap());
        assert!(!parse_flag("BNSPELL_TRUSTED_PROXY", Some("false")).unwrap());
        let config = ServerConfig::from_settings(super::EnvSettings {
            cors_origins: None,
            trusted_proxy: Some("1"),
            max_body_bytes: Some("4096"),
            request_timeout_secs: Some("5"),
            rate_limit: Some("0"),
            rate_window_secs: Some("10"),
        })
        .unwrap();
        assert!(config.trust_proxy);
        assert_eq!(config.max_body_bytes, 4096);
        assert_eq!(config.request_timeout, Duration::from_secs(5));
        assert_eq!(config.rate_limit_requests, 0);
        assert_eq!(config.rate_limit_window, Duration::from_secs(10));
    }

    #[test]
    fn forwarded_for_is_the_rightmost_address_and_only_when_trusted() {
        let mut headers = HeaderMap::new();
        headers.insert(
            "x-forwarded-for",
            HeaderValue::from_static("9.9.9.9, 203.0.113.8"),
        );
        let peer: IpAddr = "198.51.100.4".parse().unwrap();
        assert_eq!(client_key(&headers, Some(peer), false), "198.51.100.4");
        assert_eq!(client_key(&headers, Some(peer), true), "203.0.113.8");
        assert_eq!(
            parse_ip_token("203.0.113.8:443").unwrap().to_string(),
            "203.0.113.8"
        );
        assert_eq!(client_key(&HeaderMap::new(), None, false), "unknown");
    }

    #[test]
    fn rate_limiter_resets_per_key_and_skips_health() {
        let limiter = ServerConfig {
            rate_limit_requests: 1,
            trust_proxy: true,
            ..ServerConfig::default()
        }
        .rate_limiter();
        let mut first = HeaderMap::new();
        first.insert("x-forwarded-for", HeaderValue::from_static("203.0.113.1"));
        let mut second = HeaderMap::new();
        second.insert("x-forwarded-for", HeaderValue::from_static("203.0.113.2"));
        assert!(limiter.check("/api/check", &first, None).is_ok());
        assert!(limiter.check("/api/check", &first, None).is_err());
        assert!(limiter.check("/health", &first, None).is_ok());
        assert!(limiter.check("/api/health", &first, None).is_ok());
        assert!(limiter.check("/api/suggest", &second, None).is_ok());
    }
}