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
//! 中间件系统
//!
//! 优化策略:常用中间件直接内联,零动态分派

use std::sync::atomic::{AtomicU64, Ordering};

use zenith_api::{CanonicalRequest, CanonicalResponse};

use crate::extract::ExtractError;

/// 中间件执行上下文
///
/// 在中间件链中传递请求状态,支持短路响应。
#[derive(Debug, Clone)]
pub struct MiddlewareContext {
    /// 当前请求
    pub request: CanonicalRequest,
    /// 是否已被中间件短路
    pub short_circuit: bool,
    /// 短路响应(若已短路)
    pub short_circuit_response: Option<CanonicalResponse>,
}

impl MiddlewareContext {
    /// 创建新的中间件上下文
    pub fn new(request: CanonicalRequest) -> Self {
        Self {
            request,
            short_circuit: false,
            short_circuit_response: None,
        }
    }

    /// 设置短路响应,终止后续中间件链执行
    pub fn short_circuit(&mut self, response: CanonicalResponse) {
        self.short_circuit = true;
        self.short_circuit_response = Some(response);
    }

    /// 检查是否已被短路
    pub fn is_short_circuited(&self) -> bool {
        self.short_circuit
    }
}

/// 中间件特征(用于扩展)
///
/// 自定义中间件实现此 trait,通过 `before` 和 `after` 方法
/// 在请求处理前后执行逻辑。
pub trait Middleware: Send + Sync + std::any::Any + 'static {
    /// 中间件名称(用于调试和日志)
    fn name(&self) -> &'static str {
        "unnamed"
    }

    /// 请求前置处理
    ///
    /// 返回 `Ok(())` 继续处理,返回 `Err(response)` 短路请求。
    fn before(&self, ctx: &mut MiddlewareContext) -> Result<(), Box<CanonicalResponse>>;

    /// 响应后置处理
    ///
    /// 在处理器执行完成后调用,可修改响应。
    fn after(
        &self,
        request: &CanonicalRequest,
        response: CanonicalResponse,
    ) -> CanonicalResponse;
}

/// 中间件链(优化版本:内联常用中间件)
pub struct MiddlewareChain {
    // 内联中间件配置(零动态分派)
    logging_enabled: bool,
    cors_enabled: bool,
    cors_allow_origin: [u8; 128],
    cors_allow_origin_len: usize,
    cors_allow_methods: [u8; 128],
    cors_allow_methods_len: usize,
    cors_allow_headers: [u8; 128],
    cors_allow_headers_len: usize,
    cors_max_age: [u8; 16],
    cors_max_age_len: usize,
    request_id_enabled: bool,
    auth_enabled: bool,
    auth_header: [u8; 64],
    auth_header_len: usize,
    /// 认证期望值(内联定长,零堆分配;长度 0 表示不校验值)
    auth_expected_value: [u8; 128],
    /// 认证期望值实际长度
    auth_expected_value_len: usize,
    /// 是否要求认证值非空(默认 true)
    auth_require_non_empty: bool,
    // 扩展中间件(动态分派,仅用于自定义中间件)
    ext_middlewares: Vec<Box<dyn Middleware>>,
}

impl std::fmt::Debug for MiddlewareChain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MiddlewareChain")
            .field("logging", &self.logging_enabled)
            .field("cors", &self.cors_enabled)
            .field("request_id", &self.request_id_enabled)
            .field("auth", &self.auth_enabled)
            .field("ext_count", &self.ext_middlewares.len())
            .finish()
    }
}

impl MiddlewareChain {
    /// 创建新的中间件链
    pub fn new() -> Self {
        Self {
            logging_enabled: false,
            cors_enabled: false,
            cors_allow_origin: [0u8; 128],
            cors_allow_origin_len: 0,
            cors_allow_methods: [0u8; 128],
            cors_allow_methods_len: 0,
            cors_allow_headers: [0u8; 128],
            cors_allow_headers_len: 0,
            cors_max_age: [0u8; 16],
            cors_max_age_len: 0,
            request_id_enabled: false,
            auth_enabled: false,
            auth_header: [0u8; 64],
            auth_header_len: 0,
            auth_expected_value: [0u8; 128],
            auth_expected_value_len: 0,
            auth_require_non_empty: true,
            ext_middlewares: Vec::new(),
        }
    }

