autumn-web 0.5.0

An opinionated, convention-over-configuration web framework for Rust
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
//! Maintenance mode Tower middleware.
//!
//! Intercepts HTTP requests when maintenance mode is active and returns
//! `503 Service Unavailable` with a `Retry-After` header. Routes under the
//! configured actuator/health prefix always pass through so platform load
//! balancers keep every replica in rotation.
//!
//! # Response format negotiation
//!
//! - Requests with `Accept: text/html` (or no `Accept`) receive an HTML page.
//! - Requests with `Accept: application/json` or
//!   `Accept: application/problem+json` receive an RFC 7807 Problem Details
//!   JSON object.
//!
//! # Bypass mechanisms
//!
//! In order of evaluation:
//!
//! 1. **Actuator prefix** – paths starting with `health_prefix` (default
//!    `/actuator`) always pass through.
//! 2. **Bypass header** – a configured `(header_name, expected_value)` pair;
//!    requests carrying the matching header are not gated.
//! 3. **IP allow-list** – CIDR-expanded list; clients whose IP matches any
//!    entry bypass the 503.
//! 4. **Read-only mode** – when `readonly = true`, `GET`, `HEAD`, and
//!    `OPTIONS` requests pass through; write methods are gated.

use std::future::Future;
use std::net::IpAddr;
use std::pin::Pin;
use std::task::{Context, Poll};

use axum::body::Body;
use axum::http::{
    Method, Request, Response, StatusCode,
    header::{ACCEPT, CONTENT_TYPE},
};
use pin_project_lite::pin_project;
use tower::{Layer, Service};

use crate::maintenance::{MaintenanceConfig, MaintenanceState, ip_in_allow_list};

/// Default health/actuator prefix whose routes bypass maintenance.
pub const DEFAULT_HEALTH_PREFIX: &str = "/actuator";

/// Retry-After value (seconds) sent in every 503 response.
const RETRY_AFTER_SECS: &str = "120";

/// Tower [`Layer`] that adds maintenance-mode gating to a service.
///
/// Clone this layer and call [`with_health_prefix`](Self::with_health_prefix)
/// to override the default `/actuator` bypass prefix.
#[derive(Clone)]
pub struct MaintenanceLayer {
    state: MaintenanceState,
    health_prefix: String,
    bypass_paths: Vec<String>,
    probe_paths: Vec<String>,
}

impl MaintenanceLayer {
    /// Create a [`MaintenanceLayer`] backed by `state`.
    ///
    /// Uses `/actuator` as the health-check prefix by default.
    #[must_use]
    pub fn new(state: MaintenanceState) -> Self {
        Self {
            state,
            health_prefix: DEFAULT_HEALTH_PREFIX.to_owned(),
            bypass_paths: Vec::new(),
            probe_paths: Vec::new(),
        }
    }

    /// Override the health-check prefix (e.g. `/health`).
    ///
    /// Requests to paths that start with this prefix always pass through,
    /// regardless of maintenance state, so load balancers keep the replica
    /// in rotation.
    #[must_use]
    pub fn with_health_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.health_prefix = prefix.into();
        self
    }

    /// Configure bypass paths that escape maintenance mode.
    ///
    /// Requests to these paths (or starting with them as slash-delimited segments) always pass through.
    #[must_use]
    pub fn with_bypass_paths(mut self, paths: Vec<String>) -> Self {
        self.bypass_paths = paths;
        self
    }

    /// Configure exact-match health probe paths that escape maintenance mode.
    #[must_use]
    pub fn with_probe_paths(mut self, paths: Vec<String>) -> Self {
        self.probe_paths = paths;
        self
    }
}

impl<S> Layer<S> for MaintenanceLayer {
    type Service = MaintenanceService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        MaintenanceService {
            inner,
            state: self.state.clone(),
            health_prefix: self.health_prefix.clone(),
            bypass_paths: self.bypass_paths.clone(),
            probe_paths: self.probe_paths.clone(),
        }
    }
}

/// Tower [`Service`] produced by [`MaintenanceLayer`].
#[derive(Clone)]
pub struct MaintenanceService<S> {
    inner: S,
    state: MaintenanceState,
    health_prefix: String,
    bypass_paths: Vec<String>,
    probe_paths: Vec<String>,
}

