zenith-http1 0.1.0

Zenith HTTP/1.1 协议解析器(RFC 7230):零堆分配热路径、流式解析、CRLF 防注入
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! HTTP/1.1 请求走私检测器
//!
//! 检测经典的 HTTP 请求走私攻击:
//! - CL.TE: 上游使用 Content-Length,下游使用 Transfer-Encoding
//! - TE.CL: 上游使用 Transfer-Encoding,下游使用 Content-Length
//! - TE.TE: 存在多个 Transfer-Encoding 值
//!
//! 防护策略:严格 RFC 7230 §3.3.1,Content-Length 与 Transfer-Encoding 互斥。

use crate::types::Http1Error;
use std::borrow::Cow;

/// 请求走私类型
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SmugglingKind {
    /// CL.TE:同时存在 Content-Length 和 Transfer-Encoding
    ClTe,
    /// TE.CL:同时存在 Transfer-Encoding 和 Content-Length(同上,攻击方向相反)
    TeCl,
    /// TE.TE:存在多个或非标准 Transfer-Encoding
    TeTe,
    /// Host 头值包含 CRLF
    HostInjection,
    /// 头部值包含 CRLF 注入
    HeaderInjection,
    /// 双 Content-Length
    DoubleContentLength,
    /// 双 Host 头(RFC 7230 §5.4:客户端不得发送多个 Host,
    /// 前后端取词差分是经典走私向量)
    DuplicateHost,
}

impl SmugglingKind {
    /// 获取简短描述
    #[inline]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::ClTe => "CL.TE",
            Self::TeCl => "TE.CL",
            Self::TeTe => "TE.TE",
            Self::HostInjection => "Host Injection",
            Self::HeaderInjection => "Header Injection",
            Self::DoubleContentLength => "Double Content-Length",
            Self::DuplicateHost => "Duplicate Host",
        }
    }
}

/// 请求走私检测器
///
/// 在请求解析阶段对头部进行检测,识别不一致或恶意构造。
#[derive(Debug, Default, Clone)]
pub struct SmugglingDetector;

impl SmugglingDetector {
    /// 创建检测器
    #[inline]
    pub fn new() -> Self {
        Self
    }

    /// 检测头部序列中的走私攻击
    ///
    /// # 参数
    /// - `headers`: [(name, value)] 头部列表(名称未规范化也可,内部会小写化)
    ///
    /// # 返回
    /// - Ok(()) : 通过检测
    /// - Err((SmugglingKind, String)) : 检测到的走私类型与说明
    ///
    /// # 性能
    /// 头部名称已小写化的调用方(如 [`crate::parser::Http1Parser`] 经
    /// `parse_header_line` 规范化后)应优先使用 [`Self::detect_already_lowercased`],
    /// 跳过每头一次的 `to_ascii_lowercase` 分配。
    pub fn detect<N, V>(
        &self,
        headers: &[(N, V)],
    ) -> Result<(), (SmugglingKind, String)>
    where
        N: AsRef<str>,
        V: AsRef<str>,
    {
        self.detect_impl(headers, |s| Cow::Owned(s.to_ascii_lowercase()))
    }

