bext-waf 0.2.0

Web Application Firewall for bext — rate limiting, IP filtering, GeoIP, rule engine
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
504
505
506
507
508
509
510
//! Geo-blocking — country-level access control via MaxMind GeoLite2.
//!
//! Operates in **Allow** (whitelist) or **Deny** (blacklist) mode using
//! ISO 3166-1 alpha-2 country codes.  Requires the `geoip` feature and a
//! GeoLite2-Country.mmdb database file.  Supports bypass paths and extracts
//! the real client IP from a configurable header (e.g. `X-Forwarded-For`).

use std::net::IpAddr;

use serde::{Deserialize, Serialize};

use crate::{WafDecision, WafRequest};

/// Geo-blocking mode.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum GeoMode {
    /// Only listed countries are allowed.
    Allow,
    /// Listed countries are denied.
    #[default]
    Deny,
}

/// Configuration for geo-blocking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeoConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub mode: GeoMode,
    /// ISO 3166-1 alpha-2 country codes (e.g. "US", "CN", "RU").
    #[serde(default)]
    pub countries: Vec<String>,
    /// Paths that bypass geo-blocking (e.g. "/health", "/api/status").
    #[serde(default)]
    pub bypass_paths: Vec<String>,
    /// Header containing the real client IP (e.g. "X-Forwarded-For").
    #[serde(default)]
    pub real_ip_header: Option<String>,
}

impl Default for GeoConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            mode: GeoMode::Deny,
            countries: Vec::new(),
            bypass_paths: Vec::new(),
            real_ip_header: None,
        }
    }
}

/// Geo-blocking engine.
///
/// When the `geoip` feature is enabled, uses MaxMind GeoLite2 for country lookup.
/// Without the feature, this is a no-op that always returns `None`.
pub struct GeoBlocker {
    config: GeoConfig,
    #[cfg(feature = "geoip")]
    reader: Option<maxminddb::Reader<Vec<u8>>>,
}

#[cfg(feature = "geoip")]
#[derive(serde::Deserialize)]
struct GeoLookup {
    country: Option<CountryRecord>,
}

#[cfg(feature = "geoip")]
#[derive(serde::Deserialize)]
struct CountryRecord {
    iso_code: Option<String>,
}

impl GeoBlocker {
    /// Create a new `GeoBlocker`.
    ///
    /// `db_path` is the path to a MaxMind GeoLite2-Country.mmdb file. When the `geoip` feature
    /// is not enabled, `db_path` is ignored and country lookup is skipped.
    pub fn new(config: GeoConfig, _db_path: &str) -> anyhow::Result<Self> {
        #[cfg(feature = "geoip")]
        {
            let reader = if config.enabled {
                Some(maxminddb::Reader::open_readfile(_db_path)?)
            } else {
                None
            };
            Ok(Self { config, reader })
        }
        #[cfg(not(feature = "geoip"))]
        {
            if config.enabled {
                tracing::warn!(
                    "geo-blocking enabled but 'geoip' feature not compiled in — skipping"
                );
            }
            Ok(Self { config })
        }
    }

    /// Create a `GeoBlocker` that is disabled (no-op).
    pub fn disabled() -> Self {
        Self {
            config: GeoConfig::default(),
            #[cfg(feature = "geoip")]
            reader: None,
        }
    }

    fn is_bypass_path(&self, path: &str) -> bool {
        self.config
            .bypass_paths
            .iter()
            .any(|bp| path.starts_with(bp.as_str()))
    }

    /// Look up the country code for an IP address.
    #[allow(unused_variables)]
    fn lookup_country(&self, ip: IpAddr) -> Option<String> {
        #[cfg(feature = "geoip")]
        {
            let reader = self.reader.as_ref()?;
            let result: Result<GeoLookup, _> = reader.lookup(ip);
            match result {
                Ok(geo) => geo.country.and_then(|c| c.iso_code),
                Err(e) => {
                    tracing::debug!(ip = %ip, error = %e, "geoip lookup failed");
                    None
                }
            }
        }
        #[cfg(not(feature = "geoip"))]
        {
            None
        }
    }

    /// Check if a request should be blocked based on geo-location.
    pub fn check(&self, ip: IpAddr, path: &str) -> Option<WafDecision> {
        if !self.config.enabled {
            return None;
        }

        if self.is_bypass_path(path) {
            return None;
        }

        let country = match self.lookup_country(ip) {
            Some(c) => c.to_uppercase(),
            None => {
                // Unknown country: block in Allow mode (restrictive), allow in Deny mode (permissive).
                return match self.config.mode {
                    GeoMode::Allow => Some(WafDecision::Block {
                        status: 403,
                        reason: "GeoIP lookup failed — blocked by allow-list policy".into(),
                        rule: "geo".into(),
                    }),
                    GeoMode::Deny => None, // Unknown country not in deny list
                };
            }
        };

        let in_list = self
            .config
            .countries
            .iter()
            .any(|c| c.eq_ignore_ascii_case(&country));

        match self.config.mode {
            GeoMode::Deny => {
                if in_list {
                    Some(WafDecision::Block {
                        status: 403,
                        reason: format!("country {country} is geo-blocked"),
                        rule: "geo_block_deny".into(),
                    })
                } else {
                    None
                }
            }
            GeoMode::Allow => {
                if in_list {
                    None
                } else {
                    Some(WafDecision::Block {
                        status: 403,
                        reason: format!("country {country} is not in allowed list"),
                        rule: "geo_block_allow".into(),
                    })
                }
            }
        }
    }