    /// 添加中间件(优化:直接处理内置中间件类型,零动态分派)
    pub fn add<M: Middleware>(&mut self, middleware: M) -> &mut Self {
        // 编译期类型匹配(通过宏实现)
        self.add_middleware_macro(middleware)
    }

    /// 内部实现:类型分发(编译期优化)
    #[inline]
    fn add_middleware_macro<M: Middleware>(&mut self, mut middleware: M) -> &mut Self {
        // 编译期类型匹配:TypeId 在编译期已知,分支会被优化掉
        if let Some(m) = (&mut middleware as &mut dyn std::any::Any).downcast_mut::<LoggingMiddleware>() {
            self.logging_enabled = m.enabled;
            return self;
        }
        if let Some(m) = (&mut middleware as &mut dyn std::any::Any).downcast_mut::<CorsMiddleware>() {
            self.cors_enabled = true;
            let origin_bytes = m.allow_origin.as_bytes();
            // 构造期校验:origin 超过 128 字节缓冲区将静默截断,
            // 发出截断的 CORS 头构成安全风险,构造期直接拒绝
            assert!(
                origin_bytes.len() <= 128,
                "CORS allow_origin exceeds 128-byte buffer ({} bytes); would be silently truncated",
                origin_bytes.len()
            );
            self.cors_allow_origin_len = origin_bytes.len().min(128);
            self.cors_allow_origin[..self.cors_allow_origin_len].copy_from_slice(&origin_bytes[..self.cors_allow_origin_len]);
            let methods_bytes = m.allow_methods_str.as_bytes();
            assert!(methods_bytes.len() <= 128, "CORS allow_methods exceeds 128 bytes");
            self.cors_allow_methods_len = methods_bytes.len();
            self.cors_allow_methods[..self.cors_allow_methods_len].copy_from_slice(&methods_bytes[..self.cors_allow_methods_len]);
            let headers_bytes = m.allow_headers_str.as_bytes();
            assert!(headers_bytes.len() <= 128, "CORS allow_headers exceeds 128 bytes");
            self.cors_allow_headers_len = headers_bytes.len();
            self.cors_allow_headers[..self.cors_allow_headers_len].copy_from_slice(&headers_bytes[..self.cors_allow_headers_len]);
            let max_age_bytes = m.max_age_str.as_bytes();
            assert!(max_age_bytes.len() <= 16, "CORS max_age exceeds 16 bytes");
            self.cors_max_age_len = max_age_bytes.len();
            self.cors_max_age[..self.cors_max_age_len].copy_from_slice(&max_age_bytes[..self.cors_max_age_len]);
            return self;
        }
        if std::any::TypeId::of::<M>() == std::any::TypeId::of::<RequestIdMiddleware>() {
            self.request_id_enabled = true;
            return self;
        }
        if let Some(m) = (&mut middleware as &mut dyn std::any::Any).downcast_mut::<AuthMiddleware>() {
            self.auth_enabled = true;
            let header_bytes = m.header_name.as_bytes();
            self.auth_header_len = header_bytes.len().min(64);
            self.auth_header[..self.auth_header_len].copy_from_slice(&header_bytes[..self.auth_header_len]);
            self.auth_require_non_empty = m.require_non_empty;
            if let Some(ref ev) = m.expected_value {
                let ev_bytes = ev.as_bytes();
                self.auth_expected_value_len = ev_bytes.len().min(128);
                self.auth_expected_value[..self.auth_expected_value_len]
                    .copy_from_slice(&ev_bytes[..self.auth_expected_value_len]);
            } else {
                self.auth_expected_value_len = 0;
            }
            return self;
        }
        // 自定义中间件,添加到扩展列表
        self.ext_middlewares.push(Box::new(middleware));
        self
    }

