ultimo 0.9.1

Modern Rust web framework with automatic TypeScript client generation
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
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
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
//! Middleware system with composable chain execution
//!
//! Middleware can execute before and after handlers, modify context,
//! and short-circuit request handling.

use crate::{
    context::Context,
    error::Result,
    response::{Response, UltimoBody},
};
use hyper::Response as HyperResponse;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

/// Type alias for the next() function in middleware
pub type Next<'a> = Box<
    dyn FnOnce(Context) -> Pin<Box<dyn Future<Output = Result<Response>> + Send + 'a>> + Send + 'a,
>;

/// Type alias for boxed middleware functions
pub type BoxedMiddleware = Arc<
    dyn for<'a> Fn(Context, Next<'a>) -> Pin<Box<dyn Future<Output = Result<Response>> + Send + 'a>>
        + Send
        + Sync,
>;

/// Trait for types that can be converted into middleware
pub trait IntoMiddleware {
    fn into_middleware(self) -> BoxedMiddleware;
}

/// Implement IntoMiddleware for async functions
impl<F> IntoMiddleware for F
where
    F: for<'a> Fn(Context, Next<'a>) -> Pin<Box<dyn Future<Output = Result<Response>> + Send + 'a>>
        + Send
        + Sync
        + 'static,
{
    fn into_middleware(self) -> BoxedMiddleware {
        Arc::new(self)
    }
}

/// Middleware chain executor
pub struct MiddlewareChain {
    middleware: Vec<BoxedMiddleware>,
}

impl MiddlewareChain {
    /// Create a new empty middleware chain
    pub fn new() -> Self {
        Self {
            middleware: Vec::new(),
        }
    }

    /// Add middleware to the chain
    pub fn push(&mut self, middleware: BoxedMiddleware) {
        self.middleware.push(middleware);
    }

    /// Execute the middleware chain with a final handler
    pub async fn execute<F, Fut>(self, ctx: Context, handler: F) -> Result<Response>
    where
        F: FnOnce(Context) -> Fut + Send + 'static,
        Fut: Future<Output = Result<Response>> + Send + 'static,
    {
        self.execute_at(ctx, 0, Box::new(handler)).await
    }

    /// Execute starting at a specific middleware index
    fn execute_at<F, Fut>(
        self,
        ctx: Context,
        index: usize,
        handler: Box<F>,
    ) -> Pin<Box<dyn Future<Output = Result<Response>> + Send>>
    where
        F: FnOnce(Context) -> Fut + Send + 'static,
        Fut: Future<Output = Result<Response>> + Send + 'static,
    {
        Box::pin(async move {
            if index >= self.middleware.len() {
                // No more middleware, call final handler
                return handler(ctx).await;
            }

            let current_middleware = self.middleware[index].clone();
            let next_index = index + 1;

            // Create next() closure that captures remaining chain
            let next: Next = Box::new(move |ctx| self.execute_at(ctx, next_index, handler));

            current_middleware(ctx, next).await
        })
    }
}

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

/// Built-in middleware constructors
pub mod builtin {
    use super::*;
    use std::time::Instant;
    use tracing::{error, info};

    /// Logger middleware that logs request/response details
    pub fn logger() -> BoxedMiddleware {
        Arc::new(|ctx, next| {
            Box::pin(async move {
                let method = ctx.req.method().clone();
                let path = ctx.req.path().to_string();
                let start = Instant::now();

                info!("--> {} {}", method, path);

                let result = next(ctx).await;

                let duration = start.elapsed();
                match &result {
                    Ok(response) => {
                        info!(
                            "<-- {} {} {} ({:?})",
                            method,
                            path,
                            response.status().as_u16(),
                            duration
                        );
                    }
                    Err(err) => {
                        error!("<-- {} {} ERROR: {} ({:?})", method, path, err, duration);
                    }
                }

                result
            })
        })
    }

    /// CORS middleware with configurable options
    pub struct Cors {
        allow_origin: String,
        allow_methods: Vec<String>,
        allow_headers: Vec<String>,
    }

    impl Cors {
        pub fn new() -> Self {
            Self {
                allow_origin: "*".to_string(),
                allow_methods: vec!["GET".to_string(), "POST".to_string()],
                allow_headers: vec!["Content-Type".to_string()],
            }
        }

        pub fn allow_origin(mut self, origin: impl Into<String>) -> Self {
            self.allow_origin = origin.into();
            self
        }

        pub fn allow_methods(mut self, methods: Vec<impl Into<String>>) -> Self {
            self.allow_methods = methods.into_iter().map(|m| m.into()).collect();
            self
        }

        pub fn allow_headers(mut self, headers: Vec<impl Into<String>>) -> Self {
            self.allow_headers = headers.into_iter().map(|h| h.into()).collect();
            self
        }

