synapse-waf 0.9.1

High-performance WAF and reverse proxy with embedded intelligence — built on Cloudflare Pingora
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Request/Response Body Inspection Module
//!
//! Provides functionality for inspecting HTTP request and response bodies,
//! including content-type detection, parsing, and anomaly detection.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, Instant};
use thiserror::Error;
use tracing::{debug, instrument};

/// Errors that can occur during body inspection
#[derive(Debug, Error)]
pub enum BodyError {
    #[error("payload too large: {size} bytes exceeds limit of {limit} bytes")]
    PayloadTooLarge { size: usize, limit: usize },

    #[error("parse error: {message}")]
    ParseError {
        message: String,
        content_type: ContentType,
    },

    #[error("inspection timeout after {elapsed:?}")]
    Timeout { elapsed: Duration, limit: Duration },

    #[error("max parse depth exceeded: {depth} > {limit}")]
    MaxDepthExceeded { depth: usize, limit: usize },
}

pub type BodyResult<T> = Result<T, BodyError>;

/// Detected content type of HTTP body
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ContentType {
    Json,
    Xml,
    FormUrlencoded,
    Multipart,
    PlainText,
    Html,
    Binary,
    #[default]
    Unknown,
}

impl ContentType {
    pub fn from_header(header: &str) -> Self {
        let lower = header.to_lowercase();
        let mime = lower.split(';').next().unwrap_or("").trim();
        match mime {
            "application/json" | "text/json" => Self::Json,
            "application/xml" | "text/xml" => Self::Xml,
            "application/x-www-form-urlencoded" => Self::FormUrlencoded,
            m if m.starts_with("multipart/") => Self::Multipart,
            "text/plain" => Self::PlainText,
            "text/html" => Self::Html,
            "application/octet-stream" => Self::Binary,
            _ => Self::Unknown,
        }
    }

    pub fn detect_from_body(body: &[u8]) -> Self {
        if body.is_empty() {
            return Self::Unknown;
        }
        let trimmed: Vec<u8> = body
            .iter()
            .skip_while(|&&b| b.is_ascii_whitespace())
            .copied()
            .collect();
        if trimmed.is_empty() {
            return Self::Unknown;
        }
        let first = trimmed[0];
        if first == b'{' || first == b'[' {
            return Self::Json;
        }
        if first == b'<' {
            if let Ok(s) = std::str::from_utf8(&trimmed) {
                let lower = s.to_lowercase();
                if lower.starts_with("<!doctype html") || lower.starts_with("<html") {
                    return Self::Html;
                }
                return Self::Xml;
            }
        }
        if let Ok(s) = std::str::from_utf8(body) {
            if s.contains('=') && (s.contains('&') || !s.contains(' ')) {
                return Self::FormUrlencoded;
            }
            return Self::PlainText;
        }
        Self::Binary
    }

    pub const fn is_text(&self) -> bool {
        matches!(
            self,
            Self::Json | Self::Xml | Self::FormUrlencoded | Self::PlainText | Self::Html
        )
    }
}

impl std::fmt::Display for ContentType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Json => write!(f, "application/json"),
            Self::Xml => write!(f, "application/xml"),
            Self::FormUrlencoded => write!(f, "application/x-www-form-urlencoded"),
            Self::Multipart => write!(f, "multipart/form-data"),
            Self::PlainText => write!(f, "text/plain"),
            Self::Html => write!(f, "text/html"),
            Self::Binary => write!(f, "application/octet-stream"),
            Self::Unknown => write!(f, "unknown"),
        }
    }
}

/// Parsed body structure
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum ParsedBody {
    Json(serde_json::Value),
    Form(HashMap<String, Vec<String>>),
    Text(String),
    Binary { size: usize, hash: String },
}

/// Detected anomaly in body content
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BodyAnomaly {
    pub anomaly_type: AnomalyType,
    pub severity: f32,
    pub description: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnomalyType {
    OversizedPayload,
    MalformedContent,
    ContentTypeMismatch,
    NullBytesInText,
    ControlCharacters,
    DuplicateKeys,
}

impl BodyAnomaly {
    pub fn new(anomaly_type: AnomalyType, severity: f32, description: impl Into<String>) -> Self {
        Self {
            anomaly_type,
            severity: severity.clamp(0.0, 1.0),
            description: description.into(),
        }
    }
}

/// Configuration for body inspection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BodyConfig {
    pub max_body_size: usize,
    pub max_parse_depth: usize,
    pub timeout: Duration,
    pub detect_anomalies: bool,
    pub large_payload_threshold: usize,
}