    /// 获取中间件数量
    pub fn len(&self) -> usize {
        let mut count = 0;
        if self.logging_enabled { count += 1; }
        if self.cors_enabled { count += 1; }
        if self.request_id_enabled { count += 1; }
        if self.auth_enabled { count += 1; }
        count + self.ext_middlewares.len()
    }

    /// 检查中间件链是否为空
    pub fn is_empty(&self) -> bool {
        !self.logging_enabled && !self.cors_enabled && !self.request_id_enabled && 
        !self.auth_enabled && self.ext_middlewares.is_empty()
    }

    /// 执行前置中间件链
    ///
    /// 先执行内联中间件(CORS、认证),再执行扩展中间件。
    /// 若中间件短路,返回 `Err(CanonicalResponse)`。
    pub fn run_before(
        &self,
        request: CanonicalRequest,
    ) -> Result<CanonicalRequest, Box<CanonicalResponse>> {
        let mut ctx = MiddlewareContext::new(request);

        self.run_inline_before(&mut ctx);
        if ctx.is_short_circuited() {
            let response = match ctx.short_circuit_response {
                Some(resp) => resp,
                None => crate::error::MiddlewareError::Internal(
                    "middleware short-circuited without response".to_string()
                ).into(),
            };
            return Err(Box::new(response));
        }

        for middleware in &self.ext_middlewares {
            middleware.before(&mut ctx)?;
            if ctx.is_short_circuited() {
                let response = match ctx.short_circuit_response {
                    Some(resp) => resp,
                    None => crate::error::MiddlewareError::Internal(
                        "middleware short-circuited without response".to_string()
                    ).into(),
                };
                return Err(Box::new(response));
            }
        }

        Ok(ctx.request)
    }

    /// 内联前置处理(零动态分派)
    ///
    /// 处理 CORS OPTIONS 预检请求和认证检查。
    /// 通过修改 `ctx` 的副作用实现短路,返回值为 `()`。
    #[inline(always)]
    fn run_inline_before(&self, ctx: &mut MiddlewareContext) {
        // CORS OPTIONS 预检(最高优先级)
        if self.cors_enabled && matches!(ctx.request.method, zenith_api::Method::Options) {
            let mut response = CanonicalResponse::new(204);
            // allow_origin 为空表示 CORS 未配置,不发送 Allow-Origin 头
            if self.cors_allow_origin_len > 0 {
                let _ = response.add_header(
                    b"access-control-allow-origin",
                    &self.cors_allow_origin[..self.cors_allow_origin_len],
                );
            }
            let _ = response.add_header(
                b"access-control-allow-methods",
                &self.cors_allow_methods[..self.cors_allow_methods_len],
            );
            let _ = response.add_header(
                b"access-control-allow-headers",
                &self.cors_allow_headers[..self.cors_allow_headers_len],
            );
            let _ = response.add_header(
                b"access-control-max-age",
                &self.cors_max_age[..self.cors_max_age_len],
            );
            ctx.short_circuit(response);
            return;
        }

        // 认证中间件
        if self.auth_enabled {
            let auth_header_name = core::str::from_utf8(&self.auth_header[..self.auth_header_len]).unwrap_or("");
            // 修复认证绕过:原实现仅检查头部存在性(is_some()),
            // 任意值(含空值/垃圾值)均可通过。现在校验:
            //   1. 头部必须存在
            //   2. require_non_empty 时值不能为空
            //   3. 配置了期望值时使用恒定时间比较(防时序侧信道)
            let reject = match ctx.request.find_header(auth_header_name) {
                None => true, // 头部缺失 → 401
                Some(hdr) => {
                    let value = hdr.value_str();
                    if self.auth_require_non_empty && value.is_empty() {
                        true // 空值 → 401
                    } else if self.auth_expected_value_len > 0 {
                        // 配置了期望值:恒定时间比较,防时序侧信道
                        let expected = core::str::from_utf8(
                            &self.auth_expected_value[..self.auth_expected_value_len],
                        ).unwrap_or("");
                        !zenith_foundation::constant_time_eq(value.as_bytes(), expected.as_bytes())
                    } else {
                        false // 仅校验存在性 + 非空(已通过)
                    }
                }
            };

            if reject {
                let mut response = CanonicalResponse::new(401);
                let _ = response.add_header(b"content-type", b"text/plain");
                response.set_body(b"Unauthorized".to_vec());
                ctx.short_circuit(response);
            }
        }
    }