        pub fn build(self) -> BoxedMiddleware {
            let origin = self.allow_origin;
            let methods = self.allow_methods.join(", ");
            let headers = self.allow_headers.join(", ");

            Arc::new(move |ctx, next| {
                let origin = origin.clone();
                let methods = methods.clone();
                let headers = headers.clone();

                Box::pin(async move {
                    // Handle preflight OPTIONS requests
                    if ctx.req.method() == "OPTIONS" {
                        let response = HyperResponse::builder()
                            .status(204)
                            .header("Access-Control-Allow-Origin", origin)
                            .header("Access-Control-Allow-Methods", methods)
                            .header("Access-Control-Allow-Headers", headers)
                            .body(UltimoBody::empty())
                            .unwrap();
                        return Ok(response);
                    }

                    // Set CORS headers on context before calling next
                    ctx.header("Access-Control-Allow-Origin", origin).await;
                    ctx.header("Access-Control-Allow-Methods", methods).await;
                    ctx.header("Access-Control-Allow-Headers", headers).await;

                    // Call next with the modified context
                    next(ctx).await
                })
            })
        }
    }

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

    /// Convenience function to create CORS middleware
    pub fn cors() -> BoxedMiddleware {
        Cors::new().build()
    }

    /// Powered-by header middleware that adds framework identification
    ///
    /// Adds `X-Powered-By: Ultimo` header to all responses.
    /// Similar to Express.js's X-Powered-By header.
    ///
    /// # Security Note
    /// Some security guides recommend disabling this header in production
    /// as it reveals your framework version to potential attackers.
    ///
    /// # Example
    /// ```rust,no_run
    /// use ultimo::prelude::*;
    ///
    /// let mut app = Ultimo::new();
    /// app.use_middleware(ultimo::middleware::builtin::powered_by());
    /// ```
    pub fn powered_by() -> BoxedMiddleware {
        Arc::new(|ctx, next| {
            Box::pin(async move {
                ctx.header("X-Powered-By", "Ultimo").await;
                next(ctx).await
            })
        })
    }

    /// Server identification middleware with configurable name
    ///
    /// Adds custom server identification headers to all responses.
    ///
    /// # Arguments
    /// * `name` - Server name (default: "Ultimo")
    /// * `version` - Include version in X-Powered-By header (default: false)
    ///
    /// # Example
    /// ```rust,no_run
    /// use ultimo::prelude::*;
    ///
    /// let mut app = Ultimo::new();
    /// // Add simple identification
    /// app.use_middleware(ultimo::middleware::builtin::server_headers("Ultimo", false));
    ///
    /// // Or with version
    /// app.use_middleware(ultimo::middleware::builtin::server_headers("Ultimo", true));
    /// ```
    pub fn server_headers(name: impl Into<String>, include_version: bool) -> BoxedMiddleware {
        let name = name.into();
        let version = if include_version {
            format!("{}/{}", name, env!("CARGO_PKG_VERSION"))
        } else {
            name.clone()
        };

        Arc::new(move |ctx, next| {
            let powered_by = version.clone();
            Box::pin(async move {
                ctx.header("X-Powered-By", powered_by).await;
                next(ctx).await
            })
        })
    }

    /// Secure-by-default HTTP security headers.
    ///
    /// Sets HSTS, X-Content-Type-Options, X-Frame-Options, Referrer-Policy and a
    /// restrictive Permissions-Policy. Content-Security-Policy is opt-in (a wrong
    /// CSP breaks more than it protects) — set it with [`SecurityHeaders::csp`].
    /// Headers are applied to the response **only if the handler didn't already
    /// set them**, so per-route overrides win.
    ///
    /// ```
    /// # use ultimo::Ultimo;
    /// let mut app = Ultimo::new_without_defaults();
    /// app.use_middleware(ultimo::middleware::builtin::security_headers());
    /// // or customized:
    /// app.use_middleware(
    ///     ultimo::middleware::builtin::SecurityHeaders::new()
    ///         .csp("default-src 'self'")
    ///         .frame_options("SAMEORIGIN")
    ///         .build(),
    /// );
    /// ```
    #[derive(Debug, Clone)]
    pub struct SecurityHeaders {
        hsts: Option<String>,
        csp: Option<String>,
        frame_options: Option<String>,
        content_type_options: bool,
        referrer_policy: Option<String>,
        permissions_policy: Option<String>,
    }

    impl Default for SecurityHeaders {
        fn default() -> Self {
            Self {
                hsts: Some("max-age=31536000; includeSubDomains".to_string()),
                csp: None,
                frame_options: Some("DENY".to_string()),
                content_type_options: true,
                referrer_policy: Some("strict-origin-when-cross-origin".to_string()),
                permissions_policy: Some("geolocation=(), microphone=(), camera=()".to_string()),
            }
        }
    }

