zenith-web 0.1.0

Zenith Web 应用框架:编译期 Trie 路由、类型化 Extractor、中间件 DAG、静态文件服务、统一错误处理
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
//! Protocol Normalization Layer
//!
//! Normalizes requests from HTTP/1.1, HTTP/2, HTTP/3 into the unified
//! [`CanonicalRequest`] format, and encodes [`CanonicalResponse`] back
//! into protocol-specific wire formats.
//!
//! # Security
//! - Strict RFC compliance for method parsing, pseudo-header ordering,
//!   and forbidden connection-specific headers.
//! - Fail-closed validation: every CRLF, size limit, and count check
//!   returns an error rather than silently truncating.
//! - Protocol-differential attack resistance: all upstream protocols
//!   converge on a single canonical form before application logic.

use std::fmt;

use zenith_api::{
    CanonicalRequest, CanonicalResponse, Method, Protocol, Transport, MAX_HEADER_COUNT,
    MAX_PATH_LEN,
};
use zenith_http1::response::{Http1ResponseEncoder, ResponseSerializeError};
use zenith_http1::types::HttpRequest as Http1Request;
use zenith_http2::error::Http2Error;
use zenith_http2::hpack::HeaderField;
use zenith_http2::response::Http2ResponseEncoder;
use zenith_http3::encoder::Http3ResponseEncoder;
use zenith_http3::frame::Http3Error;

/// Maximum request target length (bytes).  Aligned 1:1 with
/// [`zenith_api::MAX_PATH_LEN`] so [`CanonicalRequest::set_path`] never
/// silently truncates a path that has already passed length validation.
const MAX_REQUEST_TARGET_LEN: usize = MAX_PATH_LEN;

/// Maximum request body size (16 MiB)
const MAX_BODY_SIZE: usize = 16_777_216;

/// Normalization error type.
///
/// All variants carry enough context for logging while avoiding heap
/// allocations on hot error paths where possible.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProtocolNormalizeError {
    /// Request method is not one of the nine RFC 7231 / 9110 methods.
    UnsupportedMethod(String),
    /// A single header value exceeded the implementation limit.
    HeaderTooLong(String),
    /// More than [`MAX_HEADER_COUNT`] headers supplied.
    TooManyHeaders,
    /// Header name failed validation (CRLF injection, invalid UTF-8).
    InvalidHeaderName(String),
    /// Header value failed validation (CRLF injection, invalid UTF-8).
    InvalidHeaderValue(String),
    /// Request target exceeded [`MAX_REQUEST_TARGET_LEN`].
    RequestTargetTooLong,
    /// Request body exceeded the configured size limit.
    BodyTooLarge {
        /// Actual body size in bytes.
        size: usize,
        /// Maximum allowed body size in bytes.
        max: usize,
    },
    /// Low-level protocol violation (pseudo-header ordering, forbidden
    /// connection-specific headers, etc.).
    ProtocolViolation(String),
    /// Internal invariant violation, should never occur in practice.
    Internal(String),
}

impl fmt::Display for ProtocolNormalizeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedMethod(m) => write!(f, "unsupported HTTP method: {m}"),
            Self::HeaderTooLong(h) => write!(f, "header too long: {h}"),
            Self::TooManyHeaders => write!(f, "too many headers (max {MAX_HEADER_COUNT})"),
            Self::InvalidHeaderName(n) => write!(f, "invalid header name: {n}"),
            Self::InvalidHeaderValue(v) => write!(f, "invalid header value: {v}"),
            Self::RequestTargetTooLong => {
                write!(f, "request target too long (max {MAX_REQUEST_TARGET_LEN})")
            }
            Self::BodyTooLarge { size, max } => {
                write!(f, "body too large: {size} bytes (max {max})")
            }
            Self::ProtocolViolation(m) => write!(f, "protocol violation: {m}"),
            Self::Internal(m) => write!(f, "internal normalization error: {m}"),
        }
    }
}

impl std::error::Error for ProtocolNormalizeError {}

/// Parses a raw method string into [`Method`] using strict RFC 7231 / 9110
/// matching: exact case-sensitive comparison, no trimming.
///
/// 单一实现委托 [`Method::from_str`](全库唯一方法解析入口),
/// 消除双解析器分歧引入的规范化绕过(请求走私面)。
#[inline]
pub fn parse_method(s: &str) -> Result<Method, ProtocolNormalizeError> {
    s.parse::<Method>()
        .map_err(|_| ProtocolNormalizeError::UnsupportedMethod(s.to_string()))
}

/// Maps the string error returned by [`CanonicalRequest::add_header`] to
/// the appropriate [`ProtocolNormalizeError`] variant.
fn map_header_err(
    msg: &'static str,
    name: &str,
    value: &str,
) -> ProtocolNormalizeError {
    match msg {
        "header count exceeded" => ProtocolNormalizeError::TooManyHeaders,
        "header name contains CRLF" => ProtocolNormalizeError::InvalidHeaderName(name.to_string()),
        "header value contains CRLF" => ProtocolNormalizeError::InvalidHeaderValue(value.to_string()),
        // zenith-api fail-closed 超长拒绝:映射为对应的非法头部错误
        "header name too long" | "header name or value too long" => {
            ProtocolNormalizeError::InvalidHeaderName(name.to_string())
        }
        "header value too long" => ProtocolNormalizeError::InvalidHeaderValue(value.to_string()),
        other => ProtocolNormalizeError::Internal(other.to_string()),
    }
}