    /// 执行后置中间件链
    ///
    /// 先逆序执行扩展中间件,再执行内联后置处理。
    pub fn run_after(&self, request: &CanonicalRequest, mut response: CanonicalResponse) -> CanonicalResponse {
        for middleware in self.ext_middlewares.iter().rev() {
            response = middleware.after(request, response);
        }

        response = self.run_inline_after(request, response);

        response
    }

    #[inline(always)]
    fn run_inline_after(&self, request: &CanonicalRequest, mut response: CanonicalResponse) -> CanonicalResponse {
        // RequestId 中间件
        if self.request_id_enabled {
            let counter = REQUEST_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
            let mut buf = [0u8; 32];
            let id = format_request_id(counter, &mut buf);
            let _ = response.add_header(b"x-request-id", id);
        }

        // CORS 中间件
        // allow_origin 为空表示 CORS 未配置,不发送 Allow-Origin 头
        if self.cors_enabled
            && self.cors_allow_origin_len > 0
            && response.find_header("access-control-allow-origin").is_none()
        {
            let _ = response.add_header(
                b"access-control-allow-origin",
                &self.cors_allow_origin[..self.cors_allow_origin_len],
            );
        }

        // Logging 中间件
        if self.logging_enabled {
            tracing::info!(
                method = %request.method.as_str(),
                path = %request.path_str(),
                status = response.status_code,
                "[Zenith] request completed"
            );
        }

        response
    }

    /// 执行完整的中间件处理流程
    ///
    /// 依次执行:内联前置 → 扩展前置 → 处理器 → 扩展后置 → 内联后置
    pub fn run<F>(&self, request: CanonicalRequest, handler: F) -> CanonicalResponse
    where
        F: FnOnce(&CanonicalRequest) -> CanonicalResponse,
    {
        let mut ctx = MiddlewareContext::new(request);

        // 内联前置处理(零动态分派)
        self.run_inline_before(&mut ctx);
        if ctx.is_short_circuited() {
            let response = match ctx.short_circuit_response {
                Some(resp) => resp,
                None => crate::error::MiddlewareError::Internal(
                    "middleware short-circuited without response".to_string()
                ).into(),
            };
            return self.run_inline_after(&ctx.request, response);
        }

        // 扩展中间件前置处理(动态分派)
        for middleware in &self.ext_middlewares {
            if let Err(response) = middleware.before(&mut ctx) {
                return self.run_after(&ctx.request, *response);
            }
            if ctx.is_short_circuited() {
                let response = match ctx.short_circuit_response {
                    Some(resp) => resp,
                    None => crate::error::MiddlewareError::Internal(
                        "middleware short-circuited without response".to_string()
                    ).into(),
                };
                return self.run_after(&ctx.request, response);
            }
        }

        // 执行处理器
        let response = handler(&ctx.request);

        // 后置处理
        self.run_after(&ctx.request, response)
    }
}

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

/// 请求 ID 计数器
static REQUEST_ID_COUNTER: AtomicU64 = AtomicU64::new(0);

/// 格式化请求 ID
#[inline(always)]
fn format_request_id(counter: u64, buf: &mut [u8; 32]) -> &[u8] {
    const PREFIX: &[u8] = b"zenith-";
    let mut pos = PREFIX.len();
    
    buf[..pos].copy_from_slice(PREFIX);
    
    let mut num = counter;
    let num_start = pos;
    
    if num == 0 {
        buf[pos] = b'0';
        pos += 1;
    } else {
        while num > 0 {
            buf[pos] = b'0' + (num % 10) as u8;
            num /= 10;
            pos += 1;
        }
        buf[num_start..pos].reverse();
    }
    
    &buf[..pos]
}