impl<S> MaintenanceService<S> {
    /// Determine whether this request should be gated by maintenance mode.
    ///
    /// Returns `Some(503 response)` when the request should be blocked, or
    /// `None` when it should pass through to the inner service.
    fn gate_request<B>(
        &self,
        req: &Request<B>,
        config: &MaintenanceConfig,
    ) -> Option<Response<Body>> {
        // 1. Actuator/health routes and configured bypass paths always pass through.
        let path = req.uri().path();
        let health_matched = if self.health_prefix.is_empty() || self.health_prefix == "/" {
            path == "/"
        } else {
            path == self.health_prefix
                || if self.health_prefix.ends_with('/') {
                    path.starts_with(&self.health_prefix)
                } else {
                    let mut prefix_slash = self.health_prefix.clone();
                    prefix_slash.push('/');
                    path.starts_with(&prefix_slash)
                }
        };
        if health_matched {
            return None;
        }
        for probe in &self.probe_paths {
            if path == probe {
                return None;
            }
        }
        for bypass in &self.bypass_paths {
            if path == bypass {
                return None;
            }
            if bypass != "/"
                && !bypass.is_empty()
                && let Some(stripped) = path.strip_prefix(bypass)
                && (bypass.ends_with('/') || stripped.starts_with('/'))
            {
                return None;
            }
        }

        // 2. Bypass header.
        if let Some((header_name, expected_value)) = &config.bypass_header
            && let Some(val) = req.headers().get(header_name.as_str())
            && val.as_bytes() == expected_value.as_bytes()
        {
            return None;
        }

        // 3. IP allow-list.
        if !config.allow_ips.is_empty()
            && let Some(client_ip) = extract_client_ip(req)
            && ip_in_allow_list(&client_ip, &config.allow_ips)
        {
            return None;
        }

        // 4. Read-only mode: safe methods pass through.
        if config.readonly {
            let method = req.method();
            if matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) {
                return None;
            }
        }

        Some(build_503_response(req, config))
    }
}

impl<S, ReqBody> Service<Request<ReqBody>> for MaintenanceService<S>
where
    S: Service<Request<ReqBody>, Response = Response<Body>>,
{
    type Response = Response<Body>;
    type Error = S::Error;
    type Future = MaintenanceFuture<S::Future>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
        if let Some(config) = self.state.get()
            && let Some(response) = self.gate_request(&req, &config)
        {
            return MaintenanceFuture::ShortCircuit {
                response: Some(response),
            };
        }
        MaintenanceFuture::Forward {
            inner: self.inner.call(req),
        }
    }
}

pin_project! {
    /// Future returned by [`MaintenanceService`].
    ///
    /// Either resolves immediately with a 503 response (short-circuit path)
    /// or delegates to the wrapped inner service.
    #[project = MaintenanceFutureProj]
    pub enum MaintenanceFuture<F> {
        ShortCircuit { response: Option<Response<Body>> },
        Forward { #[pin] inner: F },
    }
}

impl<F, E> Future for MaintenanceFuture<F>
where
    F: Future<Output = Result<Response<Body>, E>>,
{
    type Output = Result<Response<Body>, E>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match self.project() {
            MaintenanceFutureProj::ShortCircuit { response } => Poll::Ready(Ok(response
                .take()
                .expect("MaintenanceFuture polled after completion"))),
            MaintenanceFutureProj::Forward { inner } => inner.poll(cx),
        }
    }
}