    impl SecurityHeaders {
        /// Secure defaults.
        pub fn new() -> Self {
            Self::default()
        }
        /// Set the `Strict-Transport-Security` value.
        pub fn hsts(mut self, value: impl Into<String>) -> Self {
            self.hsts = Some(value.into());
            self
        }
        /// Disable HSTS (e.g. for non-HTTPS environments).
        pub fn no_hsts(mut self) -> Self {
            self.hsts = None;
            self
        }
        /// Set the `Content-Security-Policy` (off by default).
        pub fn csp(mut self, value: impl Into<String>) -> Self {
            self.csp = Some(value.into());
            self
        }
        /// Set the `X-Frame-Options` value (default `DENY`).
        pub fn frame_options(mut self, value: impl Into<String>) -> Self {
            self.frame_options = Some(value.into());
            self
        }
        /// Set the `Referrer-Policy` value.
        pub fn referrer_policy(mut self, value: impl Into<String>) -> Self {
            self.referrer_policy = Some(value.into());
            self
        }
        /// Set the `Permissions-Policy` value.
        pub fn permissions_policy(mut self, value: impl Into<String>) -> Self {
            self.permissions_policy = Some(value.into());
            self
        }
        /// Disable the `X-Content-Type-Options: nosniff` header.
        pub fn no_content_type_options(mut self) -> Self {
            self.content_type_options = false;
            self
        }

        fn pairs(&self) -> Vec<(&'static str, String)> {
            let mut out = Vec::new();
            if let Some(v) = &self.hsts {
                out.push(("strict-transport-security", v.clone()));
            }
            if let Some(v) = &self.csp {
                out.push(("content-security-policy", v.clone()));
            }
            if let Some(v) = &self.frame_options {
                out.push(("x-frame-options", v.clone()));
            }
            if self.content_type_options {
                out.push(("x-content-type-options", "nosniff".to_string()));
            }
            if let Some(v) = &self.referrer_policy {
                out.push(("referrer-policy", v.clone()));
            }
            if let Some(v) = &self.permissions_policy {
                out.push(("permissions-policy", v.clone()));
            }
            out
        }

        /// Build the middleware.
        pub fn build(self) -> BoxedMiddleware {
            let pairs = Arc::new(self.pairs());
            Arc::new(move |ctx, next| {
                let pairs = pairs.clone();
                Box::pin(async move {
                    let mut response = next(ctx).await?;
                    let headers = response.headers_mut();
                    for (name, value) in pairs.iter() {
                        let header_name = hyper::header::HeaderName::from_static(name);
                        if !headers.contains_key(&header_name) {
                            if let Ok(hv) = hyper::header::HeaderValue::from_str(value) {
                                headers.insert(header_name, hv);
                            }
                        }
                    }
                    Ok(response)
                })
            })
        }
    }

    /// Security headers middleware with secure defaults.
    pub fn security_headers() -> BoxedMiddleware {
        SecurityHeaders::new().build()
    }

    // -------------------------------------------------------------------------
    // IP allow/deny (CIDR filtering)
    // -------------------------------------------------------------------------

    use std::net::IpAddr;

    /// A parsed CIDR network (e.g. `192.168.1.0/24`).
    #[derive(Debug, Clone)]
    pub(crate) struct CidrNetwork {
        addr: IpAddr,
        prefix_len: u8,
    }

    impl CidrNetwork {
        /// Parse a CIDR string like `10.0.0.0/8` or `::1/128`.
        /// Also accepts bare IPs (treated as /32 or /128).
        pub(crate) fn parse(s: &str) -> std::result::Result<Self, String> {
            let (addr_str, prefix_len) = if let Some((a, p)) = s.split_once('/') {
                let prefix: u8 = p.parse().map_err(|_| format!("invalid prefix: {p}"))?;
                (a, prefix)
            } else {
                let addr: IpAddr = s.parse().map_err(|e| format!("invalid IP: {e}"))?;
                let max = if addr.is_ipv4() { 32 } else { 128 };
                return Ok(Self {
                    addr,
                    prefix_len: max,
                });
            };

            let addr: IpAddr = addr_str.parse().map_err(|e| format!("invalid IP: {e}"))?;
            let max = if addr.is_ipv4() { 32 } else { 128 };
            if prefix_len > max {
                return Err(format!("prefix /{prefix_len} exceeds max /{max}"));
            }
            Ok(Self { addr, prefix_len })
        }

        /// Returns true if `ip` is within this network.
        pub(crate) fn contains(&self, ip: IpAddr) -> bool {
            match (self.addr, ip) {
                (IpAddr::V4(net), IpAddr::V4(target)) => {
                    if self.prefix_len == 0 {
                        return true;
                    }
                    let mask = u32::MAX
                        .checked_shl(32 - self.prefix_len as u32)
                        .unwrap_or(0);
                    (u32::from(net) & mask) == (u32::from(target) & mask)
                }
                (IpAddr::V6(net), IpAddr::V6(target)) => {
                    if self.prefix_len == 0 {
                        return true;
                    }
                    let mask = u128::MAX
                        .checked_shl(128 - self.prefix_len as u32)
                        .unwrap_or(0);
                    (u128::from(net) & mask) == (u128::from(target) & mask)
                }
                _ => false, // v4 vs v6 mismatch → no match
            }
        }
    }

    /// IP filter mode: allow-list or deny-list.
    #[derive(Debug, Clone)]
    enum IpFilterMode {
        /// Only listed networks are allowed; everything else is denied.
        Allow(Vec<CidrNetwork>),
        /// Listed networks are denied; everything else is allowed.
        Deny(Vec<CidrNetwork>),
    }