impl Default for BodyConfig {
    fn default() -> Self {
        Self {
            max_body_size: 10 * 1024 * 1024,
            max_parse_depth: 32,
            timeout: Duration::from_secs(5),
            detect_anomalies: true,
            large_payload_threshold: 1024 * 1024,
        }
    }
}

/// Result of body inspection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InspectionResult {
    pub content_type: ContentType,
    pub declared_content_type: Option<ContentType>,
    pub body_size: usize,
    pub parsed_structure: Option<ParsedBody>,
    pub anomalies: Vec<BodyAnomaly>,
    pub processing_time: Duration,
    pub parse_success: bool,
    pub parse_error: Option<String>,
}

impl InspectionResult {
    pub fn has_anomalies(&self) -> bool {
        !self.anomalies.is_empty()
    }

    pub fn max_severity(&self) -> f32 {
        self.anomalies
            .iter()
            .map(|a| a.severity)
            .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .unwrap_or(0.0)
    }
}

/// Main body inspection engine
#[derive(Debug)]
pub struct BodyInspector {
    config: BodyConfig,
}

impl BodyInspector {
    pub fn new(config: BodyConfig) -> Self {
        Self { config }
    }

    #[instrument(skip(self, body), fields(body_len = body.len()))]
    pub fn inspect(
        &self,
        body: &[u8],
        content_type_header: Option<&str>,
    ) -> BodyResult<InspectionResult> {
        let start = Instant::now();
        if body.len() > self.config.max_body_size {
            return Err(BodyError::PayloadTooLarge {
                size: body.len(),
                limit: self.config.max_body_size,
            });
        }

        let declared = content_type_header.map(ContentType::from_header);
        let detected = ContentType::detect_from_body(body);
        let content_type = declared.unwrap_or(detected);

        let (parsed, parse_success, parse_error) = self.parse_body(body, content_type);
        let mut anomalies = Vec::new();
        if self.config.detect_anomalies {
            self.detect_anomalies(body, content_type, declared, detected, &mut anomalies);
        }

        debug!(
            ?content_type,
            body_size = body.len(),
            "body inspection complete"
        );
        Ok(InspectionResult {
            content_type,
            declared_content_type: declared,
            body_size: body.len(),
            parsed_structure: parsed,
            anomalies,
            processing_time: start.elapsed(),
            parse_success,
            parse_error,
        })
    }

    fn parse_body(
        &self,
        body: &[u8],
        content_type: ContentType,
    ) -> (Option<ParsedBody>, bool, Option<String>) {
        if body.is_empty() {
            return (None, true, None);
        }
        match content_type {
            ContentType::Json => self.parse_json(body),
            ContentType::FormUrlencoded => self.parse_form(body),
            ContentType::PlainText | ContentType::Html => self.parse_text(body),
            _ => (Some(self.parse_binary(body)), true, None),
        }
    }

    fn parse_json(&self, body: &[u8]) -> (Option<ParsedBody>, bool, Option<String>) {
        let text = match std::str::from_utf8(body) {
            Ok(s) => s,
            Err(e) => return (None, false, Some(e.to_string())),
        };

        // Parse with depth limit to prevent stack overflow from deeply nested payloads
        match self.parse_json_with_depth_limit(text, self.config.max_parse_depth) {
            Ok(value) => (Some(ParsedBody::Json(value)), true, None),
            Err(e) => (None, false, Some(e)),
        }
    }

    /// Parse JSON with a maximum nesting depth limit.
    ///
    /// This prevents stack overflow attacks from payloads with extreme nesting depth.
    fn parse_json_with_depth_limit(
        &self,
        text: &str,
        max_depth: usize,
    ) -> Result<serde_json::Value, String> {
        use serde_json::Value;

        let value: Value = serde_json::from_str(text).map_err(|e| e.to_string())?;

        // Check depth after parsing (serde_json has a default recursion limit of 128,
        // but we enforce a stricter limit for security)
        if self.check_json_depth(&value, 0, max_depth) {
            Ok(value)
        } else {
            Err(format!("JSON nesting depth exceeds limit of {}", max_depth))
        }
    }