/// Normalizes an HTTP/1.1 [`Http1Request`] into the unified
/// [`CanonicalRequest`] format.
///
/// # Validation performed
/// - Method parsed via [`parse_method`] (strict uppercase match).
/// - Request target capped at [`MAX_REQUEST_TARGET_LEN`] bytes.
/// - Header count limited to [`MAX_HEADER_COUNT`].
/// - Header names and values rejected if they contain CRLF.
/// - Body size capped at [`MAX_BODY_SIZE`] bytes.
pub fn normalize_http1_request(
    req: &Http1Request,
    transport: Transport,
) -> Result<CanonicalRequest, ProtocolNormalizeError> {
    let method = parse_method(&req.line.method)?;

    if req.line.target.len() > MAX_REQUEST_TARGET_LEN {
        return Err(ProtocolNormalizeError::RequestTargetTooLong);
    }

    let mut canonical = CanonicalRequest::empty();
    canonical.method = method;
    canonical.protocol = Protocol::Http1;
    canonical.transport = transport;
    // 点段折叠(RFC 3986 §5.2.4):防路径穿越绕过 WAF/路由匹配。
    // decode=false:不 percent-decode(保持现有行为,H1 parser 已处理编码)。
    let normalized_path = zenith_api::normalize::normalize_path(&req.line.target, false)
        .map_err(|e| ProtocolNormalizeError::ProtocolViolation(format!("invalid path: {}", e.message)))?;
    // zenith-api fail-closed:set_path 内部触发 canonicalize 校验
    // (非法字节/CRLF/超长),false 不得静默放行
    if !canonical.set_path(&normalized_path) {
        return Err(ProtocolNormalizeError::ProtocolViolation(
            "path canonicalization rejected".to_string(),
        ));
    }

    for (name, value) in &req.headers {
        canonical
            .add_header(name.as_bytes(), value.as_bytes())
            .map_err(|e| map_header_err(e, name, value))?;
    }

    if req.body.len() > MAX_BODY_SIZE {
        return Err(ProtocolNormalizeError::BodyTooLarge {
            size: req.body.len(),
            max: MAX_BODY_SIZE,
        });
    }

    // 真实拷贝 Body 到 CanonicalRequest:
    // - <= MAX_BODY_LEN (4 KiB 默认) → 栈上 body_buffer,零堆分配
    // - > MAX_BODY_LEN → 堆分配 body_overflow,保证正确性不截断
    // (MAX_BODY_SIZE 可能远大于 MAX_BODY_LEN;两者校验层级不同:
    //   MAX_BODY_SIZE 是业务拒绝上限,MAX_BODY_LEN 是栈/堆切换阈值)
    canonical.set_body(req.body.clone());

    Ok(canonical)
}

/// Forbidden connection-specific header names for HTTP/2 and HTTP/3.
///
/// RFC 7540 §8.1.2.2 and RFC 9114 §4.3 prohibit these.
const FORBIDDEN_H2_H3_HEADERS: &[&[u8]] = &[
    b"connection",
    b"keep-alive",
    b"proxy-connection",
    b"transfer-encoding",
    b"upgrade",
];

/// Checks whether `name` (lowercased ASCII) is in the forbidden
/// connection-specific header list.
fn is_forbidden_connection_header(name: &[u8]) -> bool {
    FORBIDDEN_H2_H3_HEADERS
        .iter()
        .any(|forbidden| forbidden.eq_ignore_ascii_case(name))
}