    /// Check a request using `real_ip_header` to resolve the client IP.
    ///
    /// 1. If `real_ip_header` is configured, looks up that header in `req.headers` and parses the IP.
    /// 2. Falls back to `req.client_ip` if the header is missing or contains an invalid IP.
    /// 3. Calls the existing `check()` with the resolved IP.
    pub fn check_request(&self, req: &WafRequest) -> Option<WafDecision> {
        let ip = self.resolve_ip(req);
        self.check(ip, &req.path)
    }

    /// Resolve the real client IP from the request.
    ///
    /// If `real_ip_header` is set and the header exists with a valid IP, use it.
    /// Otherwise fall back to `req.client_ip`.
    fn resolve_ip(&self, req: &WafRequest) -> IpAddr {
        if let Some(ref header_name) = self.config.real_ip_header {
            let lower = header_name.to_lowercase();
            if let Some(header_val) = req
                .headers
                .iter()
                .find(|(k, _)| k.to_lowercase() == lower)
                .map(|(_, v)| v)
            {
                // Handle X-Forwarded-For style (comma-separated, take the first).
                let ip_str = header_val.split(',').next().unwrap_or(header_val).trim();
                if let Ok(ip) = ip_str.parse::<IpAddr>() {
                    return ip;
                }
                tracing::debug!(
                    header = header_name.as_str(),
                    value = header_val.as_str(),
                    "failed to parse IP from real_ip_header, falling back to client_ip"
                );
            }
        }
        req.client_ip
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn disabled_allows_all() {
        let blocker = GeoBlocker::disabled();
        assert!(blocker
            .check("1.2.3.4".parse().unwrap(), "/api/data")
            .is_none());
    }

    #[test]
    fn bypass_path_skips_check() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Deny,
            countries: vec!["CN".into()],
            bypass_paths: vec!["/health".into(), "/api/status".into()],
            real_ip_header: None,
        };
        // Without geoip feature, lookup returns None so no block anyway.
        // But we verify bypass path logic itself.
        let blocker =
            GeoBlocker::new(config, "/nonexistent.mmdb").unwrap_or_else(|_| GeoBlocker::disabled());
        assert!(blocker
            .check("1.2.3.4".parse().unwrap(), "/health")
            .is_none());
        assert!(blocker
            .check("1.2.3.4".parse().unwrap(), "/api/status/deep")
            .is_none());
    }

    #[test]
    fn default_config_is_disabled() {
        let config = GeoConfig::default();
        assert!(!config.enabled);
    }

    #[test]
    fn country_list_case_insensitive() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Deny,
            countries: vec!["cn".into(), "RU".into()],
            bypass_paths: vec![],
            real_ip_header: None,
        };
        // Verify that country matching is case-insensitive in our logic.
        assert!(config
            .countries
            .iter()
            .any(|c| c.eq_ignore_ascii_case("CN")));
        assert!(config
            .countries
            .iter()
            .any(|c| c.eq_ignore_ascii_case("ru")));
    }

    // The following tests exercise the blocker with a mock approach:
    // Without the `geoip` feature, lookup_country always returns None,
    // so these verify the correct behavior for unknown countries per mode.

    #[test]
    fn unknown_country_is_allowed_in_deny_mode() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Deny,
            countries: vec!["CN".into()],
            bypass_paths: vec![],
            real_ip_header: None,
        };
        let blocker =
            GeoBlocker::new(config, "/nonexistent.mmdb").unwrap_or_else(|_| GeoBlocker::disabled());
        // lookup_country returns None → allow in Deny mode (permissive for unknowns).
        assert!(blocker.check("8.8.8.8".parse().unwrap(), "/page").is_none());
    }

    #[test]
    fn unknown_country_is_blocked_in_allow_mode() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Allow,
            countries: vec!["US".into()],
            bypass_paths: vec![],
            real_ip_header: None,
        };
        let blocker =
            GeoBlocker::new(config, "/nonexistent.mmdb").unwrap_or_else(|_| GeoBlocker::disabled());
        // lookup_country returns None → block in Allow mode (restrictive for unknowns).
        let decision = blocker.check("8.8.8.8".parse().unwrap(), "/page");
        assert!(matches!(
            decision,
            Some(WafDecision::Block { status: 403, .. })
        ));
    }

    #[test]
    fn unknown_country_blocked_in_allow_mode_has_correct_rule() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Allow,
            countries: vec!["US".into()],
            bypass_paths: vec![],
            real_ip_header: None,
        };
        let blocker =
            GeoBlocker::new(config, "/nonexistent.mmdb").unwrap_or_else(|_| GeoBlocker::disabled());
        match blocker.check("8.8.8.8".parse().unwrap(), "/page") {
            Some(WafDecision::Block { rule, reason, .. }) => {
                assert_eq!(rule, "geo");
                assert!(reason.contains("allow-list policy"));
            }
            other => panic!("expected Block, got {other:?}"),
        }
    }

    #[test]
    fn unknown_country_bypass_path_still_allowed_in_allow_mode() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Allow,
            countries: vec!["US".into()],
            bypass_paths: vec!["/health".into()],
            real_ip_header: None,
        };
        let blocker =
            GeoBlocker::new(config, "/nonexistent.mmdb").unwrap_or_else(|_| GeoBlocker::disabled());
        // Bypass path should still be allowed even in Allow mode with unknown country.
        assert!(blocker
            .check("8.8.8.8".parse().unwrap(), "/health")
            .is_none());
    }

    // Tests for check_request and real_ip_header.

    #[test]
    fn check_request_uses_client_ip_when_no_real_ip_header() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Deny,
            countries: vec!["CN".into()],
            bypass_paths: vec![],
            real_ip_header: None,
        };
        let blocker =
            GeoBlocker::new(config, "/nonexistent.mmdb").unwrap_or_else(|_| GeoBlocker::disabled());
        let req = WafRequest {
            client_ip: "8.8.8.8".parse().unwrap(),
            method: "GET".into(),
            path: "/page".into(),
            query: None,
            headers: std::collections::HashMap::new(),
            body: None,
            user_agent: None,
        };
        // Should use client_ip; unknown country in deny mode → allow.
        assert!(blocker.check_request(&req).is_none());
    }

    #[test]
    fn check_request_uses_real_ip_header_when_configured() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Deny,
            countries: vec!["CN".into()],
            bypass_paths: vec![],
            real_ip_header: Some("X-Real-IP".into()),
        };
        let blocker =
            GeoBlocker::new(config, "/nonexistent.mmdb").unwrap_or_else(|_| GeoBlocker::disabled());
        let mut headers = std::collections::HashMap::new();
        headers.insert("X-Real-IP".into(), "1.2.3.4".into());
        let req = WafRequest {
            client_ip: "8.8.8.8".parse().unwrap(),
            method: "GET".into(),
            path: "/page".into(),
            query: None,
            headers,
            body: None,
            user_agent: None,
        };
        // resolve_ip should return 1.2.3.4 from the header.
        assert_eq!(
            blocker.resolve_ip(&req),
            "1.2.3.4".parse::<IpAddr>().unwrap()
        );
    }

    #[test]
    fn check_request_falls_back_to_client_ip_on_invalid_header() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Deny,
            countries: vec!["CN".into()],
            bypass_paths: vec![],
            real_ip_header: Some("X-Real-IP".into()),
        };
        let blocker =
            GeoBlocker::new(config, "/nonexistent.mmdb").unwrap_or_else(|_| GeoBlocker::disabled());
        let mut headers = std::collections::HashMap::new();
        headers.insert("X-Real-IP".into(), "not-an-ip".into());
        let req = WafRequest {
            client_ip: "8.8.8.8".parse().unwrap(),
            method: "GET".into(),
            path: "/page".into(),
            query: None,
            headers,
            body: None,
            user_agent: None,
        };
        // Should fall back to client_ip.
        assert_eq!(
            blocker.resolve_ip(&req),
            "8.8.8.8".parse::<IpAddr>().unwrap()
        );
    }

    #[test]
    fn check_request_falls_back_when_header_missing() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Deny,
            countries: vec!["CN".into()],
            bypass_paths: vec![],
            real_ip_header: Some("X-Real-IP".into()),
        };
        let blocker =
            GeoBlocker::new(config, "/nonexistent.mmdb").unwrap_or_else(|_| GeoBlocker::disabled());
        let req = WafRequest {
            client_ip: "8.8.8.8".parse().unwrap(),
            method: "GET".into(),
            path: "/page".into(),
            query: None,
            headers: std::collections::HashMap::new(),
            body: None,
            user_agent: None,
        };
        assert_eq!(
            blocker.resolve_ip(&req),
            "8.8.8.8".parse::<IpAddr>().unwrap()
        );
    }

    #[test]
    fn check_request_parses_x_forwarded_for_first_ip() {
        let config = GeoConfig {
            enabled: true,
            mode: GeoMode::Deny,
            countries: vec![],
            bypass_paths: vec![],
            real_ip_header: Some("X-Forwarded-For".into()),
        };
        let blocker =
            GeoBlocker::new(config, "/nonexistent.mmdb").unwrap_or_else(|_| GeoBlocker::disabled());
        let mut headers = std::collections::HashMap::new();
        headers.insert(
            "X-Forwarded-For".into(),
            "1.2.3.4, 5.6.7.8, 9.10.11.12".into(),
        );
        let req = WafRequest {
            client_ip: "127.0.0.1".parse().unwrap(),
            method: "GET".into(),
            path: "/page".into(),
            query: None,
            headers,
            body: None,
            user_agent: None,
        };
        assert_eq!(
            blocker.resolve_ip(&req),
            "1.2.3.4".parse::<IpAddr>().unwrap()
        );
    }
}