    /// Recursively check if JSON depth exceeds the limit.
    fn check_json_depth(
        &self,
        value: &serde_json::Value,
        current_depth: usize,
        max_depth: usize,
    ) -> bool {
        if current_depth > max_depth {
            return false;
        }

        match value {
            serde_json::Value::Array(arr) => arr
                .iter()
                .all(|v| self.check_json_depth(v, current_depth + 1, max_depth)),
            serde_json::Value::Object(obj) => obj
                .values()
                .all(|v| self.check_json_depth(v, current_depth + 1, max_depth)),
            _ => true,
        }
    }

    fn parse_form(&self, body: &[u8]) -> (Option<ParsedBody>, bool, Option<String>) {
        let text = match std::str::from_utf8(body) {
            Ok(s) => s,
            Err(e) => return (None, false, Some(e.to_string())),
        };
        let mut form: HashMap<String, Vec<String>> = HashMap::new();
        for pair in text.split('&') {
            if pair.is_empty() {
                continue;
            }
            let (key, value) = match pair.split_once('=') {
                Some((k, v)) => (k, v),
                None => (pair, ""),
            };
            form.entry(key.to_string())
                .or_default()
                .push(value.to_string());
        }
        (Some(ParsedBody::Form(form)), true, None)
    }

    fn parse_text(&self, body: &[u8]) -> (Option<ParsedBody>, bool, Option<String>) {
        match std::str::from_utf8(body) {
            Ok(s) => (Some(ParsedBody::Text(s.to_string())), true, None),
            Err(e) => (None, false, Some(e.to_string())),
        }
    }

    fn parse_binary(&self, body: &[u8]) -> ParsedBody {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        body.hash(&mut hasher);
        ParsedBody::Binary {
            size: body.len(),
            hash: format!("{:016x}", hasher.finish()),
        }
    }

    fn detect_anomalies(
        &self,
        body: &[u8],
        content_type: ContentType,
        declared: Option<ContentType>,
        detected: ContentType,
        anomalies: &mut Vec<BodyAnomaly>,
    ) {
        if body.len() > self.config.large_payload_threshold {
            anomalies.push(BodyAnomaly::new(
                AnomalyType::OversizedPayload,
                0.3,
                "large payload",
            ));
        }
        if let Some(decl) = declared {
            if decl != detected && detected != ContentType::Unknown {
                anomalies.push(BodyAnomaly::new(
                    AnomalyType::ContentTypeMismatch,
                    0.6,
                    "content type mismatch",
                ));
            }
        }
        if content_type.is_text() && body.contains(&0u8) {
            anomalies.push(BodyAnomaly::new(
                AnomalyType::NullBytesInText,
                0.8,
                "null bytes in text",
            ));
        }
    }
}