    /// IP allow/deny middleware builder (CIDR-aware).
    ///
    /// Filters requests by client IP against an allow-list or deny-list of
    /// CIDR networks. Respects proxy headers when `trust_proxy` is enabled.
    ///
    /// ```
    /// # use ultimo::Ultimo;
    /// let mut app = Ultimo::new_without_defaults();
    /// // Allow only private networks:
    /// app.use_middleware(
    ///     ultimo::middleware::builtin::IpFilter::allow(&[
    ///         "10.0.0.0/8",
    ///         "172.16.0.0/12",
    ///         "192.168.0.0/16",
    ///         "127.0.0.1",
    ///     ]).build(),
    /// );
    /// // Or deny specific ranges:
    /// app.use_middleware(
    ///     ultimo::middleware::builtin::IpFilter::deny(&["203.0.113.0/24"])
    ///         .build(),
    /// );
    /// ```
    #[derive(Debug, Clone)]
    pub struct IpFilter {
        mode: IpFilterMode,
    }

    impl IpFilter {
        /// Create an allow-list filter. Only IPs matching one of the given
        /// CIDR networks will be allowed; all others get 403 Forbidden.
        ///
        /// Accepts bare IPs (`127.0.0.1`) or CIDR notation (`10.0.0.0/8`).
        ///
        /// # Panics
        /// Panics if any entry fails to parse as a valid CIDR/IP.
        pub fn allow(cidrs: &[&str]) -> Self {
            Self {
                mode: IpFilterMode::Allow(Self::parse_cidrs(cidrs)),
            }
        }

        /// Create a deny-list filter. IPs matching any of the given CIDR
        /// networks will get 403 Forbidden; all others are allowed.
        ///
        /// # Panics
        /// Panics if any entry fails to parse as a valid CIDR/IP.
        pub fn deny(cidrs: &[&str]) -> Self {
            Self {
                mode: IpFilterMode::Deny(Self::parse_cidrs(cidrs)),
            }
        }

        fn parse_cidrs(cidrs: &[&str]) -> Vec<CidrNetwork> {
            cidrs
                .iter()
                .map(|s| {
                    CidrNetwork::parse(s).unwrap_or_else(|e| panic!("invalid CIDR '{s}': {e}"))
                })
                .collect()
        }

        /// Build the middleware.
        pub fn build(self) -> BoxedMiddleware {
            let mode = Arc::new(self.mode);
            Arc::new(move |ctx, next| {
                let mode = mode.clone();
                Box::pin(async move {
                    let ip = ctx.client_ip();

                    let allowed = match (ip, mode.as_ref()) {
                        (None, _) => false, // no IP → deny
                        (Some(ip), IpFilterMode::Allow(nets)) => {
                            nets.iter().any(|n| n.contains(ip))
                        }
                        (Some(ip), IpFilterMode::Deny(nets)) => {
                            !nets.iter().any(|n| n.contains(ip))
                        }
                    };

                    if allowed {
                        next(ctx).await
                    } else {
                        Ok(HyperResponse::builder()
                            .status(403)
                            .body(UltimoBody::full("Forbidden"))
                            .unwrap())
                    }
                })
            })
        }
    }

    // -------------------------------------------------------------------------
    // Rate limiting
    // -------------------------------------------------------------------------

    use std::collections::HashMap;
    use std::sync::Mutex;

    /// A token-bucket entry for a single key.
    pub(crate) struct RateBucket {
        pub(crate) tokens: f64,
        pub(crate) last_refill: std::time::Instant,
    }

    /// Evict buckets idle for at least `idle_cutoff`. A bucket idle that long
    /// has already refilled to its cap, so removing it is behaviorally
    /// identical to it staying — but bounds the map's memory under sustained
    /// load from many distinct keys (e.g. spoofed `X-Forwarded-For` values).
    pub(crate) fn evict_stale(
        buckets: &mut HashMap<String, RateBucket>,
        now: std::time::Instant,
        idle_cutoff: std::time::Duration,
    ) {
        buckets.retain(|_, b| now.duration_since(b.last_refill) < idle_cutoff);
    }

    /// Key extraction strategy for rate limiting.
    #[derive(Clone)]
    pub enum RateLimitKey {
        /// Rate limit by client IP (default).
        Ip,
        /// Rate limit by a custom header value (e.g. `X-API-Key`).
        Header(String),
        /// Rate limit globally (all requests share one bucket).
        Global,
    }

    /// Per-route or global rate limiting middleware (token bucket algorithm).
    ///
    /// Limits the number of requests per time window. Returns `429 Too Many
    /// Requests` with a `Retry-After` header when the limit is exceeded.
    ///
    /// ```
    /// # use ultimo::Ultimo;
    /// let mut app = Ultimo::new_without_defaults();
    /// // 100 requests per 60 seconds, keyed by client IP:
    /// app.use_middleware(
    ///     ultimo::middleware::builtin::RateLimiter::new(100, 60).build()
    /// );
    /// // 10 requests per second, keyed by API key header:
    /// app.use_middleware(
    ///     ultimo::middleware::builtin::RateLimiter::new(10, 1)
    ///         .key(ultimo::middleware::builtin::RateLimitKey::Header("X-API-Key".into()))
    ///         .build()
    /// );
    /// ```
    #[derive(Clone)]
    pub struct RateLimiter {
        max_requests: u64,
        window_secs: u64,
        key: RateLimitKey,
    }