/// Extract the client IP from a request.
///
/// When [`crate::security::ResolvedClientIdentity`] is present (stamped by
/// `TrustedProxiesLayer`), its resolved address is used so that the configured
/// trusted-proxy policy governs which forwarded IP is accepted. Raw
/// `X-Forwarded-For` / `X-Real-IP` headers are only consulted as a fallback
/// when the layer is not installed (e.g. in tests).
fn extract_client_ip<B>(req: &Request<B>) -> Option<IpAddr> {
    // Resolved by TrustedProxiesLayer — respects the proxy trust policy.
    if let Some(identity) = req
        .extensions()
        .get::<crate::security::ResolvedClientIdentity>()
    {
        return identity.addr;
    }

    // Fallback: raw headers (TrustedProxiesLayer not installed).

    // X-Forwarded-For: <client>, <proxy1>, <proxy2>
    if let Some(xff) = req.headers().get("x-forwarded-for")
        && let Ok(s) = xff.to_str()
        && let Some(first) = s.split(',').next()
        && let Ok(ip) = first.trim().parse::<IpAddr>()
    {
        return Some(ip);
    }

    // X-Real-Ip (set by nginx)
    if let Some(xri) = req.headers().get("x-real-ip")
        && let Ok(s) = xri.to_str()
        && let Ok(ip) = s.trim().parse::<IpAddr>()
    {
        return Some(ip);
    }

    // SocketAddr extension set by Axum's ConnectInfo
    req.extensions()
        .get::<std::net::SocketAddr>()
        .map(std::net::SocketAddr::ip)
}