    /// 共享检测逻辑(内部实现)
    ///
    /// 通过闭包 `normalize` 控制头部名称是否小写化:
    /// - [`Self::detect`] 传入 `to_ascii_lowercase` 闭包(每头分配一次 `String`)
    /// - [`Self::detect_already_lowercased`] 传入恒等闭包(零分配,`Cow::Borrowed`)
    fn detect_impl<N, V>(
        &self,
        headers: &[(N, V)],
        normalize: impl for<'a> Fn(&'a str) -> Cow<'a, str>,
    ) -> Result<(), (SmugglingKind, String)>
    where
        N: AsRef<str>,
        V: AsRef<str>,
    {
        let mut has_content_length = false;
        let mut content_length_count: usize = 0;
        let mut transfer_encoding_values: Vec<String> = Vec::with_capacity(4);
        let mut has_te = false;
        let mut host_count: usize = 0;
        // CL / TE 首个出现位置(用于区分 CL.TE 与 TE.CL 两个攻击方向)
        let mut cl_position: Option<usize> = None;
        let mut te_position: Option<usize> = None;

        for (idx, (name, value)) in headers.iter().enumerate() {
            let value = value.as_ref();
            let n = normalize(name.as_ref());

            match &*n {
                "content-length" => {
                    content_length_count += 1;
                    if content_length_count > 1 {
                        return Err((
                            SmugglingKind::DoubleContentLength,
                            "multiple Content-Length".into(),
                        ));
                    }
                    // 严格校验为十进制数字
                    if !value.chars().all(|c| c.is_ascii_digit()) {
                        return Err((
                            SmugglingKind::ClTe,
                            "Content-Length not decimal".into(),
                        ));
                    }
                    has_content_length = true;
                    if cl_position.is_none() {
                        cl_position = Some(idx);
                    }
                }
                "transfer-encoding" => {
                    has_te = true;
                    if te_position.is_none() {
                        te_position = Some(idx);
                    }
                    // 解析多值(逗号分隔)
                    for v in value.split(',') {
                        let v = v.trim().to_ascii_lowercase();
                        if !v.is_empty() {
                            transfer_encoding_values.push(v);
                        }
                    }
                }
                "host" => {
                    host_count += 1;
                    if host_count > 1 {
                        // RFC 7230 §5.4:多个 Host 头必须拒绝(前后端取词差分走私向量)
                        return Err((
                            SmugglingKind::DuplicateHost,
                            "multiple Host headers".into(),
                        ));
                    }
                    if value.contains('\r') || value.contains('\n') {
                        return Err((
                            SmugglingKind::HostInjection,
                            "host contains CRLF".into(),
                        ));
                    }
                }
                _ => {}
            }

            // 1. 头部值 CRLF 注入检测(在特定头检测之后)
            if value.contains("\r") || value.contains("\n") {
                return Err((
                    SmugglingKind::HeaderInjection,
                    format!("header '{n}' value contains CRLF"),
                ));
            }
            // 控制字符检测
            if Self::contains_invalid_control(value) {
                return Err((
                    SmugglingKind::HeaderInjection,
                    format!("header '{n}' contains invalid control chars"),
                ));
            }
        }

        // 2. CL 和 TE 共存 → 按头部出现顺序区分攻击方向:
        //    CL 在前 → CL.TE(上游用 CL、下游用 TE)
        //    TE 在前 → TE.CL(上游用 TE、下游用 CL)
        if has_content_length && has_te {
            let kind = match (cl_position, te_position) {
                (Some(cl), Some(te)) if te < cl => SmugglingKind::TeCl,
                _ => SmugglingKind::ClTe,
            };
            return Err((
                kind,
                "Content-Length and Transfer-Encoding both present".into(),
            ));
        }

        // 3. TE.TE: 多个 chunked 值或 chunked 不是最后
        if has_te {
            // HTTP-002:RFC 7230 §3.3.1 已废弃 `identity` 作为 Transfer-Encoding
            // 值(该值无传输编码语义且是前后端差分走私向量),出现即拒绝(fail-closed),
            // 不再豁免。此检查须先于 chunked 位置判断,确保含 identity 的 TE 一律拒绝。
            if transfer_encoding_values.iter().any(|v| v == "identity") {
                return Err((
                    SmugglingKind::TeTe,
                    "deprecated 'identity' in Transfer-Encoding (RFC 7230)".into(),
                ));
            }
            let chunked_positions: Vec<usize> = transfer_encoding_values
                .iter()
                .enumerate()
                .filter_map(|(i, v)| (v == "chunked").then_some(i))
                .collect();
            if chunked_positions.len() > 1 {
                return Err((
                    SmugglingKind::TeTe,
                    "multiple 'chunked' in Transfer-Encoding".into(),
                ));
            }
            if let Some(pos) = chunked_positions.first().copied()
                && pos != transfer_encoding_values.len() - 1 {
                    return Err((
                        SmugglingKind::TeTe,
                        "'chunked' not last in Transfer-Encoding".into(),
                    ));
                }
            // TE 存在但无 chunked → 走私嫌疑(fail-closed),与 parser 的 TE 语义统一
            if chunked_positions.is_empty() {
                return Err((
                    SmugglingKind::TeTe,
                    "Transfer-Encoding without 'chunked'".into(),
                ));
            }
        }

        // 4. Host 头缺失(HTTP/1.1 必须存在)不在此处直接报错,
        // 由解析器结合版本上下文决定

        Ok(())
    }

    /// 检测头部序列中的走私攻击(假设头部名称已小写化)
    ///
    /// 与 [`Self::detect`] 语义一致,但假设调用方已将头部名称小写化
    /// (如 [`crate::parser::Http1Parser`] 的 `parse_header_line` 已执行
    /// `to_ascii_lowercase`),跳过每头一次的 `to_ascii_lowercase` 分配。
    ///
    /// # 安全性
    /// 若传入未小写化的头部名称,匹配将失败(如 `Content-Length` 不会匹配
    /// `"content-length"`),可能导致漏检。调用方必须保证名称已小写。
    pub fn detect_already_lowercased<N, V>(
        &self,
        headers: &[(N, V)],
    ) -> Result<(), (SmugglingKind, String)>
    where
        N: AsRef<str>,
        V: AsRef<str>,
    {
        self.detect_impl(headers, |s| Cow::Borrowed(s))
    }

    /// 便捷:直接返回 Http1Error
    pub fn detect_err<N, V>(
        &self,
        headers: &[(N, V)],
    ) -> Result<(), Http1Error>
    where
        N: AsRef<str>,
        V: AsRef<str>,
    {
        self.detect(headers).map_err(|(k, m)| {
            Http1Error::SmugglingDetected(format!("{}: {}", k.as_str(), m))
        })
    }

    /// 便捷:直接返回 Http1Error(假设头部名称已小写化)
    ///
    /// 与 [`Self::detect_err`] 语义一致,但委托 [`Self::detect_already_lowercased`],
    /// 跳过 `to_ascii_lowercase` 分配。调用方必须保证头部名称已小写化。
    pub fn detect_err_already_lowercased<N, V>(
        &self,
        headers: &[(N, V)],
    ) -> Result<(), Http1Error>
    where
        N: AsRef<str>,
        V: AsRef<str>,
    {
        self.detect_already_lowercased(headers).map_err(|(k, m)| {
            Http1Error::SmugglingDetected(format!("{}: {}", k.as_str(), m))
        })
    }

    /// 检测非法控制字符
    #[inline]
    fn contains_invalid_control(s: &str) -> bool {
        // RFC 7230 §3.2.4:field-content 仅允许 VCHAR/obs-text/SP/HTAB,
        // 其余控制字符全量拒绝:0x00-0x08, 0x0b, 0x0c, 0x0e-0x1f, 0x7f
        // (0x0a/0x0d 由 CRLF 检查单独覆盖;HTAB 0x09 为合法 OWS)。
        s.chars().any(|c| {
            let code = c as u32;
            matches!(code, 0x00..=0x08 | 0x0b | 0x0c | 0x0e..=0x1f | 0x7f)
        })
    }
}

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

    #[test]
    fn test_clean_headers() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Content-Length".to_string(), "13".to_string()),
            ("Accept".to_string(), "text/plain".to_string()),
        ];
        assert!(d.detect(&headers).is_ok());
    }

    #[test]
    fn test_cl_te_smuggling() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Content-Length".to_string(), "0".to_string()),
            ("Transfer-Encoding".to_string(), "chunked".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_err());
        assert_eq!(r.unwrap_err().0, SmugglingKind::ClTe);
    }

    #[test]
    fn test_te_te_multiple_chunked() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            (
                "Transfer-Encoding".to_string(),
                "chunked, chunked".to_string(),
            ),
        ];
        let r = d.detect(&headers);
        assert_eq!(r.unwrap_err().0, SmugglingKind::TeTe);
    }

    #[test]
    fn test_te_te_chunked_not_last() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            (
                "Transfer-Encoding".to_string(),
                "chunked, identity".to_string(),
            ),
        ];
        let r = d.detect(&headers);
        assert_eq!(r.unwrap_err().0, SmugglingKind::TeTe);
    }

    #[test]
    fn test_double_content_length() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Content-Length".to_string(), "10".to_string()),
            ("Content-Length".to_string(), "20".to_string()),
        ];
        let r = d.detect(&headers);
        assert_eq!(r.unwrap_err().0, SmugglingKind::DoubleContentLength);
    }

    #[test]
    fn test_header_injection_crlf() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("X-Test".to_string(), "val\r\nEvil: yes".to_string()),
        ];
        let r = d.detect(&headers);
        assert_eq!(r.unwrap_err().0, SmugglingKind::HeaderInjection);
    }

    #[test]
    fn test_host_injection() {
        let d = SmugglingDetector::new();
        let headers = vec![("Host".to_string(), "example.com\r\nX: y".to_string())];
        let r = d.detect(&headers);
        assert_eq!(r.unwrap_err().0, SmugglingKind::HostInjection);
    }

    #[test]
    fn test_duplicate_host_rejected() {
        // RFC 7230 §5.4:多个 Host 头必须拒绝(前后端取词差分走私向量)
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "a.com".to_string()),
            ("Host".to_string(), "b.com".to_string()),
        ];
        let r = d.detect(&headers);
        assert_eq!(r.unwrap_err().0, SmugglingKind::DuplicateHost);
    }

    #[test]
    fn test_duplicate_host_case_insensitive() {
        // 头部名大小写不敏感:HOST + host 同样构成双 Host
        let d = SmugglingDetector::new();
        let headers = vec![
            ("HOST".to_string(), "a.com".to_string()),
            ("host".to_string(), "a.com".to_string()),
        ];
        let r = d.detect(&headers);
        assert_eq!(r.unwrap_err().0, SmugglingKind::DuplicateHost);
    }

    #[test]
    fn test_valid_te_chunked() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Transfer-Encoding".to_string(), "gzip, chunked".to_string()),
        ];
        assert!(d.detect(&headers).is_ok());
    }

    #[test]
    fn test_invalid_control_chars() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("X".to_string(), "val\x00ue".to_string()),
        ];
        let r = d.detect(&headers);
        assert_eq!(r.unwrap_err().0, SmugglingKind::HeaderInjection);
    }

    #[test]
    fn test_smuggling_kind_all_variants() {
        let kinds = [
            SmugglingKind::ClTe,
            SmugglingKind::TeCl,
            SmugglingKind::TeTe,
            SmugglingKind::HostInjection,
            SmugglingKind::HeaderInjection,
            SmugglingKind::DoubleContentLength,
        ];
        for k in kinds.iter() {
            let s = k.as_str();
            assert!(!s.is_empty());
        }
    }

    #[test]
    fn test_smuggling_kind_as_str() {
        assert_eq!(SmugglingKind::ClTe.as_str(), "CL.TE");
        assert_eq!(SmugglingKind::TeCl.as_str(), "TE.CL");
        assert_eq!(SmugglingKind::TeTe.as_str(), "TE.TE");
        assert_eq!(SmugglingKind::HostInjection.as_str(), "Host Injection");
        assert_eq!(SmugglingKind::HeaderInjection.as_str(), "Header Injection");
        assert_eq!(SmugglingKind::DoubleContentLength.as_str(), "Double Content-Length");
    }

    #[test]
    fn test_smuggling_detector_default() {
        let d = SmugglingDetector;
        let headers = vec![("Host".to_string(), "example.com".to_string())];
        assert!(d.detect(&headers).is_ok());
    }

    #[test]
    fn test_smuggling_detector_new() {
        let d = SmugglingDetector::new();
        let headers = vec![("Host".to_string(), "example.com".to_string())];
        assert!(d.detect(&headers).is_ok());
    }

    #[test]
    fn test_detect_err_wraps_correctly() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Content-Length".to_string(), "10".to_string()),
            ("Content-Length".to_string(), "20".to_string()),
        ];
        let r = d.detect_err(&headers);
        assert!(r.is_err());
        let err = r.unwrap_err();
        assert!(matches!(err, Http1Error::SmugglingDetected(_)));
        let err_str = err.to_string();
        assert!(err_str.contains("Double Content-Length"));
    }

    #[test]
    fn test_content_length_not_decimal() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Content-Length".to_string(), "12a3".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_err());
        assert_eq!(r.unwrap_err().0, SmugglingKind::ClTe);
    }

    #[test]
    fn test_content_length_negative_rejected() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Content-Length".to_string(), "-5".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_err());
    }

    #[test]
    fn test_transfer_encoding_whitespace() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Transfer-Encoding".to_string(), "  chunked  ".to_string()),
        ];
        assert!(d.detect(&headers).is_ok());
    }

    #[test]
    fn test_transfer_encoding_mixed_case() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Transfer-Encoding".to_string(), "Chunked".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_ok());
    }

    #[test]
    fn test_header_name_case_insensitive() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("HOST".to_string(), "example.com".to_string()),
            ("content-length".to_string(), "10".to_string()),
        ];
        assert!(d.detect(&headers).is_ok());
    }

    #[test]
    fn test_null_byte_in_header_value() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("X-Test".to_string(), "val\x00ue".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_err());
        assert_eq!(r.unwrap_err().0, SmugglingKind::HeaderInjection);
    }

    #[test]
    fn test_vtab_in_header_value() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("X-Test".to_string(), "val\x0bue".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_err());
        assert_eq!(r.unwrap_err().0, SmugglingKind::HeaderInjection);
    }

    #[test]
    fn test_formfeed_in_header_value() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("X-Test".to_string(), "val\x0cue".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_err());
        assert_eq!(r.unwrap_err().0, SmugglingKind::HeaderInjection);
    }

    #[test]
    fn test_cr_only_in_header_value() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("X-Test".to_string(), "val\revil".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_err());
        assert_eq!(r.unwrap_err().0, SmugglingKind::HeaderInjection);
    }

    #[test]
    fn test_lf_only_in_header_value() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("X-Test".to_string(), "val\nevil".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_err());
        assert_eq!(r.unwrap_err().0, SmugglingKind::HeaderInjection);
    }

    #[test]
    fn test_te_cl_direction_distinguished() {
        // TE 在前、CL 在后 → TE.CL 攻击方向(上游用 TE、下游用 CL)
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Transfer-Encoding".to_string(), "chunked".to_string()),
            ("Content-Length".to_string(), "0".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_err());
        assert_eq!(
            r.unwrap_err().0,
            SmugglingKind::TeCl,
            "TE 在前必须判定为 TE.CL"
        );
    }

    #[test]
    fn test_cl_te_direction_distinguished() {
        // CL 在前、TE 在后 → CL.TE 攻击方向(上游用 CL、下游用 TE)
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Content-Length".to_string(), "0".to_string()),
            ("Transfer-Encoding".to_string(), "chunked".to_string()),
        ];
        let r = d.detect(&headers);
        assert!(r.is_err());
        assert_eq!(
            r.unwrap_err().0,
            SmugglingKind::ClTe,
            "CL 在前必须判定为 CL.TE"
        );
    }

    #[test]
    fn test_te_without_chunked_rejected() {
        // TE 存在但无 chunked 且非 identity → fail-closed 拒绝
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Transfer-Encoding".to_string(), "gzip".to_string()),
        ];
        let r = d.detect(&headers);
        assert_eq!(r.unwrap_err().0, SmugglingKind::TeTe);
    }

    #[test]
    fn test_te_identity_rejected() {
        // HTTP-002:RFC 7230 已废弃 TE: identity,必须拒绝(不再豁免)
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Transfer-Encoding".to_string(), "identity".to_string()),
        ];
        let r = d.detect(&headers);
        assert_eq!(
            r.unwrap_err().0,
            SmugglingKind::TeTe,
            "TE: identity 必须按 TeTe 拒绝(fail-closed)"
        );
    }

    #[test]
    fn test_single_transfer_encoding_chunked() {
        let d = SmugglingDetector::new();
        let headers = vec![
            ("Host".to_string(), "example.com".to_string()),
            ("Transfer-Encoding".to_string(), "chunked".to_string()),
        ];
        assert!(d.detect(&headers).is_ok());
    }

    #[test]
    fn test_empty_headers() {
        let d = SmugglingDetector::new();
        let headers: Vec<(String, String)> = vec![];
        assert!(d.detect(&headers).is_ok());
    }

    #[test]
    fn test_smuggling_kind_debug() {
        let k = SmugglingKind::ClTe;
        let s = format!("{:?}", k);
        assert!(!s.is_empty());
    }

    #[test]
    fn test_smuggling_kind_clone() {
        let k = SmugglingKind::ClTe;
        let k2 = k;
        assert_eq!(k, k2);
    }
}