// ---------------------------------------------------------------------------
// 内置中间件
// ---------------------------------------------------------------------------

/// 日志中间件
///
/// 在响应完成后输出请求方法、路径和状态码到 stderr。
#[derive(Debug, Default)]
pub struct LoggingMiddleware {
    /// 是否启用日志输出
    pub enabled: bool,
}

impl LoggingMiddleware {
    /// 创建日志中间件
    pub fn new(enabled: bool) -> Self {
        Self { enabled }
    }
}

impl Middleware for LoggingMiddleware {
    fn name(&self) -> &'static str {
        "LoggingMiddleware"
    }

    fn before(&self, _ctx: &mut MiddlewareContext) -> Result<(), Box<CanonicalResponse>> {
        Ok(())
    }

    fn after(&self, _request: &CanonicalRequest, response: CanonicalResponse) -> CanonicalResponse {
        response
    }
}

/// CORS 中间件
///
/// 处理跨域请求,包括 OPTIONS 预检请求和响应头设置。
#[derive(Debug, Clone)]
pub struct CorsMiddleware {
    /// 允许的源
    pub allow_origin: String,
    /// 允许的 HTTP 方法
    pub allow_methods_str: String,
    /// 允许的请求头
    pub allow_headers_str: String,
    /// 预检请求缓存时间(秒)
    pub max_age_str: String,
}

impl CorsMiddleware {
    /// 创建 CORS 中间件(默认禁用 CORS:`allow_origin` 为空,不发送 CORS 头)
    ///
    /// 安全默认:不主动放行任意源,避免默认开放跨域。需显式调用
    /// `with_origin(...)` 配置允许的源(如 `"*"` 或具体白名单域名)。
    pub fn new() -> Self {
        Self {
            allow_origin: String::new(),
            allow_methods_str: "GET,POST,PUT,DELETE,PATCH,OPTIONS".to_string(),
            allow_headers_str: "Content-Type,Authorization,X-Requested-With".to_string(),
            max_age_str: "3600".to_string(),
        }
    }

    /// 设置允许的源
    pub fn with_origin(mut self, origin: &str) -> Self {
        self.allow_origin = origin.to_string();
        self
    }

    /// 设置允许的 HTTP 方法
    pub fn with_methods(mut self, methods: Vec<String>) -> Self {
        self.allow_methods_str = methods.join(",");
        self
    }

    /// 设置允许的请求头
    pub fn with_headers(mut self, headers: Vec<String>) -> Self {
        self.allow_headers_str = headers.join(",");
        self
    }

    /// 设置预检请求缓存时间
    pub fn with_max_age(mut self, max_age: u32) -> Self {
        self.max_age_str = max_age.to_string();
        self
    }
}

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

impl Middleware for CorsMiddleware {
    fn name(&self) -> &'static str {
        "CorsMiddleware"
    }

    fn before(&self, _ctx: &mut MiddlewareContext) -> Result<(), Box<CanonicalResponse>> {
        Ok(())
    }

    fn after(&self, _request: &CanonicalRequest, response: CanonicalResponse) -> CanonicalResponse {
        response
    }
}

/// 请求 ID 中间件
///
/// 为每个请求生成唯一 ID (x-request-id),用于日志追踪。
#[derive(Debug, Default)]
pub struct RequestIdMiddleware;

impl RequestIdMiddleware {
    /// 创建请求 ID 中间件
    pub fn new() -> Self {
        Self
    }
}

impl Middleware for RequestIdMiddleware {
    fn name(&self) -> &'static str {
        "RequestIdMiddleware"
    }

    fn before(&self, _ctx: &mut MiddlewareContext) -> Result<(), Box<CanonicalResponse>> {
        Ok(())
    }

    fn after(&self, _request: &CanonicalRequest, response: CanonicalResponse) -> CanonicalResponse {
        response
    }
}