/// H2/H3 公共规范化内核(RFC 7540 §8.1.2 / RFC 9114 §4.3 共享语义)。
///
/// 两协议除输入编码(HPACK `HeaderField` vs QPACK 原始字节对)外逐点同构,
/// 收敛为单一内核以消除双实现分歧(安全规则漂移面)。
///
/// # Validation performed
/// - Pseudo-headers (`:`-prefixed) must precede any regular header.
/// - Required pseudo-headers `:method`, `:path`, `:scheme` are all present.
/// - `:authority` 必须存在(AGENT §4.5 authority 一致性);CONNECT 与
///   Asterisk-form(`OPTIONS *`)例外放行。
/// - Method parsed via [`parse_method`].
/// - Path length capped at [`MAX_REQUEST_TARGET_LEN`] bytes.
/// - No connection-specific headers (connection, keep-alive,
///   proxy-connection, transfer-encoding, upgrade).
/// - `:scheme` 与 `transport` 必须一致(拒绝跨协议走私)。
fn normalize_h23_request_core<'a, I>(
    pairs: I,
    total_len: usize,
    transport: Transport,
    protocol: Protocol,
) -> Result<CanonicalRequest, ProtocolNormalizeError>
where
    I: Iterator<Item = (&'a str, &'a str)>,
{
    let mut past_pseudo = false;
    let mut method: Option<Method> = None;
    // 伪首部借用解码输出中的字符串,避免一次堆分配;
    // CanonicalRequest::set_path 内部会把 path 再复制到固定缓冲,
    // 因此零拷贝只在 normalize 层生效。
    let mut path: Option<&str> = None;
    let mut scheme: Option<&str> = None;
    let mut authority: Option<&str> = None;
    // 预分配:RFC 限制 ≤ MAX_HEADER_COUNT,这里上限由该常量约束。
    let cap = total_len.min(MAX_HEADER_COUNT);
    let mut regular_headers: Vec<(&str, &str)> = Vec::with_capacity(cap);

    for (name, value) in pairs {
        if name.starts_with(':') {
            if past_pseudo {
                return Err(ProtocolNormalizeError::ProtocolViolation(
                    "pseudo-header after regular header".to_string(),
                ));
            }
            match name {
                ":method" => {
                    // 重复伪首部 fail-closed(RFC 7540 §8.1.2.1 / RFC 9114 §4.3:
                    // "A request or response containing more than one pseudo-header
                    // field of a given type MUST be treated as malformed")。
                    // 修复前以"后写覆盖"静默放行第一个值,H3 面由此弱于 H2 connection 层。
                    if method.is_some() {
                        return Err(ProtocolNormalizeError::ProtocolViolation(
                            "duplicate pseudo-header: :method".to_string(),
                        ));
                    }
                    let m = parse_method(value)?;
                    method = Some(m);
                }
                ":path" => {
                    if path.is_some() {
                        return Err(ProtocolNormalizeError::ProtocolViolation(
                            "duplicate pseudo-header: :path".to_string(),
                        ));
                    }
                    // RFC 7540 §8.1.2.3 / RFC 9114 §4.3.1:":path" 不得为空
                    // (除 OPTIONS * 的 asterisk-form 外)。空 :path 必须以
                    // stream error PROTOCOL_ERROR 拒绝(h2spec 8.1.2.3 #1)。
                    if value.is_empty() {
                        return Err(ProtocolNormalizeError::ProtocolViolation(
                            "empty :path pseudo-header".to_string(),
                        ));
                    }
                    if value.len() > MAX_REQUEST_TARGET_LEN {
                        return Err(ProtocolNormalizeError::RequestTargetTooLong);
                    }
                    path = Some(value);
                }
                ":scheme" => {
                    if scheme.is_some() {
                        return Err(ProtocolNormalizeError::ProtocolViolation(
                            "duplicate pseudo-header: :scheme".to_string(),
                        ));
                    }
                    scheme = Some(value);
                }
                ":authority" => {
                    if authority.is_some() {
                        return Err(ProtocolNormalizeError::ProtocolViolation(
                            "duplicate pseudo-header: :authority".to_string(),
                        ));
                    }
                    authority = Some(value);
                }
                other => {
                    return Err(ProtocolNormalizeError::ProtocolViolation(format!(
                        "unknown pseudo-header: {other}"
                    )));
                }
            }
        } else {
            past_pseudo = true;
            // 头名必须小写(RFC 7540 §8.1.2 / RFC 9114 §4.2:
            // "field names MUST be converted to lowercase prior to encoding"),
            // 大写字母即协议违规(fail-closed 拒绝,与 H2 connection 层
            // validate_regular_header 同一判据,修复 H3 面无等价检查缺陷)。
            if name.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
                return Err(ProtocolNormalizeError::ProtocolViolation(format!(
                    "uppercase header name rejected (must be lowercase): {name}"
                )));
            }
            if is_forbidden_connection_header(name.as_bytes()) {
                return Err(ProtocolNormalizeError::ProtocolViolation(format!(
                    "forbidden connection-specific header: {name}"
                )));
            }
            // te 语义(RFC 7540 §8.1.2.2 / RFC 9114 §4.2):除 "trailers" 外
            // 一切取值拒绝(与 H2 connection 层同一判据)。
            if name.eq_ignore_ascii_case("te") && !value.eq_ignore_ascii_case("trailers") {
                return Err(ProtocolNormalizeError::ProtocolViolation(format!(
                    "te header must be 'trailers', got: {value}"
                )));
            }
            if regular_headers.len() >= MAX_HEADER_COUNT {
                return Err(ProtocolNormalizeError::TooManyHeaders);
            }
            regular_headers.push((name, value));
        }
    }

    let method =
        method.ok_or_else(|| ProtocolNormalizeError::ProtocolViolation("missing :method".to_string()))?;
    let path =
        path.ok_or_else(|| ProtocolNormalizeError::ProtocolViolation("missing :path".to_string()))?;
    // :scheme 必须存在(RFC 7540 §8.1.2.3 / RFC 9114 §4.3.1);记录一次以便拒绝缺失值,
    // 但 CanonicalRequest 当前未直接暴露 scheme 字段,因此此处显式使用而不是以
    // `_scheme` 形式丢弃。
    let scheme_val =
        scheme.ok_or_else(|| ProtocolNormalizeError::ProtocolViolation("missing :scheme".to_string()))?;
    // :authority 必须存在(RFC 7540 §8.1.2.3 / RFC 9114 §4.3.1,AGENT §4.5 四元一致性)。
    // CONNECT(authority-form)/ Asterisk-form(OPTIONS *)例外放行:
    // 这两类请求目标语义不以 authority 为路由身份。
    let asterisk_form = method == Method::Options && path == "*";
    if method != Method::Connect
        && !asterisk_form
        && authority.is_none()
    {
        return Err(ProtocolNormalizeError::ProtocolViolation(
            "missing :authority".to_string(),
        ));
    }
    // 检查 :scheme 与 transport 是否一致,拒绝跨协议走私请求。
    let schemes_match = matches!(
        (transport, scheme_val),
        (Transport::Plaintext, "http") | (Transport::Tls13, "https")
    );
    if !schemes_match {
        return Err(ProtocolNormalizeError::ProtocolViolation(format!(
            "transport/scheme mismatch: transport={transport:?} scheme={scheme_val}"
        )));
    }

    let mut canonical = CanonicalRequest::empty();
    canonical.method = method;
    canonical.protocol = protocol;
    canonical.transport = transport;
    // 点段折叠(RFC 3986 §5.2.4):防路径穿越绕过 WAF/路由匹配。
    // decode=false:不 percent-decode(保持现有行为)。
    let normalized_path = zenith_api::normalize::normalize_path(path, false)
        .map_err(|e| ProtocolNormalizeError::ProtocolViolation(format!("invalid path: {}", e.message)))?;
    // zenith-api fail-closed:set_path 内部触发 canonicalize 校验
    // (非法字节/CRLF/超长),false 不得静默放行
    if !canonical.set_path(&normalized_path) {
        return Err(ProtocolNormalizeError::ProtocolViolation(
            "path canonicalization rejected".to_string(),
        ));
    }

    if let Some(auth) = authority {
        // zenith-api fail-closed:authority 不变量失守不得静默放行
        if !canonical.set_authority(auth) {
            return Err(ProtocolNormalizeError::ProtocolViolation(
                "authority canonicalization rejected".to_string(),
            ));
        }
    }

    for (name, value) in regular_headers {
        canonical
            .add_header(name.as_bytes(), value.as_bytes())
            .map_err(|e| map_header_err(e, name, value))?;
    }

    Ok(canonical)
}