/// Build a 503 response with the appropriate content type.
fn build_503_response<B>(req: &Request<B>, config: &MaintenanceConfig) -> Response<Body> {
    let message = config
        .message
        .as_deref()
        .unwrap_or("The service is temporarily unavailable. Please try again later.");

    let wants_json = req
        .headers()
        .get(ACCEPT)
        .and_then(|v| v.to_str().ok())
        .is_some_and(|accept| {
            accept.contains("application/json") || accept.contains("application/problem+json")
        });

    if wants_json {
        let body = serde_json::json!({
            "type": "about:blank",
            "title": "Service Unavailable",
            "status": 503,
            "detail": message,
        });
        Response::builder()
            .status(StatusCode::SERVICE_UNAVAILABLE)
            .header("Retry-After", RETRY_AFTER_SECS)
            .header(CONTENT_TYPE, "application/problem+json")
            .body(Body::from(body.to_string()))
            .expect("valid 503 JSON response")
    } else {
        let html = format!(
            "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\">\
             <title>503 Service Unavailable</title>\
             <style>body{{font-family:sans-serif;max-width:600px;margin:4rem auto;padding:0 1rem}}\
             h1{{color:#c0392b}}</style></head>\
             <body><h1>Service Temporarily Unavailable</h1>\
             <p>{message}</p>\
             <p>Please try again later.</p></body></html>"
        );
        Response::builder()
            .status(StatusCode::SERVICE_UNAVAILABLE)
            .header("Retry-After", RETRY_AFTER_SECS)
            .header(CONTENT_TYPE, "text/html; charset=utf-8")
            .body(Body::from(html))
            .expect("valid 503 HTML response")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::maintenance::MaintenanceConfig;
    use axum::Router;
    use axum::body::Body;
    use axum::routing::get;
    use tower::ServiceExt; // for oneshot

    fn make_app(state: MaintenanceState) -> Router {
        Router::new()
            .route("/", get(|| async { "ok" }))
            .route("/api/data", get(|| async { "data" }))
            .route("/actuator/health", get(|| async { "healthy" }))
            .layer(MaintenanceLayer::new(state))
    }

    async fn response_status(app: Router, uri: &str) -> StatusCode {
        app.oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
            .await
            .unwrap()
            .status()
    }

    // ── Maintenance off ───────────────────────────────────────────────────────

    #[tokio::test]
    async fn maintenance_off_passes_through() {
        let state = MaintenanceState::new();
        let app = make_app(state);
        assert_eq!(response_status(app, "/").await, StatusCode::OK);
    }

    // ── Maintenance on — basic 503 ────────────────────────────────────────────

    #[tokio::test]
    async fn maintenance_on_returns_503() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig::default());
        let app = make_app(state);
        assert_eq!(
            response_status(app, "/").await,
            StatusCode::SERVICE_UNAVAILABLE
        );
    }

    #[tokio::test]
    async fn maintenance_on_includes_retry_after_header() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig::default());
        let app = make_app(state);

        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert!(resp.headers().contains_key("retry-after"));
    }

    // ── Content negotiation ───────────────────────────────────────────────────

    #[tokio::test]
    async fn maintenance_on_html_response_for_browser() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig::default());
        let app = make_app(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header(ACCEPT, "text/html")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        let ct = resp.headers().get(CONTENT_TYPE).unwrap().to_str().unwrap();
        assert!(ct.contains("text/html"), "expected text/html, got {ct}");
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let html = String::from_utf8(body.to_vec()).unwrap();
        assert!(
            html.contains("Service Temporarily Unavailable"),
            "body: {html}"
        );
    }

    #[tokio::test]
    async fn maintenance_on_json_response_for_api_client() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig::default());
        let app = make_app(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/api/data")
                    .header(ACCEPT, "application/json")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        let ct = resp.headers().get(CONTENT_TYPE).unwrap().to_str().unwrap();
        assert!(
            ct.contains("application/problem+json"),
            "expected problem+json, got {ct}"
        );
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["status"], 503);
        assert_eq!(json["title"], "Service Unavailable");
        assert!(json["detail"].is_string(), "detail should be a string");
    }

    #[tokio::test]
    async fn maintenance_on_problem_json_for_problem_json_accept() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig::default());
        let app = make_app(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/api/data")
                    .header(ACCEPT, "application/problem+json")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let ct = resp.headers().get(CONTENT_TYPE).unwrap().to_str().unwrap();
        assert!(ct.contains("application/problem+json"), "got {ct}");
    }

    #[tokio::test]
    async fn maintenance_on_custom_message_in_body() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig {
            message: Some("Deploying v2.0".into()),
            ..Default::default()
        });
        let app = make_app(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header(ACCEPT, "text/html")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let html = String::from_utf8(body.to_vec()).unwrap();
        assert!(
            html.contains("Deploying v2.0"),
            "custom message absent: {html}"
        );
    }

    // ── Actuator / health bypass ──────────────────────────────────────────────

    #[tokio::test]
    async fn maintenance_on_actuator_path_passes_through() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig::default());
        let app = make_app(state);
        assert_eq!(
            response_status(app, "/actuator/health").await,
            StatusCode::OK
        );
    }

    #[tokio::test]
    async fn maintenance_on_custom_health_prefix_passes_through() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig::default());

        let app = Router::new()
            .route("/health", get(|| async { "ok" }))
            .route("/", get(|| async { "root" }))
            .layer(MaintenanceLayer::new(state).with_health_prefix("/health"));

        assert_eq!(
            response_status(app.clone(), "/health").await,
            StatusCode::OK
        );
        assert_eq!(
            response_status(app, "/").await,
            StatusCode::SERVICE_UNAVAILABLE
        );
    }

    // ── Bypass header ─────────────────────────────────────────────────────────

    #[tokio::test]
    async fn maintenance_on_bypass_header_passes_through() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig {
            bypass_header: Some(("X-Autumn-Maintenance-Bypass".into(), "my-secret".into())),
            ..Default::default()
        });
        let app = make_app(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header("X-Autumn-Maintenance-Bypass", "my-secret")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn maintenance_on_wrong_bypass_header_value_blocked() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig {
            bypass_header: Some(("X-Autumn-Maintenance-Bypass".into(), "my-secret".into())),
            ..Default::default()
        });
        let app = make_app(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header("X-Autumn-Maintenance-Bypass", "wrong-value")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    #[tokio::test]
    async fn maintenance_on_missing_bypass_header_blocked() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig {
            bypass_header: Some(("X-Autumn-Maintenance-Bypass".into(), "my-secret".into())),
            ..Default::default()
        });
        let app = make_app(state);
        assert_eq!(
            response_status(app, "/").await,
            StatusCode::SERVICE_UNAVAILABLE
        );
    }

    // ── IP allow-list bypass ──────────────────────────────────────────────────

    #[tokio::test]
    async fn maintenance_on_allowed_ip_passes_through() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig {
            allow_ips: vec!["127.0.0.1".into()],
            ..Default::default()
        });
        let app = make_app(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header("X-Forwarded-For", "127.0.0.1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn maintenance_on_disallowed_ip_blocked() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig {
            allow_ips: vec!["10.0.0.0/8".into()],
            ..Default::default()
        });
        let app = make_app(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header("X-Forwarded-For", "192.168.1.5")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    /// When `ResolvedClientIdentity` is stamped by `TrustedProxiesLayer`, its
    /// resolved addr is used for allow-list checks — a spoofed X-Forwarded-For
    /// header cannot bypass maintenance mode by claiming an allowed IP.
    #[tokio::test]
    async fn maintenance_resolved_identity_takes_precedence_over_raw_xff() {
        use crate::security::ResolvedClientIdentity;
        use std::net::IpAddr;

        let state = MaintenanceState::new();
        // Only 10.x.x.x is allowed.
        state.enable(MaintenanceConfig {
            allow_ips: vec!["10.0.0.0/8".into()],
            ..Default::default()
        });

        // The resolved identity (from TrustedProxiesLayer) says the real client
        // is 192.168.1.5 — not in the allow list.
        let real_ip: IpAddr = "192.168.1.5".parse().unwrap();
        let mut req = Request::builder()
            .uri("/")
            // Attacker forges an allowed IP in XFF.
            .header("X-Forwarded-For", "10.0.0.1")
            .body(Body::empty())
            .unwrap();
        req.extensions_mut().insert(ResolvedClientIdentity {
            addr: Some(real_ip),
            host: None,
            scheme: None,
        });

        let app = Router::new()
            .route("/", get(|| async { "ok" }))
            .layer(MaintenanceLayer::new(state));

        let resp = app.oneshot(req).await.unwrap();
        // Must be blocked: resolved IP (192.168.1.5) is not in the allow list.
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    // ── Read-only mode ────────────────────────────────────────────────────────

    #[tokio::test]
    async fn maintenance_readonly_get_passes_through() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig {
            readonly: true,
            ..Default::default()
        });
        let app = Router::new()
            .route("/", get(|| async { "ok" }))
            .layer(MaintenanceLayer::new(state));

        assert_eq!(response_status(app, "/").await, StatusCode::OK);
    }

    #[tokio::test]
    async fn maintenance_readonly_post_returns_503() {
        use axum::routing::post;
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig {
            readonly: true,
            ..Default::default()
        });
        let app = Router::new()
            .route("/submit", post(|| async { "ok" }))
            .layer(MaintenanceLayer::new(state));

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/submit")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    #[tokio::test]
    async fn maintenance_readonly_head_passes_through() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig {
            readonly: true,
            ..Default::default()
        });
        let app = Router::new()
            .route("/", get(|| async { "ok" }))
            .layer(MaintenanceLayer::new(state));

        let resp = app
            .oneshot(
                Request::builder()
                    .method(Method::HEAD)
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        // HEAD returns 200 (no body)
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // ── Layer behaviour ───────────────────────────────────────────────────────

    #[tokio::test]
    async fn maintenance_layer_clone_shares_state() {
        let state = MaintenanceState::new();
        let layer = MaintenanceLayer::new(state.clone());

        // The cloned layer wraps the same underlying Arc, so enabling
        // maintenance through `state` is visible through the clone.
        let app = Router::new()
            .route("/", get(|| async { "ok" }))
            .layer(layer.clone());

        state.enable(MaintenanceConfig::default());
        assert_eq!(
            response_status(app, "/").await,
            StatusCode::SERVICE_UNAVAILABLE
        );
    }

    #[tokio::test]
    async fn maintenance_on_root_health_prefix_passes_only_root() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig::default());

        let app = Router::new()
            .route("/", get(|| async { "root" }))
            .route("/api/data", get(|| async { "data" }))
            .layer(MaintenanceLayer::new(state).with_health_prefix("/"));

        assert_eq!(response_status(app.clone(), "/").await, StatusCode::OK);
        assert_eq!(
            response_status(app, "/api/data").await,
            StatusCode::SERVICE_UNAVAILABLE
        );
    }

    #[tokio::test]
    async fn maintenance_on_custom_health_prefix_segment_aware() {
        let state = MaintenanceState::new();
        state.enable(MaintenanceConfig::default());

        let app = Router::new()
            .route("/actuator/health", get(|| async { "healthy" }))
            .route("/actuator-dashboard", get(|| async { "dashboard" }))
            .layer(MaintenanceLayer::new(state).with_health_prefix("/actuator"));

        assert_eq!(
            response_status(app.clone(), "/actuator/health").await,
            StatusCode::OK
        );
        assert_eq!(
            response_status(app, "/actuator-dashboard").await,
            StatusCode::SERVICE_UNAVAILABLE
        );
    }
}