/// 认证中间件(凭据值校验)
///
/// 检查请求头中是否存在指定的认证头,并校验凭据值:
/// - 默认要求非空值(`require_non_empty = true`)
/// - 配置了 `expected_value` 时使用恒定时间比较验证凭据值
///
/// 安全设计:
/// - 恒定时间比较防时序侧信道
/// - 空值/垃圾值/不匹配值均被拒绝(401 Unauthorized)
#[derive(Debug, Clone)]
pub struct AuthMiddleware {
    /// 认证头名称
    pub header_name: String,
    /// 认证期望值(可选;配置后使用恒定时间比较验证)
    pub expected_value: Option<String>,
    /// 是否要求认证值非空(默认 true)
    pub require_non_empty: bool,
}

impl AuthMiddleware {
    /// 创建认证中间件(默认要求非空值,不校验具体值)
    pub fn new(header_name: &str) -> Self {
        Self {
            header_name: header_name.to_string(),
            expected_value: None,
            require_non_empty: true,
        }
    }

    /// 设置期望的认证值(启用恒定时间比较校验)
    pub fn with_expected_value(mut self, value: &str) -> Self {
        self.expected_value = Some(value.to_string());
        self
    }
}

impl Default for AuthMiddleware {
    fn default() -> Self {
        Self::new("Authorization")
    }
}

impl Middleware for AuthMiddleware {
    fn name(&self) -> &'static str {
        "AuthMiddleware"
    }

    fn before(&self, _ctx: &mut MiddlewareContext) -> Result<(), Box<CanonicalResponse>> {
        Ok(())
    }

    fn after(&self, _request: &CanonicalRequest, response: CanonicalResponse) -> CanonicalResponse {
        response
    }
}

// ---------------------------------------------------------------------------
// 身份一致性中间件(AGENT.md §4.5)
// ---------------------------------------------------------------------------

/// 身份一致性中间件
///
/// 验证 HTTP 请求的 authority/host 头与配置的虚拟主机一致,
/// 防止请求走私(Request Smuggling)与虚拟主机欺骗攻击。
///
/// # 安全
/// - 使用恒定时间比较(恒定字节 XOR 累加)防止时序侧信道
/// - 仅比较非秘密数据(域名、主机名)
/// - 不匹配直接返回 421(Misdirected Request)或 403
#[derive(Debug, Clone)]
pub struct IdentityMiddleware {
    /// 允许的虚拟主机列表(小写,定长数组零堆分配)
    allowed_hosts: Vec<String>,
    /// 严格模式:要求 host 头必须存在
    strict: bool,
}

impl IdentityMiddleware {
    /// 创建新的身份一致性中间件
    ///
    /// # Arguments
    /// * `allowed_hosts` - 允许的虚拟主机列表(小写)
    pub fn new(allowed_hosts: Vec<String>) -> Self {
        Self {
            allowed_hosts,
            strict: true,
        }
    }

    /// 设置严格模式(默认 true)
    pub fn with_strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// 从请求中提取 host/authority 值(小写规范化,支持 IPv6 方括号字面量)
    ///
    /// 统一委托 `zenith_api::normalize::split_host_port`(单一实现源),
    /// 修复前手写 `split(':').next()` 会把 `[::1]:8080` 截成 `"["`,
    /// 裸 IPv6 也会切错端口边界。
    fn extract_host(&self, request: &CanonicalRequest) -> Option<String> {
        let authority = request.authority_str();
        if !authority.is_empty() {
            let (host_part, _port) = zenith_api::normalize::split_host_port(authority);
            let lower =
                zenith_api::normalize::unbracket_ipv6(host_part).to_ascii_lowercase();
            if !lower.is_empty() {
                return Some(lower);
            }
        }

        if let Some(host_header) = request.find_header("host") {
            let value = host_header.value_str();
            let (host_part, _port) = zenith_api::normalize::split_host_port(value);
            let lower =
                zenith_api::normalize::unbracket_ipv6(host_part).to_ascii_lowercase();
            if !lower.is_empty() {
                return Some(lower);
            }
        }

        None
    }