/// Normalizes a list of HPACK-decoded HTTP/2 headers into the unified
/// [`CanonicalRequest`] format.
///
/// 薄封装:伪/常规头部借用 `HeaderField` 字符串(HPACK 输出已是 UTF-8
/// 字符串,无需二次校验),实际校验逻辑全部收敛于
/// [`normalize_h23_request_core`]。Same header / body size limits as HTTP/1.1.
pub fn normalize_http2_request(
    headers: &[HeaderField],
    transport: Transport,
) -> Result<CanonicalRequest, ProtocolNormalizeError> {
    normalize_h23_request_core(
        headers.iter().map(|h| (h.name.as_str(), h.value.as_str())),
        headers.len(),
        transport,
        Protocol::Http2,
    )
}

/// Normalizes a list of QPACK-decoded HTTP/3 raw `(name, value)` byte pairs
/// into the unified [`CanonicalRequest`] format.
///
/// 薄封装:QPACK 交付原始字节而非保证 UTF-8 的字符串,因此 UTF-8 校验
/// 保留在本层(错误类型/顺序与原实现一致),核心逻辑委托
/// [`normalize_h23_request_core`](与 HTTP/2 同内核)。
pub fn normalize_http3_request(
    headers: &[(Vec<u8>, Vec<u8>)],
    transport: Transport,
) -> Result<CanonicalRequest, ProtocolNormalizeError> {
    // UTF-8 校验(RFC 9114 §4.3:QPACK 原始字节必须合法 UTF-8);
    // 临时对偶向量复用 MAX_HEADER_COUNT 上限约束,生命周期绑定输入 headers。
    let mut pairs: Vec<(&str, &str)> = Vec::with_capacity(headers.len().min(MAX_HEADER_COUNT));
    for (name_raw, value_raw) in headers {
        let name = std::str::from_utf8(name_raw).map_err(|_| {
            ProtocolNormalizeError::InvalidHeaderName(String::from_utf8_lossy(name_raw).to_string())
        })?;
        let value = std::str::from_utf8(value_raw).map_err(|_| {
            ProtocolNormalizeError::InvalidHeaderValue(String::from_utf8_lossy(value_raw).to_string())
        })?;
        pairs.push((name, value));
    }

    normalize_h23_request_core(pairs.into_iter(), headers.len(), transport, Protocol::Http3)
}

/// Encodes a [`CanonicalResponse`] into HTTP/1.1 wire format, appending to
/// the provided output buffer.
///
/// Delegates to [`Http1ResponseEncoder::encode`] and maps serialization
/// errors to [`ProtocolNormalizeError`].
pub fn encode_response_http1(
    resp: &CanonicalResponse,
    out: &mut Vec<u8>,
) -> Result<usize, ProtocolNormalizeError> {
    Http1ResponseEncoder::encode(resp, out).map_err(|e| match e {
        ResponseSerializeError::CrlfInjection => {
            ProtocolNormalizeError::InvalidHeaderValue("CRLF injection detected".to_string())
        }
        ResponseSerializeError::InvalidHeaderName => {
            ProtocolNormalizeError::InvalidHeaderName("invalid header name character".to_string())
        }
    })
}

/// Encodes a [`CanonicalResponse`] into HTTP/2 frame bytes for the given
/// stream ID.
///
/// Delegates to [`Http2ResponseEncoder::encode`] and maps [`Http2Error`] to
/// [`ProtocolNormalizeError`]. Protocol-level errors map to
/// [`ProtocolNormalizeError::ProtocolViolation`]; all others map to
/// [`ProtocolNormalizeError::Internal`].
pub fn encode_response_http2(
    encoder: &mut Http2ResponseEncoder,
    resp: &CanonicalResponse,
    stream_id: u32,
) -> Result<Vec<u8>, ProtocolNormalizeError> {
    encoder.encode(resp, stream_id).map_err(|e| match e {
        Http2Error::ProtocolError(m) => ProtocolNormalizeError::ProtocolViolation(m),
        Http2Error::FrameFormatError(m) => ProtocolNormalizeError::ProtocolViolation(m),
        Http2Error::ConnectionError(code) => {
            ProtocolNormalizeError::ProtocolViolation(format!("connection error: {code}"))
        }
        Http2Error::StreamError(id, info) => ProtocolNormalizeError::ProtocolViolation(format!(
            "stream {id} error ({}): {}",
            info.code, info.message
        )),
        Http2Error::CompressionError(m) => ProtocolNormalizeError::ProtocolViolation(m),
        Http2Error::RapidReset(n) => {
            ProtocolNormalizeError::ProtocolViolation(format!("rapid reset: {n}"))
        }
        Http2Error::FrameTooShort
        | Http2Error::FrameTooLarge
        | Http2Error::UnknownFrameType(_)
        | Http2Error::FlowControlError(_)
        | Http2Error::SettingsError(_)
        | Http2Error::UnknownSettingId(_)
        | Http2Error::IntegerOverflow(_)
        | Http2Error::Internal(_) => ProtocolNormalizeError::Internal(e.to_string()),
    })
}