    impl RateLimiter {
        /// Create a rate limiter: `max_requests` per `window_secs` seconds.
        /// Default key is client IP.
        pub fn new(max_requests: u64, window_secs: u64) -> Self {
            Self {
                max_requests,
                window_secs,
                key: RateLimitKey::Ip,
            }
        }

        /// Set the key extraction strategy.
        pub fn key(mut self, key: RateLimitKey) -> Self {
            self.key = key;
            self
        }

        /// Build the middleware.
        pub fn build(self) -> BoxedMiddleware {
            let rate = self.max_requests as f64 / self.window_secs as f64;
            let max_tokens = self.max_requests as f64;
            let window_secs = self.window_secs;
            let key_strategy = self.key;

            let buckets: Arc<Mutex<HashMap<String, RateBucket>>> =
                Arc::new(Mutex::new(HashMap::new()));
            // A bucket idle this long is guaranteed to have refilled to its
            // cap, so it's safe to evict (see `evict_stale`).
            let idle_cutoff = std::time::Duration::from_secs(window_secs.max(1));

            Arc::new(move |ctx, next| {
                let buckets = buckets.clone();
                let key_strategy = key_strategy.clone();
                let rate = rate;
                let max_tokens = max_tokens;
                let window_secs = window_secs;
                let idle_cutoff = idle_cutoff;

                Box::pin(async move {
                    // Extract key
                    let key = match &key_strategy {
                        RateLimitKey::Ip => ctx
                            .client_ip()
                            .map(|ip| ip.to_string())
                            .unwrap_or_else(|| "unknown".to_string()),
                        RateLimitKey::Header(name) => ctx
                            .req
                            .header(name)
                            .unwrap_or_else(|| "anonymous".to_string()),
                        RateLimitKey::Global => "__global__".to_string(),
                    };

                    // Check/update bucket
                    let allowed = {
                        let mut map = buckets.lock().unwrap_or_else(|e| e.into_inner());
                        let now = std::time::Instant::now();
                        let bucket = map.entry(key).or_insert_with(|| RateBucket {
                            tokens: max_tokens,
                            last_refill: now,
                        });

                        // Refill tokens based on elapsed time
                        let elapsed = now.duration_since(bucket.last_refill).as_secs_f64();
                        bucket.tokens = (bucket.tokens + elapsed * rate).min(max_tokens);
                        bucket.last_refill = now;

                        // Try to consume a token
                        let allowed = if bucket.tokens >= 1.0 {
                            bucket.tokens -= 1.0;
                            true
                        } else {
                            false
                        };

                        // Bound the map's memory (anti unbounded-growth DoS).
                        evict_stale(&mut map, now, idle_cutoff);

                        allowed
                    };

                    if allowed {
                        next(ctx).await
                    } else {
                        Ok(HyperResponse::builder()
                            .status(429)
                            .header("Retry-After", window_secs.to_string())
                            .header("Content-Type", "text/plain")
                            .body(UltimoBody::full("Too Many Requests"))
                            .unwrap())
                    }
                })
            })
        }
    }

    /// Rate limiting middleware with default settings (100 req/min per IP).
    pub fn rate_limiter() -> BoxedMiddleware {
        RateLimiter::new(100, 60).build()
    }

    // -------------------------------------------------------------------------
    // Response compression
    // -------------------------------------------------------------------------

    /// Response compression middleware (gzip + brotli).
    ///
    /// Negotiates the best encoding from the request's `Accept-Encoding` header.
    /// Brotli is preferred over gzip when both are accepted.
    ///
    /// Skips compression when:
    /// - The response body is smaller than `min_size` bytes (default: 1024).
    /// - The `Content-Type` is a binary format (images, audio, video, zip, …).
    /// - The response already carries a `Content-Encoding` header.
    ///
    /// Always sets `Vary: Accept-Encoding` (required by RFC 7231 so caches
    /// serve the correct version to each client).
    ///
    /// ```
    /// # use ultimo::Ultimo;
    /// let mut app = Ultimo::new_without_defaults();
    /// app.use_middleware(ultimo::middleware::builtin::compression());
    /// // or configured:
    /// app.use_middleware(
    ///     ultimo::middleware::builtin::Compression::new()
    ///         .gzip()
    ///         .brotli()
    ///         .min_size(512)
    ///         .build(),
    /// );
    /// ```
    #[cfg(feature = "compression")]
    #[derive(Debug, Clone)]
    pub struct Compression {
        gzip: bool,
        brotli: bool,
        min_size: usize,
    }

    #[cfg(feature = "compression")]
    impl Default for Compression {
        fn default() -> Self {
            Self {
                gzip: true,
                brotli: true,
                min_size: 1024,
            }
        }
    }