    /// 验证请求主机是否在允许列表中
    ///
    /// `pub(crate)`:供 `ProtocolServer` 默认管线装配复用(AGENT §4.5),
    /// 保证中间件路径与默认管线路径同一验证逻辑。
    pub(crate) fn verify(&self, request: &CanonicalRequest) -> Result<(), &'static str> {
        let host = self.extract_host(request);

        match (host, self.strict) {
            (None, true) => Err("identity: host header missing (strict mode)"),
            (None, false) => Ok(()),
            (Some(ref h), _) => {
                for allowed in &self.allowed_hosts {
                    // 复用 core 中经过 `#[inline(never)]` 加固的恒定时间实现
                    if zenith_foundation::constant_time_eq(h.as_bytes(), allowed.as_bytes()) {
                        return Ok(());
                    }
                }
                Err("identity: host not in allowed list")
            }
        }
    }
}

impl Default for IdentityMiddleware {
    fn default() -> Self {
        Self::new(Vec::new())
    }
}

impl Middleware for IdentityMiddleware {
    fn name(&self) -> &'static str {
        "IdentityMiddleware"
    }

    fn before(&self, ctx: &mut MiddlewareContext) -> Result<(), Box<CanonicalResponse>> {
        if self.allowed_hosts.is_empty() {
            return Ok(());
        }

        if let Err(reason) = self.verify(&ctx.request) {
            let mut response = CanonicalResponse::new(421);
            let _ = response.add_header(b"content-type", b"text/plain");
            response.set_body(reason.as_bytes().to_vec());
            ctx.short_circuit(response);
        }
        Ok(())
    }

    fn after(
        &self,
        _request: &CanonicalRequest,
        response: CanonicalResponse,
    ) -> CanonicalResponse {
        response
    }
}

// ---------------------------------------------------------------------------
// 结果类型
// ---------------------------------------------------------------------------