/// Encodes a [`CanonicalResponse`] into HTTP/3 frame bytes.
///
/// Converts the [`CanonicalResponse`] headers into the raw `(Vec<u8>, Vec<u8>)`
/// pairs expected by [`Http3ResponseEncoder::encode_response`], and maps
/// [`Http3Error`] to [`ProtocolNormalizeError`].
pub fn encode_response_http3(
    encoder: &mut Http3ResponseEncoder,
    resp: &CanonicalResponse,
    _stream_id: u64,
) -> Result<Vec<u8>, ProtocolNormalizeError> {
    let raw_headers_cap = resp.header_count() as usize;
    let mut raw_headers: Vec<(Vec<u8>, Vec<u8>)> = Vec::with_capacity(raw_headers_cap);
    for h in resp.headers_iter() {
        raw_headers.push((
            h.name_str().as_bytes().to_vec(),
            h.value_str().as_bytes().to_vec(),
        ));
    }

    encoder
        .encode_response(resp.status_code, &raw_headers, resp.body())
        .map_err(|e| match e {
            Http3Error::ProtocolError(m) => ProtocolNormalizeError::ProtocolViolation(m),
            Http3Error::FrameFormatError(m) => ProtocolNormalizeError::ProtocolViolation(m),
            Http3Error::StreamError(id, code) => {
                ProtocolNormalizeError::ProtocolViolation(format!("stream {id} error: {code}"))
            }
            Http3Error::FrameTooShort
            | Http3Error::FrameTooLarge
            | Http3Error::UnknownFrameType(_)
            | Http3Error::InternalError(_) => ProtocolNormalizeError::Internal(e.to_string()),
        })
}

/// Maps a raw ALPN protocol identifier to the corresponding [`Protocol`].
///
/// Recognized values:
/// - `b"h2"` → [`Protocol::Http2`]
/// - `b"http/1.1"` → [`Protocol::Http1`]
/// - `b"h3"` → [`Protocol::Http3`]
///
/// All other inputs return [`None`].
#[inline]
pub fn alpn_to_protocol(alpn: &[u8]) -> Option<Protocol> {
    match zenith_tls::sni::Alpn::from_bytes(alpn) {
        zenith_tls::sni::Alpn::Http1 => Some(Protocol::Http1),
        zenith_tls::sni::Alpn::Http2 => Some(Protocol::Http2),
        zenith_tls::sni::Alpn::Http3 => Some(Protocol::Http3),
        zenith_tls::sni::Alpn::Unknown => None,
    }
}