    #[cfg(feature = "compression")]
    impl Compression {
        /// Create with defaults (gzip + brotli enabled, min_size = 1024 bytes).
        pub fn new() -> Self {
            Self::default()
        }

        /// Enable gzip compression.
        pub fn gzip(mut self) -> Self {
            self.gzip = true;
            self
        }

        /// Enable brotli compression.
        pub fn brotli(mut self) -> Self {
            self.brotli = true;
            self
        }

        /// Minimum response body size in bytes before compression is applied.
        /// Responses smaller than this are passed through unchanged (default: 1024).
        pub fn min_size(mut self, bytes: usize) -> Self {
            self.min_size = bytes;
            self
        }

        /// Build the [`BoxedMiddleware`].
        pub fn build(self) -> BoxedMiddleware {
            use brotli::CompressorWriter;
            use flate2::{write::GzEncoder, Compression as GzLevel};
            use http_body_util::BodyExt;
            use hyper::header::{CONTENT_ENCODING, CONTENT_LENGTH, VARY};
            use std::io::Write;

            let gzip_enabled = self.gzip;
            let brotli_enabled = self.brotli;
            let min_size = self.min_size;

            Arc::new(move |ctx, next| {
                Box::pin(async move {
                    // Capture Accept-Encoding BEFORE consuming ctx with next().
                    let accept_enc = ctx
                        .req
                        .header("accept-encoding")
                        .unwrap_or_default()
                        .to_lowercase();

                    let mut res = next(ctx).await?;

                    // Always set Vary (RFC 7231 §7.1.4).
                    res.headers_mut().insert(
                        VARY,
                        hyper::header::HeaderValue::from_static("Accept-Encoding"),
                    );

                    // Skip if already encoded.
                    if res.headers().contains_key(CONTENT_ENCODING) {
                        return Ok(res);
                    }

                    // Decompose response so we can inspect and replace the body.
                    let (parts, body) = res.into_parts();

                    // Never buffer a streaming body — pass it through untouched.
                    let body_bytes = match body {
                        UltimoBody::Stream(_) => {
                            return Ok(hyper::Response::from_parts(parts, body));
                        }
                        // `Full<Bytes>` is infallible — unwrap is safe.
                        UltimoBody::Full(full) => full.collect().await.unwrap().to_bytes(),
                    };

                    // Skip below min_size.
                    if body_bytes.len() < min_size {
                        return Ok(hyper::Response::from_parts(
                            parts,
                            UltimoBody::full(body_bytes),
                        ));
                    }

                    // Skip binary content types.
                    let ct = parts
                        .headers
                        .get(hyper::header::CONTENT_TYPE)
                        .and_then(|v| v.to_str().ok())
                        .unwrap_or("")
                        .to_lowercase();

                    const SKIP_PREFIXES: &[&str] = &["image/", "audio/", "video/", "font/woff"];
                    const SKIP_EXACT: &[&str] = &[
                        "application/zip",
                        "application/gzip",
                        "application/x-gzip",
                        "application/octet-stream",
                    ];
                    let skip = SKIP_PREFIXES.iter().any(|p| ct.starts_with(p))
                        || SKIP_EXACT.iter().any(|e| ct.starts_with(e));

                    if skip {
                        return Ok(hyper::Response::from_parts(
                            parts,
                            UltimoBody::full(body_bytes),
                        ));
                    }

                    // Choose algorithm: prefer brotli > gzip > identity.
                    let use_brotli =
                        brotli_enabled && accept_enc.split(',').any(|t| t.trim() == "br");
                    let use_gzip = !use_brotli
                        && gzip_enabled
                        && accept_enc.split(',').any(|t| t.trim().starts_with("gzip"));

                    if use_brotli {
                        let mut compressed = Vec::new();
                        {
                            let mut writer = CompressorWriter::new(&mut compressed, 4096, 5, 22);
                            writer.write_all(&body_bytes).unwrap();
                        }
                        let len = compressed.len();
                        let mut res =
                            hyper::Response::from_parts(parts, UltimoBody::full(compressed));
                        res.headers_mut().insert(
                            CONTENT_ENCODING,
                            hyper::header::HeaderValue::from_static("br"),
                        );
                        res.headers_mut().insert(
                            CONTENT_LENGTH,
                            hyper::header::HeaderValue::from_str(&len.to_string()).unwrap(),
                        );
                        Ok(res)
                    } else if use_gzip {
                        let mut compressed = Vec::new();
                        {
                            let mut encoder = GzEncoder::new(&mut compressed, GzLevel::default());
                            encoder.write_all(&body_bytes).unwrap();
                            encoder.finish().unwrap();
                        }
                        let len = compressed.len();
                        let mut res =
                            hyper::Response::from_parts(parts, UltimoBody::full(compressed));
                        res.headers_mut().insert(
                            CONTENT_ENCODING,
                            hyper::header::HeaderValue::from_static("gzip"),
                        );
                        res.headers_mut().insert(
                            CONTENT_LENGTH,
                            hyper::header::HeaderValue::from_str(&len.to_string()).unwrap(),
                        );
                        Ok(res)
                    } else {
                        // No matching encoding — pass through unmodified.
                        Ok(hyper::Response::from_parts(
                            parts,
                            UltimoBody::full(body_bytes),
                        ))
                    }
                })
            })
        }
    }