/// 中间件操作结果类型
pub type MiddlewareResult<T> = Result<T, ExtractError>;

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

    #[test]
    fn test_middleware_chain_empty() {
        let chain = MiddlewareChain::new();
        let request = CanonicalRequest::empty();

        let response = chain.run(request, |_| CanonicalResponse::new(200));
        assert_eq!(response.status_code, 200);
    }

    #[test]
    fn test_logging_middleware() {
        let mut chain = MiddlewareChain::new();
        chain.add(LoggingMiddleware::new(false));

        let request = CanonicalRequest::empty();
        let response = chain.run(request, |_| CanonicalResponse::new(200));
        assert_eq!(response.status_code, 200);
    }

    #[test]
    fn test_cors_middleware_preflight() {
        let mut chain = MiddlewareChain::new();
        chain.add(CorsMiddleware::new().with_origin("*"));

        let mut request = CanonicalRequest::empty();
        request.method = zenith_api::Method::Options;

        let response = chain.run(request, |_| CanonicalResponse::new(200));
        assert_eq!(response.status_code, 204);
        assert!(response.find_header("access-control-allow-origin").is_some());
    }

    /// 回归(曾 `split(':').next()` 截断为 `"["`):
    /// `extract_host` 必须正确处理 IPv6 方括号 `host[:port]` 与裸主机。
    /// 委托 zenith-api `split_host_port` + `unbracket_ipv6` 单一实现源。
    #[test]
    fn identity_extract_host_ipv6_and_port_variants() {
        let mw = IdentityMiddleware::new(vec!["::1".into(), "example.com".into()]);

        // IPv6 带括号带端口 → 提取裸地址(与 SNI 侧同形)
        let mut req = CanonicalRequest::empty();
        req.method = zenith_api::Method::Get;
        assert!(req.set_path("/"));
        assert!(req.set_authority("[::1]:8080"));
        assert_eq!(mw.extract_host(&req), Some("::1".to_string()));
        assert!(mw.verify(&req).is_ok(), "bracketed ipv6 ::1 must be in whitelist");

        // IPv6 括号不带端口 → 同样裸地址
        let mut req_b = CanonicalRequest::empty();
        req_b.method = zenith_api::Method::Get;
        assert!(req_b.set_path("/"));
        assert!(req_b.set_authority("[::1]"));
        assert_eq!(mw.extract_host(&req_b), Some("::1".to_string()));
        assert!(mw.verify(&req_b).is_ok());

        // 裸域名带端口 → 剥端口
        let mut req_c = CanonicalRequest::empty();
        req_c.method = zenith_api::Method::Get;
        assert!(req_c.set_path("/"));
        assert!(req_c.set_authority("example.com:8443"));
        assert_eq!(mw.extract_host(&req_c), Some("example.com".to_string()));
        assert!(mw.verify(&req_c).is_ok());

        // authority 空 → host 头兜底;IPv6 host 头同样剥括号剥端口
        let mut req_d = CanonicalRequest::empty();
        req_d.method = zenith_api::Method::Get;
        assert!(req_d.set_path("/"));
        assert!(req_d.add_header(b"host", b"[::1]:9000").is_ok());
        assert_eq!(mw.extract_host(&req_d), Some("::1".to_string()));
        assert!(mw.verify(&req_d).is_ok());

        // 白名单外主机 fail-closed 拒绝
        let mut req_e = CanonicalRequest::empty();
        req_e.method = zenith_api::Method::Get;
        assert!(req_e.set_path("/"));
        assert!(req_e.set_authority("evil.com"));
        assert!(mw.verify(&req_e).is_err());

        // 严格模式(默认)host 缺失 → Err
        let empty = CanonicalRequest::empty();
        assert!(mw.verify(&empty).is_err());
    }

    #[test]
    fn test_cors_middleware_normal() {
        let mut chain = MiddlewareChain::new();
        chain.add(CorsMiddleware::new().with_origin("*"));

        let request = CanonicalRequest::empty();
        let response = chain.run(request, |_| CanonicalResponse::new(200));
        assert_eq!(response.status_code, 200);
        assert!(response.find_header("access-control-allow-origin").is_some());
    }

    #[test]
    fn test_request_id_middleware() {
        let mut chain = MiddlewareChain::new();
        chain.add(RequestIdMiddleware::new());

        let request = CanonicalRequest::empty();
        let response = chain.run(request, |_| CanonicalResponse::new(200));
        assert!(response.find_header("x-request-id").is_some());
    }

    #[test]
    fn test_auth_middleware_no_auth() {
        let mut chain = MiddlewareChain::new();
        chain.add(AuthMiddleware::new("X-Auth"));

        let request = CanonicalRequest::empty();
        let response = chain.run(request, |_| CanonicalResponse::new(200));
        assert_eq!(response.status_code, 401);
    }

    #[test]
    fn test_auth_middleware_with_auth() {
        let mut chain = MiddlewareChain::new();
        chain.add(AuthMiddleware::new("X-Auth"));

        let mut request = CanonicalRequest::empty();
        request.add_header(b"X-Auth", b"token").unwrap();

        let response = chain.run(request, |_| CanonicalResponse::new(200));
        assert_eq!(response.status_code, 200);
    }

    #[test]
    fn test_multiple_middlewares() {
        let mut chain = MiddlewareChain::new();
        chain.add(LoggingMiddleware::new(false));
        chain.add(CorsMiddleware::new().with_origin("*"));
        chain.add(RequestIdMiddleware::new());

        let request = CanonicalRequest::empty();
        let response = chain.run(request, |_| {
            let mut resp = CanonicalResponse::new(200);
            resp.set_body(b"OK".to_vec());
            resp
        });

        assert_eq!(response.status_code, 200);
        assert!(response.find_header("access-control-allow-origin").is_some());
        assert!(response.find_header("x-request-id").is_some());
    }

    #[test]
    fn test_middleware_context_short_circuit() {
        let mut ctx = MiddlewareContext::new(CanonicalRequest::empty());
        assert!(!ctx.is_short_circuited());

        ctx.short_circuit(CanonicalResponse::new(403));
        assert!(ctx.is_short_circuited());
        assert_eq!(ctx.short_circuit_response.as_ref().unwrap().status_code, 403);
    }
}