// ─────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────

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

    // ───────── parse_method ─────────

    #[test]
    fn parse_method_all_standard() {
        assert_eq!(parse_method("GET"), Ok(Method::Get));
        assert_eq!(parse_method("POST"), Ok(Method::Post));
        assert_eq!(parse_method("PUT"), Ok(Method::Put));
        assert_eq!(parse_method("DELETE"), Ok(Method::Delete));
        assert_eq!(parse_method("PATCH"), Ok(Method::Patch));
        assert_eq!(parse_method("HEAD"), Ok(Method::Head));
        assert_eq!(parse_method("OPTIONS"), Ok(Method::Options));
        assert_eq!(parse_method("TRACE"), Ok(Method::Trace));
        assert_eq!(parse_method("CONNECT"), Ok(Method::Connect));
    }

    #[test]
    fn parse_method_unknown() {
        let err = parse_method("FOOBAR").unwrap_err();
        assert!(matches!(err, ProtocolNormalizeError::UnsupportedMethod(ref m) if m == "FOOBAR"));
    }

    #[test]
    fn parse_method_case_sensitive() {
        assert!(parse_method("get").is_err());
        assert!(parse_method("Get").is_err());
        assert!(parse_method("Post ").is_err());
        assert!(parse_method(" GET").is_err());
    }

    // ───────── normalize_http1_request ─────────

    fn make_http1(method: &str, target: &str) -> Http1Request {
        let mut r = Http1Request::new(method.into(), target.into(), "HTTP/1.1".into());
        r.keep_alive = true;
        r
    }

    #[test]
    fn normalize_http1_simple_get() {
        let mut req = make_http1("GET", "/");
        req.headers
            .push(("content-type".into(), "application/json".into()));

        let c = normalize_http1_request(&req, Transport::Plaintext).unwrap();
        assert_eq!(c.method, Method::Get);
        assert_eq!(c.protocol, Protocol::Http1);
        assert_eq!(c.transport, Transport::Plaintext);
        assert_eq!(c.path_str(), "/");
        assert_eq!(c.header_count(), 1);
        let h = c.find_header("content-type").unwrap();
        assert_eq!(h.value_str(), "application/json");
    }

    #[test]
    fn normalize_http1_body_within_limit_ok() {
        let mut req = make_http1("POST", "/submit");
        req.body = b"hello world".to_vec();
        let c = normalize_http1_request(&req, Transport::Tls13).unwrap();
        assert_eq!(c.method, Method::Post);
        assert_eq!(c.transport, Transport::Tls13);
    }

    #[test]
    fn normalize_http1_body_too_large() {
        let mut req = make_http1("POST", "/submit");
        req.body = vec![b'x'; MAX_BODY_SIZE + 1];
        let err = normalize_http1_request(&req, Transport::Plaintext).unwrap_err();
        assert!(matches!(
            err,
            ProtocolNormalizeError::BodyTooLarge { size, max }
                if size == MAX_BODY_SIZE + 1 && max == MAX_BODY_SIZE
        ));
    }

    #[test]
    fn normalize_http1_too_many_headers() {
        let mut req = make_http1("GET", "/");
        for i in 0..MAX_HEADER_COUNT + 1 {
            req.headers
                .push((format!("h{i}").into(), format!("v{i}").into()));
        }
        let err = normalize_http1_request(&req, Transport::Plaintext).unwrap_err();
        assert!(matches!(err, ProtocolNormalizeError::TooManyHeaders));
    }

    #[test]
    fn normalize_http1_crlf_in_header_value() {
        let mut req = make_http1("GET", "/");
        req.headers
            .push(("x-evil".into(), "val\r\nInjected: yes".into()));
        let err = normalize_http1_request(&req, Transport::Plaintext).unwrap_err();
        assert!(matches!(
            err,
            ProtocolNormalizeError::InvalidHeaderValue(ref v) if v.contains("val")
        ));
    }

    #[test]
    fn normalize_http1_unsupported_method() {
        let req = make_http1("FOO", "/");
        let err = normalize_http1_request(&req, Transport::Plaintext).unwrap_err();
        assert!(matches!(err, ProtocolNormalizeError::UnsupportedMethod(_)));
    }

    #[test]
    fn normalize_http1_target_too_long() {
        let long_target = "a".repeat(MAX_REQUEST_TARGET_LEN + 1);
        let req = make_http1("GET", &long_target);
        let err = normalize_http1_request(&req, Transport::Plaintext).unwrap_err();
        assert!(matches!(err, ProtocolNormalizeError::RequestTargetTooLong));
    }

    #[test]
    fn normalize_http1_keep_alive_header_preserved() {
        let mut req = make_http1("GET", "/");
        req.headers
            .push(("keep-alive".into(), "timeout=5".into()));
        let c = normalize_http1_request(&req, Transport::Plaintext).unwrap();
        assert!(c.find_header("keep-alive").is_some());
    }

    // ───────── normalize_http2_request ─────────

    #[test]
    fn normalize_http2_valid() {
        let headers = vec![
            HeaderField::new(":method", "GET"),
            HeaderField::new(":path", "/api"),
            HeaderField::new(":scheme", "https"),
            HeaderField::new(":authority", "example.com"),
            HeaderField::new("content-type", "application/json"),
        ];
        let c = normalize_http2_request(&headers, Transport::Tls13).unwrap();
        assert_eq!(c.method, Method::Get);
        assert_eq!(c.protocol, Protocol::Http2);
        assert_eq!(c.path_str(), "/api");
        assert_eq!(c.authority_str(), "example.com");
        assert_eq!(c.header_count(), 1);
    }

    #[test]
    fn normalize_http2_pseudo_after_regular() {
        let headers = vec![
            HeaderField::new("content-type", "text/plain"),
            HeaderField::new(":method", "GET"),
            HeaderField::new(":path", "/"),
            HeaderField::new(":scheme", "http"),
        ];
        let err = normalize_http2_request(&headers, Transport::Plaintext).unwrap_err();
        assert!(matches!(
            err,
            ProtocolNormalizeError::ProtocolViolation(ref m) if m.contains("pseudo-header after regular")
        ));
    }

    #[test]
    fn normalize_http2_missing_method() {
        let headers = vec![
            HeaderField::new(":path", "/"),
            HeaderField::new(":scheme", "http"),
        ];
        let err = normalize_http2_request(&headers, Transport::Plaintext).unwrap_err();
        assert!(matches!(
            err,
            ProtocolNormalizeError::ProtocolViolation(ref m) if m.contains("missing :method")
        ));
    }

    #[test]
    fn normalize_http2_forbidden_connection_header() {
        let headers = vec![
            HeaderField::new(":method", "GET"),
            HeaderField::new(":path", "/"),
            HeaderField::new(":scheme", "http"),
            HeaderField::new("connection", "keep-alive"),
        ];
        let err = normalize_http2_request(&headers, Transport::Plaintext).unwrap_err();
        assert!(matches!(
            err,
            ProtocolNormalizeError::ProtocolViolation(ref m) if m.contains("connection")
        ));
    }

    #[test]
    fn normalize_http2_unknown_method() {
        let headers = vec![
            HeaderField::new(":method", "FOOBAR"),
            HeaderField::new(":path", "/"),
            HeaderField::new(":scheme", "http"),
        ];
        let err = normalize_http2_request(&headers, Transport::Plaintext).unwrap_err();
        assert!(matches!(err, ProtocolNormalizeError::UnsupportedMethod(_)));
    }

    #[test]
    fn normalize_http2_missing_authority_rejected() {
        // 非 CONNECT 请求缺失 :authority → 拒绝(AGENT §4.5 / RFC 7540 §8.1.2.3)
        let headers = vec![
            HeaderField::new(":method", "GET"),
            HeaderField::new(":path", "/"),
            HeaderField::new(":scheme", "http"),
        ];
        let err = normalize_http2_request(&headers, Transport::Plaintext).unwrap_err();
        assert!(matches!(
            err,
            ProtocolNormalizeError::ProtocolViolation(ref m) if m.contains("missing :authority")
        ));
    }

    #[test]
    fn normalize_http2_connect_without_authority_ok() {
        // CONNECT(authority-form)例外放行:无 :authority 不拒绝;
        // :method/:path/:scheme 必需伪首部规则维持原语义。
        let headers = vec![
            HeaderField::new(":method", "CONNECT"),
            HeaderField::new(":path", "/"),
            HeaderField::new(":scheme", "http"),
        ];
        let c = normalize_http2_request(&headers, Transport::Plaintext).unwrap();
        assert_eq!(c.method, Method::Connect);
        assert_eq!(c.authority_str(), "");
    }

    #[test]
    fn normalize_http2_asterisk_form_without_authority_ok() {
        // Asterisk-form(OPTIONS *)例外放行
        let headers = vec![
            HeaderField::new(":method", "OPTIONS"),
            HeaderField::new(":path", "*"),
            HeaderField::new(":scheme", "http"),
        ];
        let c = normalize_http2_request(&headers, Transport::Plaintext).unwrap();
        assert_eq!(c.method, Method::Options);
    }

    // ───────── normalize_http3_request ─────────

    #[test]
    fn normalize_http3_valid() {
        let headers: Vec<(Vec<u8>, Vec<u8>)> = vec![
            (b":method".to_vec(), b"POST".to_vec()),
            (b":path".to_vec(), b"/submit".to_vec()),
            (b":scheme".to_vec(), b"https".to_vec()),
            (b":authority".to_vec(), b"example.com".to_vec()),
            (b"accept".to_vec(), b"*/*".to_vec()),
        ];
        let c = normalize_http3_request(&headers, Transport::Tls13).unwrap();
        assert_eq!(c.method, Method::Post);
        assert_eq!(c.protocol, Protocol::Http3);
        assert_eq!(c.path_str(), "/submit");
        assert_eq!(c.authority_str(), "example.com");
        assert_eq!(c.header_count(), 1);
    }

    #[test]
    fn normalize_http3_transfer_encoding_forbidden() {
        let headers: Vec<(Vec<u8>, Vec<u8>)> = vec![
            (b":method".to_vec(), b"GET".to_vec()),
            (b":path".to_vec(), b"/".to_vec()),
            (b":scheme".to_vec(), b"http".to_vec()),
            (b"transfer-encoding".to_vec(), b"chunked".to_vec()),
        ];
        let err = normalize_http3_request(&headers, Transport::Plaintext).unwrap_err();
        assert!(matches!(
            err,
            ProtocolNormalizeError::ProtocolViolation(ref m) if m.contains("transfer-encoding")
        ));
    }

    #[test]
    fn normalize_http3_missing_authority_rejected() {
        // 非 CONNECT 请求缺失 :authority → 拒绝(AGENT §4.5 / RFC 9114 §4.3.1)
        let headers: Vec<(Vec<u8>, Vec<u8>)> = vec![
            (b":method".to_vec(), b"GET".to_vec()),
            (b":path".to_vec(), b"/".to_vec()),
            (b":scheme".to_vec(), b"http".to_vec()),
        ];
        let err = normalize_http3_request(&headers, Transport::Plaintext).unwrap_err();
        assert!(matches!(
            err,
            ProtocolNormalizeError::ProtocolViolation(ref m) if m.contains("missing :authority")
        ));
    }

    #[test]
    fn normalize_http3_connect_without_authority_ok() {
        // CONNECT 例外放行(与 H2 公共内核同语义)
        let headers: Vec<(Vec<u8>, Vec<u8>)> = vec![
            (b":method".to_vec(), b"CONNECT".to_vec()),
            (b":path".to_vec(), b"/".to_vec()),
            (b":scheme".to_vec(), b"https".to_vec()),
        ];
        let c = normalize_http3_request(&headers, Transport::Tls13).unwrap();
        assert_eq!(c.method, Method::Connect);
    }

    // ───────── encode_response_http1 ─────────

    #[test]
    fn encode_response_http1_round_trip_format() {
        let mut resp = CanonicalResponse::new(200);
        resp.add_header(b"content-type", b"text/plain").unwrap();
        resp.set_body(b"Hello");

        let mut out = Vec::new();
        let n = encode_response_http1(&resp, &mut out).unwrap();
        assert_eq!(n, out.len());

        let s = String::from_utf8(out).unwrap();
        assert!(s.starts_with("HTTP/1.1 200 OK\r\n"));
        assert!(s.contains("content-type: text/plain\r\n"));
        assert!(s.ends_with("\r\nHello"));
    }

    // ───────── alpn_to_protocol ─────────

    #[test]
    fn alpn_matches() {
        assert_eq!(alpn_to_protocol(b"h2"), Some(Protocol::Http2));
        assert_eq!(alpn_to_protocol(b"http/1.1"), Some(Protocol::Http1));
        assert_eq!(alpn_to_protocol(b"h3"), Some(Protocol::Http3));
    }

    #[test]
    fn alpn_unknown_is_none() {
        assert_eq!(alpn_to_protocol(b"http/0.9"), None);
        assert_eq!(alpn_to_protocol(b""), None);
        assert_eq!(alpn_to_protocol(b"h2c"), None);
        assert_eq!(alpn_to_protocol(b"H2"), None);
    }

    // ───────── ProtocolNormalizeError Display ─────────

    #[test]
    fn normalize_error_display_variants() {
        let cases: Vec<(ProtocolNormalizeError, &str)> = vec![
            (
                ProtocolNormalizeError::UnsupportedMethod("FOO".into()),
                "unsupported HTTP method: FOO",
            ),
            (
                ProtocolNormalizeError::HeaderTooLong("x-big".into()),
                "header too long: x-big",
            ),
            (ProtocolNormalizeError::TooManyHeaders, "too many headers"),
            (
                ProtocolNormalizeError::InvalidHeaderName("bad name".into()),
                "invalid header name: bad name",
            ),
            (
                ProtocolNormalizeError::InvalidHeaderValue("bad val".into()),
                "invalid header value: bad val",
            ),
            (
                ProtocolNormalizeError::RequestTargetTooLong,
                "request target too long",
            ),
            (
                ProtocolNormalizeError::BodyTooLarge {
                    size: 100,
                    max: 50,
                },
                "body too large: 100 bytes (max 50)",
            ),
            (
                ProtocolNormalizeError::ProtocolViolation("oops".into()),
                "protocol violation: oops",
            ),
            (
                ProtocolNormalizeError::Internal("bug".into()),
                "internal normalization error: bug",
            ),
        ];
        for (err, expected) in cases {
            let msg = err.to_string();
            assert!(
                msg.contains(expected),
                "display mismatch:\n  expected to contain: {expected}\n  actual: {msg}"
            );
        }
    }

    /// 回归(曾后写覆盖放行):重复伪首部必须 fail-closed
    /// (RFC 7540 §8.1.2.1 / RFC 9114 §4.3:malformed request)。
    /// 经 H3 层(QPACK 输入 -> normalize_http3_request)复现最小路径。
    #[test]
    fn h23_duplicate_pseudo_header_rejected() {
        fn h3(pairs: Vec<(&str, &str)>) -> Result<CanonicalRequest, ProtocolNormalizeError> {
            let bytes: Vec<(Vec<u8>, Vec<u8>)> = pairs
                .into_iter()
                .map(|(n, v)| (n.as_bytes().to_vec(), v.as_bytes().to_vec()))
                .collect();
            normalize_http3_request(&bytes, Transport::Tls13)
        }

        for dup in [":method", ":path", ":scheme", ":authority"] {
            let err = h3(vec![
                (":method", "GET"),
                (":path", "/"),
                (":scheme", "https"),
                (":authority", "a.com"),
                (dup, "x"),
            ])
            .unwrap_err();
            assert!(
                matches!(err, ProtocolNormalizeError::ProtocolViolation(ref m) if m.contains("duplicate pseudo-header")),
                "duplicate {dup} not rejected: {err}"
            );
        }
        // 无重复 → 基线通过
        let ok = h3(vec![
            (":method", "GET"), (":path", "/"), (":scheme", "https"), (":authority", "a.com"),
        ]);
        assert!(ok.is_ok());
    }

    /// 回归(曾直接放行):H2/H3 头名必须小写(RFC 7540 §8.1.2 / RFC 9114 §4.2)。
    #[test]
    fn h23_uppercase_header_name_rejected() {
        let bytes = vec![
            (b":method".to_vec(), b"GET".to_vec()),
            (b":path".to_vec(), b"/".to_vec()),
            (b":scheme".to_vec(), b"https".to_vec()),
            (b":authority".to_vec(), b"a.com".to_vec()),
            (b"X-Custom".to_vec(), b"v".to_vec()),
        ];
        let err = normalize_http3_request(&bytes, Transport::Tls13).unwrap_err();
        assert!(matches!(
            err,
            ProtocolNormalizeError::ProtocolViolation(ref m) if m.contains("uppercase header name")
        ));
        // 纯小写大写混合数字/连字符均接受
        let ok = vec![
            (b":method".to_vec(), b"GET".to_vec()),
            (b":path".to_vec(), b"/".to_vec()),
            (b":scheme".to_vec(), b"https".to_vec()),
            (b":authority".to_vec(), b"a.com".to_vec()),
            (b"x-custom-1".to_vec(), b"v".to_vec()),
        ];
        assert!(normalize_http3_request(&ok, Transport::Tls13).is_ok());
    }

    /// 回归(曾无 te 规则):`te` 头仅允许 "trailers"
    /// (RFC 7540 §8.1.2.2 / RFC 9114 §4.2,走私向量)。
    #[test]
    fn h23_te_must_be_trailers() {
        // trailers 放行
        let ok = vec![
            (b":method".to_vec(), b"GET".to_vec()),
            (b":path".to_vec(), b"/".to_vec()),
            (b":scheme".to_vec(), b"https".to_vec()),
            (b":authority".to_vec(), b"a.com".to_vec()),
            (b"te".to_vec(), b"trailers".to_vec()),
        ];
        assert!(normalize_http3_request(&ok, Transport::Tls13).is_ok());
        // chunked / 其他值 → 拒绝(走私阻断)
        for bad in ["chunked", "identity", "trailers, chunked"] {
            let bytes = vec![
                (b":method".to_vec(), b"GET".to_vec()),
                (b":path".to_vec(), b"/".to_vec()),
                (b":scheme".to_vec(), b"https".to_vec()),
                (b":authority".to_vec(), b"a.com".to_vec()),
                (b"te".to_vec(), bad.as_bytes().to_vec()),
            ];
            let err = normalize_http3_request(&bytes, Transport::Tls13).unwrap_err();
            assert!(
                matches!(err, ProtocolNormalizeError::ProtocolViolation(ref m) if m.contains("te header")),
                "te={bad} not rejected: {err}"
            );
        }
    }

    /// H2 层同内核(与 H3 共享 normalize_h23_request_core):
    /// 重复 :authority 也经 H2 层入口 fail-closed。
    #[test]
    fn h2_duplicate_authority_rejected() {
        use zenith_http2::hpack::HeaderField;
        let fields = vec![
            HeaderField::new(":method", "GET"),
            HeaderField::new(":path", "/"),
            HeaderField::new(":scheme", "https"),
            HeaderField::new(":authority", "a.com"),
            HeaderField::new(":authority", "b.com"),
        ];
        let err = normalize_http2_request(&fields, Transport::Tls13).unwrap_err();
        assert!(matches!(
            err,
            ProtocolNormalizeError::ProtocolViolation(ref m) if m.contains("duplicate pseudo-header")
        ));
    }
}