    /// Compression middleware with defaults (gzip + brotli, min 1 KB).
    ///
    /// Convenience alias for `Compression::new().build()`.
    ///
    /// Requires the `compression` Cargo feature.
    ///
    /// ```
    /// # use ultimo::Ultimo;
    /// let mut app = Ultimo::new_without_defaults();
    /// app.use_middleware(ultimo::middleware::builtin::compression());
    /// ```
    #[cfg(feature = "compression")]
    pub fn compression() -> BoxedMiddleware {
        Compression::new().build()
    }
}

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

    #[test]
    fn test_middleware_chain_creation() {
        let chain = MiddlewareChain::new();
        assert_eq!(chain.middleware.len(), 0);
    }

    #[test]
    fn test_middleware_chain_push() {
        let mut chain = MiddlewareChain::new();
        let middleware: BoxedMiddleware =
            Arc::new(|ctx, next| Box::pin(async move { next(ctx).await }));

        chain.push(middleware.clone());
        assert_eq!(chain.middleware.len(), 1);

        chain.push(middleware);
        assert_eq!(chain.middleware.len(), 2);
    }

    #[test]
    fn test_cors_builder_creation() {
        let _cors = builtin::Cors::default();
        let _cors2 = builtin::Cors::new();
        // Just verify they compile
    }

    #[test]
    fn test_cors_builder_chaining() {
        let cors = builtin::Cors::new()
            .allow_origin("https://example.com")
            .allow_methods(vec!["GET", "POST"])
            .allow_headers(vec!["Authorization"]);

        // Build to verify it works
        let _middleware = cors.build();
    }

    #[test]
    fn test_cors_convenience_function() {
        let _cors = builtin::cors();
        // Just verify it compiles and returns middleware
    }

    #[test]
    fn test_logger_convenience_function() {
        let _logger = builtin::logger();
        // Just verify it compiles and returns middleware
    }

    #[test]
    fn test_powered_by_convenience_function() {
        let _powered_by = builtin::powered_by();
        // Just verify it compiles and returns middleware
    }

    #[test]
    fn test_middleware_chain_default() {
        let chain1 = MiddlewareChain::default();
        let chain2 = MiddlewareChain::new();
        assert_eq!(chain1.middleware.len(), chain2.middleware.len());
    }

    #[test]
    fn test_boxed_middleware_creation() {
        // Test that we can create BoxedMiddleware from a closure
        let _middleware: BoxedMiddleware = Arc::new(|ctx, next| {
            Box::pin(async move {
                // Do something before
                let result = next(ctx).await;
                // Do something after
                result
            })
        });
    }

    #[test]
    fn test_middleware_passthrough() {
        // Test creating a simple passthrough middleware
        let _passthrough: BoxedMiddleware =
            Arc::new(|ctx, next| Box::pin(async move { next(ctx).await }));
    }

    #[test]
    fn test_cors_multiple_methods() {
        let cors =
            builtin::Cors::new().allow_methods(vec!["GET", "POST", "PUT", "PATCH", "DELETE"]);

        let _middleware = cors.build();
    }

    #[test]
    fn test_cors_multiple_headers() {
        let cors = builtin::Cors::new().allow_headers(vec![
            "Content-Type",
            "Authorization",
            "X-Custom-Header",
        ]);

        let _middleware = cors.build();
    }

    #[test]
    fn test_cors_custom_origin() {
        let cors = builtin::Cors::new().allow_origin("https://app.example.com");

        let _middleware = cors.build();
    }

    #[test]
    fn test_cors_builder_defaults() {
        let cors = builtin::Cors::default();
        // Verify defaults are set - just build to ensure no panics
        let _middleware = cors.build();
    }

    #[test]
    fn test_server_headers_builder() {
        let _middleware = builtin::server_headers("CustomServer", false);
        let _middleware_with_version = builtin::server_headers("Ultimo", true);
        // Just verify compilation and creation
    }

    #[test]
    fn test_cors_origin_string_conversion() {
        // Test that Into<String> works for various types
        let cors1 = builtin::Cors::new().allow_origin("https://example.com");
        let cors2 = builtin::Cors::new().allow_origin(String::from("https://test.com"));

        let _m1 = cors1.build();
        let _m2 = cors2.build();
    }

    #[test]
    fn test_cors_methods_string_conversion() {
        let cors = builtin::Cors::new().allow_methods(vec!["GET", "POST"]);

        let _middleware = cors.build();
    }

    #[test]
    fn test_cors_headers_string_conversion() {
        let cors = builtin::Cors::new().allow_headers(vec!["Content-Type"]);

        let _middleware = cors.build();
    }

    #[test]
    fn test_middleware_arc_clone() {
        let middleware: BoxedMiddleware =
            Arc::new(|ctx, next| Box::pin(async move { next(ctx).await }));

        let cloned = middleware.clone();
        // Verify Arc::clone works
        assert_eq!(Arc::strong_count(&middleware), Arc::strong_count(&cloned));
    }

    #[test]
    fn test_middleware_is_send_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}

        assert_send::<BoxedMiddleware>();
        assert_sync::<BoxedMiddleware>();
    }

    #[test]
    fn test_middleware_chain_is_send() {
        fn assert_send<T: Send>() {}
        assert_send::<MiddlewareChain>();
    }

    #[test]
    fn test_cors_struct_is_send_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}

        assert_send::<builtin::Cors>();
        assert_sync::<builtin::Cors>();
    }

    // IP filter tests ---------------------------------------------------------

    #[test]
    fn test_ip_filter_allow_builder() {
        let _m = builtin::IpFilter::allow(&["10.0.0.0/8", "192.168.1.0/24"]).build();
    }

    #[test]
    fn test_ip_filter_deny_builder() {
        let _m = builtin::IpFilter::deny(&["203.0.113.0/24"]).build();
    }

    #[test]
    fn test_ip_filter_bare_ip() {
        let _m = builtin::IpFilter::allow(&["127.0.0.1", "::1"]).build();
    }

    #[test]
    #[should_panic(expected = "invalid CIDR")]
    fn test_ip_filter_invalid_cidr_panics() {
        builtin::IpFilter::allow(&["not-an-ip/8"]);
    }

    #[test]
    #[should_panic(expected = "prefix /33 exceeds max /32")]
    fn test_ip_filter_prefix_too_large() {
        builtin::IpFilter::allow(&["10.0.0.0/33"]);
    }

    #[test]
    fn test_cidr_contains_ipv4() {
        let net = builtin::CidrNetwork::parse("192.168.1.0/24").unwrap();
        assert!(net.contains("192.168.1.1".parse().unwrap()));
        assert!(net.contains("192.168.1.254".parse().unwrap()));
        assert!(!net.contains("192.168.2.1".parse().unwrap()));
        assert!(!net.contains("10.0.0.1".parse().unwrap()));
    }

    #[test]
    fn test_cidr_contains_ipv6() {
        let net = builtin::CidrNetwork::parse("fd00::/8").unwrap();
        assert!(net.contains("fd00::1".parse().unwrap()));
        assert!(net.contains("fdff::1".parse().unwrap()));
        assert!(!net.contains("fe80::1".parse().unwrap()));
    }

    #[test]
    fn test_cidr_single_host() {
        let net = builtin::CidrNetwork::parse("127.0.0.1").unwrap();
        assert!(net.contains("127.0.0.1".parse().unwrap()));
        assert!(!net.contains("127.0.0.2".parse().unwrap()));
    }

    #[test]
    fn test_cidr_v4_v6_mismatch() {
        let net = builtin::CidrNetwork::parse("10.0.0.0/8").unwrap();
        assert!(!net.contains("::1".parse().unwrap()));
    }

    #[test]
    fn test_cidr_zero_prefix() {
        let net = builtin::CidrNetwork::parse("0.0.0.0/0").unwrap();
        assert!(net.contains("1.2.3.4".parse().unwrap()));
        assert!(net.contains("255.255.255.255".parse().unwrap()));
    }

    #[test]
    fn test_ip_filter_struct_is_send_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}

        assert_send::<builtin::IpFilter>();
        assert_sync::<builtin::IpFilter>();
    }

    // Rate limiter tests ------------------------------------------------------

    #[test]
    fn test_rate_limiter_builder() {
        let _m = builtin::RateLimiter::new(100, 60).build();
    }

    #[test]
    fn test_rate_limiter_with_header_key() {
        let _m = builtin::RateLimiter::new(10, 1)
            .key(builtin::RateLimitKey::Header("X-API-Key".into()))
            .build();
    }

    #[test]
    fn test_rate_limiter_with_global_key() {
        let _m = builtin::RateLimiter::new(5, 10)
            .key(builtin::RateLimitKey::Global)
            .build();
    }

    #[test]
    fn test_rate_limiter_convenience_function() {
        let _m = builtin::rate_limiter();
    }

    #[test]
    fn test_rate_limiter_struct_is_send_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}

        assert_send::<builtin::RateLimiter>();
        assert_sync::<builtin::RateLimiter>();
    }

    #[test]
    fn test_rate_limiter_evicts_stale_buckets() {
        use builtin::{evict_stale, RateBucket};
        use std::collections::HashMap;
        use std::time::{Duration, Instant};

        let now = Instant::now();
        let mut map: HashMap<String, RateBucket> = HashMap::new();
        map.insert(
            "stale".to_string(),
            RateBucket {
                tokens: 5.0,
                last_refill: now - Duration::from_secs(120),
            },
        );
        map.insert(
            "fresh".to_string(),
            RateBucket {
                tokens: 5.0,
                last_refill: now,
            },
        );

        evict_stale(&mut map, now, Duration::from_secs(60));

        assert!(!map.contains_key("stale"), "idle bucket must be evicted");
        assert!(map.contains_key("fresh"), "active bucket must be kept");
    }
}