impl Default for BodyInspector {
    fn default() -> Self {
        Self::new(BodyConfig::default())
    }
}

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

    #[test]
    fn test_content_type_detection() {
        assert_eq!(
            ContentType::from_header("application/json"),
            ContentType::Json
        );
        assert_eq!(ContentType::from_header("text/html"), ContentType::Html);
        assert_eq!(
            ContentType::detect_from_body(br#"{"key": "value"}"#),
            ContentType::Json
        );
        assert_eq!(ContentType::detect_from_body(b"<html>"), ContentType::Html);
    }

    #[test]
    fn test_inspector_json() {
        let inspector = BodyInspector::default();
        let body = br#"{"test": "value"}"#;
        let result = inspector.inspect(body, Some("application/json")).unwrap();
        assert_eq!(result.content_type, ContentType::Json);
        assert!(result.parse_success);
    }

    #[test]
    fn test_inspector_size_limit() {
        let mut config = BodyConfig::default();
        config.max_body_size = 10;
        let inspector = BodyInspector::new(config);
        let body = b"this is way too large";
        let result = inspector.inspect(body, None);
        assert!(matches!(result, Err(BodyError::PayloadTooLarge { .. })));
    }

    #[test]
    fn test_json_depth_limit_within_limit() {
        let mut config = BodyConfig::default();
        config.max_parse_depth = 4;
        let inspector = BodyInspector::new(config);

        // Depth 3: {"a": {"b": {"c": "value"}}}
        let body = br#"{"a": {"b": {"c": "value"}}}"#;
        let result = inspector.inspect(body, Some("application/json")).unwrap();
        assert!(result.parse_success);
    }

    #[test]
    fn test_json_depth_limit_exceeded() {
        let mut config = BodyConfig::default();
        config.max_parse_depth = 2;
        let inspector = BodyInspector::new(config);

        // Depth 3: {"a": {"b": {"c": "value"}}} - exceeds limit of 2
        let body = br#"{"a": {"b": {"c": "value"}}}"#;
        let result = inspector.inspect(body, Some("application/json")).unwrap();
        assert!(!result.parse_success);
        assert!(result.parse_error.unwrap().contains("depth"));
    }

    #[test]
    fn test_json_array_depth_limit() {
        let mut config = BodyConfig::default();
        config.max_parse_depth = 3;
        let inspector = BodyInspector::new(config);

        // Depth 4: [[[[1]]]] - exceeds limit of 3
        let body = br#"[[[[1]]]]"#;
        let result = inspector.inspect(body, Some("application/json")).unwrap();
        assert!(!result.parse_success);
    }

    #[test]
    fn test_form_urlencoded_duplicate_keys() {
        let inspector = BodyInspector::default();
        let body = b"name=alice&name=bob";
        let result = inspector
            .inspect(body, Some("application/x-www-form-urlencoded"))
            .unwrap();

        assert_eq!(result.content_type, ContentType::FormUrlencoded);
        assert!(result.parse_success);

        match result.parsed_structure.unwrap() {
            ParsedBody::Form(form) => {
                let names = form.get("name").expect("key 'name' should exist");
                assert_eq!(names, &vec!["alice".to_string(), "bob".to_string()]);
            }
            other => panic!("expected ParsedBody::Form, got {:?}", other),
        }
    }

    #[test]
    fn test_form_urlencoded_single_key() {
        let inspector = BodyInspector::default();
        let body = b"key=value";
        let result = inspector
            .inspect(body, Some("application/x-www-form-urlencoded"))
            .unwrap();

        assert!(result.parse_success);
        match result.parsed_structure.unwrap() {
            ParsedBody::Form(form) => {
                assert_eq!(form.get("key").unwrap(), &vec!["value".to_string()]);
            }
            other => panic!("expected ParsedBody::Form, got {:?}", other),
        }
    }

    #[test]
    fn test_form_urlencoded_key_without_value() {
        let inspector = BodyInspector::default();
        let body = b"flag&key=val";
        let result = inspector
            .inspect(body, Some("application/x-www-form-urlencoded"))
            .unwrap();

        assert!(result.parse_success);
        match result.parsed_structure.unwrap() {
            ParsedBody::Form(form) => {
                // "flag" has no '=' so value is ""
                assert_eq!(form.get("flag").unwrap(), &vec!["".to_string()]);
                assert_eq!(form.get("key").unwrap(), &vec!["val".to_string()]);
            }
            other => panic!("expected ParsedBody::Form, got {:?}", other),
        }
    }

    #[test]
    fn test_form_urlencoded_empty_pairs_skipped() {
        let inspector = BodyInspector::default();
        // Trailing & and double && should be skipped
        let body = b"a=1&&b=2&";
        let result = inspector
            .inspect(body, Some("application/x-www-form-urlencoded"))
            .unwrap();

        assert!(result.parse_success);
        match result.parsed_structure.unwrap() {
            ParsedBody::Form(form) => {
                assert_eq!(form.len(), 2);
                assert_eq!(form.get("a").unwrap(), &vec!["1".to_string()]);
                assert_eq!(form.get("b").unwrap(), &vec!["2".to_string()]);
            }
            other => panic!("expected ParsedBody::Form, got {:?}", other),
        }
    }

    #[test]
    fn test_json_mixed_depth_limit() {
        let mut config = BodyConfig::default();
        config.max_parse_depth = 3;
        let inspector = BodyInspector::new(config);

        // Mix of arrays and objects at depth 3 - within limit
        let body = br#"{"arr": [{"key": "value"}]}"#;
        let result = inspector.inspect(body, Some("application/json")).unwrap();
        assert!(result.parse_success);
    }
}