guard-core-rs 4.3.2

Framework-agnostic security engine for the Guard ecosystem.
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
//! The HTTPS enforcement pipeline stage for tower stacks.
//!
//! One `tower::Layer` answering the reference engine's `https_enforcement`
//! check (`guard_core/core/checks/implementations/https_enforcement.py`)
//! before a request reaches the inner service.
//!
//! The decision core is [`guard_core_engine::https_enforcement`]; this
//! stage wires it into the family's tower seams:
//!
//! ```text
//! route require_https wins over the global enforce_https arm
//! plain HTTP under a requirement:  301 redirect to the https URL
//!                                  (the reference create_https_redirect)
//! passive mode:                    pass through (log-only in the reference)
//! ```
//!
//! The reference answers the redirect through its response factory and the
//! response modifier, and never fires the block hook for this check
//! (`https_enforcement` is in `ON_BLOCK_EXCLUDED_CHECK_NAMES`) - the stage
//! mirrors the exclusion by construction (it carries no hook) and renders
//! the plain `301` + `Location` shape.
//!
//! # Example
//!
//! ```
//! use guard_core_rs::https_enforcement::{HttpsEnforcementStage, HttpsEnforcementStageConfig};
//!
//! let stage = HttpsEnforcementStage::builder(HttpsEnforcementStageConfig::default())
//!     .enforce_https(true)
//!     .build()
//!     .expect("valid proxy list");
//!
//! // Plain HTTP under a global enforcement: a 301 to the https URL.
//! let answer = stage
//!     .decide("/", "http", None, None, "https://host.example/")
//!     .expect("redirected");
//! assert_eq!(answer.status, 301);
//! assert_eq!(answer.location, "https://host.example/");
//!
//! // HTTPS passes.
//! assert!(stage.decide("/", "https", None, None, "").is_none());
//! ```

use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use ::tower::Layer;
use http::{Request, Response, StatusCode};

use crate::event_types::{EVENT_DECORATOR_VIOLATION, EVENT_HTTPS_ENFORCED};
use crate::events::{MIDDLEWARE_HANDLER_NAME, SecurityEvent, SecurityEventBus};
use crate::redact::SensitiveNames;

pub use guard_core_engine::https_enforcement::{
    HTTPS_ENFORCEMENT_CHECK_NAME, HTTPS_REDIRECT_STATUS,
};

/// The stage's answer: the reference's `create_https_redirect` shape (a
/// `301` to the scheme-upgraded URL).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpsRedirectAnswer {
    /// `301` (`HTTPS_REDIRECT_STATUS`).
    pub status: u16,
    /// The request URL with the scheme replaced by `https` (the reference's
    /// `url_replace_scheme("https")`), composed by the caller.
    pub location: String,
}

/// How the stage learns a path's `require_https` (the reference reads it
/// from `request.state.route_config`). `None` means no route config: the
/// global arm decides. `Some(false)` opts the route out.
pub type RouteHttpsResolver = Arc<dyn Fn(&str) -> Option<bool> + Send + Sync>;

/// The stage configuration (`SecurityConfig.enforce_https`,
/// `.trust_x_forwarded_proto`, `.passive_mode`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct HttpsEnforcementStageConfig {
    /// The global arm, used when the route resolver has no entry.
    pub enforce_https: bool,
    /// Whether `X-Forwarded-Proto` is believed (never without a trusted
    /// connecting IP).
    pub trust_x_forwarded_proto: bool,
    /// `passive_mode`: the violation is observed, never redirected.
    pub passive_mode: bool,
}

/// The HTTPS enforcement stage.
#[derive(Clone)]
pub struct HttpsEnforcementStage {
    config: HttpsEnforcementStageConfig,
    trusted_proxies: Vec<String>,
    route_resolver: Option<RouteHttpsResolver>,
    events: Option<Arc<SecurityEventBus>>,
    sensitive: Arc<SensitiveNames>,
}

impl fmt::Debug for HttpsEnforcementStage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HttpsEnforcementStage")
            .field("config", &self.config)
            .field("trusted_proxies", &self.trusted_proxies.len())
            .finish_non_exhaustive()
    }
}

/// Builder for [`HttpsEnforcementStage`].
#[derive(Default)]
pub struct HttpsEnforcementStageBuilder {
    config: HttpsEnforcementStageConfig,
    trusted_proxies: Vec<String>,
    route_resolver: Option<RouteHttpsResolver>,
    events: Option<Arc<SecurityEventBus>>,
    sensitive: SensitiveNames,
}

impl HttpsEnforcementStage {
    /// Start a builder over `config`.
    #[must_use]
    pub fn builder(config: HttpsEnforcementStageConfig) -> HttpsEnforcementStageBuilder {
        HttpsEnforcementStageBuilder {
            config,
            trusted_proxies: Vec::new(),
            route_resolver: None,
            events: None,
            sensitive: SensitiveNames::default(),
        }
    }

    /// One pass of the stage. `path` selects the route's `require_https`,
    /// `url_scheme` / `client_host` / `x_forwarded_proto` are the request
    /// facts the reference check reads, and `https_url` is the request URL
    /// with the scheme already swapped to `https` (the redirect target the
    /// reference's `url_replace_scheme` produces; the engine cannot see
    /// the full URL). `None` passes; `Some` is the redirect answer.
    ///
    /// # Errors
    ///
    /// A [`guard_core_engine::ip_gate::IpGateError`] naming an invalid
    /// trusted-proxy entry (config errors fail closed at the builder, so
    /// this only surfaces through [`HttpsEnforcementStageBuilder::build`]).
    #[must_use]
    pub fn decide(
        &self,
        path: &str,
        url_scheme: &str,
        client_host: Option<&str>,
        x_forwarded_proto: Option<&str>,
        https_url: &str,
    ) -> Option<HttpsRedirectAnswer> {
        let route_require_https = self
            .route_resolver
            .as_ref()
            .and_then(|resolve| resolve(path));
        self.decide_route(
            path,
            url_scheme,
            client_host,
            x_forwarded_proto,
            https_url,
            route_require_https,
        )
    }

    /// One pass of the stage with the route's `require_https` handed in
    /// directly (the carrier lane: the adapter resolved the route's
    /// `RouteConfig` itself, so no resolver seam needs to be installed on
    /// the stage). Everything else - the global arm, the trust knobs, the
    /// passive handling, the violation emission - matches
    /// [`HttpsEnforcementStage::decide`]; `None` means the resolver seam
    /// had no answer for the path.
    #[must_use]
    pub fn decide_route(
        &self,
        path: &str,
        url_scheme: &str,
        client_host: Option<&str>,
        x_forwarded_proto: Option<&str>,
        https_url: &str,
        route_require_https: Option<bool>,
    ) -> Option<HttpsRedirectAnswer> {
        let engine_config = guard_core_engine::https_enforcement::HttpsEnforcementConfig::new(
            self.config.enforce_https,
            self.config.trust_x_forwarded_proto,
            self.trusted_proxies.iter().map(String::as_str),
        )
        .expect("builder validated the proxy list");
        let request = guard_core_engine::https_enforcement::HttpsRequest {
            url_scheme,
            client_host,
            x_forwarded_proto,
            route_require_https,
        };
        match guard_core_engine::https_enforcement::decide(&request, &engine_config) {
            guard_core_engine::https_enforcement::HttpsVerdict::Allowed => None,
            guard_core_engine::https_enforcement::HttpsVerdict::Redirect { route_scoped } => {
                // The reference emits the violation event before its
                // passive-mode branch, so passive mode observes it too.
                self.observe_https_violation(
                    route_scoped,
                    url_scheme,
                    client_host,
                    path,
                    https_url,
                );
                if self.config.passive_mode {
                    None
                } else {
                    Some(HttpsRedirectAnswer {
                        status: HTTPS_REDIRECT_STATUS,
                        location: https_url.to_owned(),
                    })
                }
            }
        }
    }

    /// The violation emission (`send_https_violation_event`): a route's
    /// `require_https` fires `decorator_violation`
    /// (`decorator_type` `authentication`, `violation_type`
    /// `require_https`), the global arm fires `https_enforced`; both
    /// carry action `https_redirect`, `original_scheme`, and the
    /// redacted scheme-upgraded URL as `redirect_url`.
    fn observe_https_violation(
        &self,
        route_scoped: bool,
        original_scheme: &str,
        client_host: Option<&str>,
        path: &str,
        https_url: &str,
    ) {
        let Some(bus) = &self.events else {
            return;
        };
        let mut event = if route_scoped {
            let mut event = SecurityEvent::new(
                EVENT_DECORATOR_VIOLATION,
                client_host.unwrap_or_default(),
                "https_redirect",
                "Route requires HTTPS but request was HTTP",
                MIDDLEWARE_HANDLER_NAME,
            );
            event.decorator_type = Some(String::from("authentication"));
            event.metadata.insert(
                String::from("decorator_type"),
                serde_json::json!("authentication"),
            );
            event.metadata.insert(
                String::from("violation_type"),
                serde_json::json!("require_https"),
            );
            event
        } else {
            SecurityEvent::new(
                EVENT_HTTPS_ENFORCED,
                client_host.unwrap_or_default(),
                "https_redirect",
                "HTTP request redirected to HTTPS for security",
                MIDDLEWARE_HANDLER_NAME,
            )
        };
        event.metadata.insert(
            String::from("original_scheme"),
            serde_json::json!(original_scheme),
        );
        event.metadata.insert(
            String::from("redirect_url"),
            serde_json::json!(crate::redact::redact_url_for_display(
                https_url,
                &self.sensitive
            )),
        );
        event.endpoint = Some(crate::redact::redact_url_for_display(path, &self.sensitive));
        bus.send_event(&event);
    }
}

impl HttpsEnforcementStageBuilder {
    /// Set the global arm.
    #[must_use]
    pub const fn enforce_https(mut self, enforce_https: bool) -> Self {
        self.config.enforce_https = enforce_https;
        self
    }

    /// Add trusted-proxy entries (bare IPs or CIDR ranges); the build
    /// fails closed on an invalid one.
    #[must_use]
    pub fn trusted_proxies<I>(mut self, entries: I) -> Self
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        self.trusted_proxies
            .extend(entries.into_iter().map(|entry| entry.as_ref().to_owned()));
        self
    }

    /// Install the route `require_https` resolver.
    #[must_use]
    pub fn route_resolver(mut self, resolver: RouteHttpsResolver) -> Self {
        self.route_resolver = Some(resolver);
        self
    }

    /// Install the middleware-event bus (`send_https_violation_event`).
    #[must_use]
    pub fn events(mut self, bus: Arc<SecurityEventBus>) -> Self {
        self.events = Some(bus);
        self
    }

    /// Set the merged sensitive-name sets for the `redirect_url` /
    /// `endpoint` redaction.
    #[must_use]
    pub fn sensitive(mut self, sensitive: SensitiveNames) -> Self {
        self.sensitive = sensitive;
        self
    }

    /// Validate the trusted-proxy list and build the stage, failing closed.
    ///
    /// # Errors
    ///
    /// [`guard_core_engine::ip_gate::IpGateError`] naming the first
    /// invalid trusted-proxy entry.
    pub fn build(self) -> Result<HttpsEnforcementStage, guard_core_engine::ip_gate::IpGateError> {
        guard_core_engine::https_enforcement::HttpsEnforcementConfig::new(
            self.config.enforce_https,
            self.config.trust_x_forwarded_proto,
            self.trusted_proxies.iter().map(String::as_str),
        )?;
        Ok(HttpsEnforcementStage {
            config: self.config,
            trusted_proxies: self.trusted_proxies,
            route_resolver: self.route_resolver,
            events: self.events,
            sensitive: Arc::new(self.sensitive),
        })
    }
}

/// The `tower::Layer` carrying [`HttpsEnforcementStage`].
#[derive(Clone)]
pub struct HttpsEnforcementStageLayer {
    stage: HttpsEnforcementStage,
}

impl HttpsEnforcementStageLayer {
    /// Carry `stage` into every service this layer wraps.
    #[must_use]
    pub const fn new(stage: HttpsEnforcementStage) -> Self {
        Self { stage }
    }
}

impl fmt::Debug for HttpsEnforcementStageLayer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HttpsEnforcementStageLayer")
            .field("stage", &self.stage)
            .finish()
    }
}

impl<S> Layer<S> for HttpsEnforcementStageLayer {
    type Service = HttpsEnforcementStageService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        HttpsEnforcementStageService {
            inner,
            stage: self.stage.clone(),
        }
    }
}

/// The stage as a `tower::Service` around the inner service it wrapped.
#[derive(Clone)]
pub struct HttpsEnforcementStageService<S> {
    inner: S,
    stage: HttpsEnforcementStage,
}

/// The host half of an authority string (`host` or `host:port` or a
/// bracketed IPv6 literal, optionally `user:pass@`-prefixed in a URI
/// authority): the port is stripped and IPv6 brackets are removed, the
/// bare-address shape the reference compares trusted-proxy entries
/// against. A colon run that is not an all-digits port never splits, so
/// a bracket-less IPv6 text survives whole.
fn host_of_authority(value: &str) -> &str {
    let host_port = value.rsplit('@').next().unwrap_or_default();
    if let Some(rest) = host_port.strip_prefix('[') {
        return rest.split(']').next().unwrap_or(rest);
    }
    match host_port.split_once(':') {
        Some((host, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => host,
        _ => host_port,
    }
}

impl<S, B, ResBody> ::tower::Service<Request<B>> for HttpsEnforcementStageService<S>
where
    S: ::tower::Service<Request<B>, Response = Response<ResBody>>,
    S::Future: Send + 'static,
    ResBody: From<&'static str> + Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<S::Response, S::Error>> + Send>>;

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

    fn call(&mut self, request: Request<B>) -> Self::Future {
        let scheme = request.uri().scheme_str().unwrap_or("http").to_owned();
        let path = request.uri().path().to_owned();
        let host_and_port = request
            .uri()
            .authority()
            .map(|authority| authority.as_str().to_owned())
            .or_else(|| {
                request
                    .headers()
                    .get(http::header::HOST)
                    .and_then(|value| value.to_str().ok())
                    .map(ToOwned::to_owned)
            });
        // The connecting identity the trusted-proxy arm reads: the host
        // half of the authority (or Host header), port stripped, IPv6
        // brackets removed - the socket-host shape the reference's
        // `request.client_host` carries.
        let client_host = host_and_port
            .as_deref()
            .map(|value| host_of_authority(value).to_owned());
        let forwarded = request
            .headers()
            .get("x-forwarded-proto")
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned);
        let authority = host_and_port.unwrap_or_default();
        let query = request
            .uri()
            .query()
            .map(|q| format!("?{q}"))
            .unwrap_or_default();
        let https_url = format!("https://{authority}{path}{query}");

        let answer = self.stage.decide(
            &path,
            &scheme,
            client_host.as_deref(),
            forwarded.as_deref(),
            &https_url,
        );
        let Some(redirect) = answer else {
            return Box::pin(self.inner.call(request));
        };
        drop(request);
        let status = StatusCode::from_u16(redirect.status).expect("reference status");
        let mut response = Response::new(ResBody::from(""));
        *response.status_mut() = status;
        #[cfg(not(coverage))] // unreachable: the location composes only
        // URI-validated bytes (the http crate rejects controls and DEL in
        // authorities, paths, and queries, and the Host fallback passes
        // through a header-value str check), all of which are valid
        // header-value bytes, so from_str cannot reject it
        if let Ok(value) = http::HeaderValue::from_str(&redirect.location) {
            response.headers_mut().insert(http::header::LOCATION, value);
        }
        #[cfg(coverage)]
        response.headers_mut().insert(
            http::header::LOCATION,
            http::HeaderValue::from_str(&redirect.location)
                .expect("the composed location is a valid header value"),
        );
        Box::pin(async move { Ok(response) })
    }
}

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

    use ::tower::Service;

    fn stage() -> HttpsEnforcementStage {
        HttpsEnforcementStage::builder(HttpsEnforcementStageConfig::default())
            .enforce_https(true)
            .build()
            .expect("valid")
    }

    fn route_stage() -> HttpsEnforcementStage {
        HttpsEnforcementStage::builder(HttpsEnforcementStageConfig::default())
            .enforce_https(false)
            .route_resolver(Arc::new(|path: &str| match path {
                "/secure" => Some(true),
                "/open" => Some(false),
                _ => None,
            }))
            .build()
            .expect("valid")
    }

    #[test]
    fn decide_route_carries_the_direct_require_https_override() {
        let stage = HttpsEnforcementStage::builder(HttpsEnforcementStageConfig::default())
            .build()
            .expect("default config");
        // The carrier lane: require_https = true on a plain-http request
        // redirects exactly like the resolver-seam lane.
        let answer = stage
            .decide_route(
                "/private",
                "http",
                None,
                None,
                "https://host/private",
                Some(true),
            )
            .expect("route require_https redirects");
        assert_eq!(answer.status, HTTPS_REDIRECT_STATUS);
        assert_eq!(answer.location, "https://host/private");
        // require_https = false (the RouteConfig default, the unset shape)
        // leaves the global arm alone (default config: not enforced).
        assert!(
            stage
                .decide_route(
                    "/private",
                    "http",
                    None,
                    None,
                    "https://host/private",
                    Some(false)
                )
                .is_none()
        );
        // An already-https request passes.
        assert!(
            stage
                .decide_route(
                    "/private",
                    "https",
                    None,
                    None,
                    "https://host/private",
                    Some(true)
                )
                .is_none()
        );
    }

    #[test]
    fn global_enforcement_redirects_plain_http_and_passes_https() {
        let stage = stage();
        let answer = stage
            .decide("/x", "http", None, None, "https://host/x")
            .expect("redirected");
        assert_eq!(answer.status, 301);
        assert_eq!(answer.location, "https://host/x");
        assert!(stage.decide("/x", "https", None, None, "").is_none());
    }

    #[test]
    fn the_route_verdict_wins_both_ways() {
        let stage = route_stage();
        assert!(
            stage.decide("/secure", "http", None, None, "").is_some(),
            "a route requiring https redirects even with the global arm off"
        );
        assert!(
            stage.decide("/open", "http", None, None, "").is_none(),
            "a route opting out passes even under a global arm"
        );
        assert!(
            stage.decide("/other", "http", None, None, "").is_none(),
            "no route entry and a globally-off engine passes"
        );
    }

    #[test]
    fn passive_mode_observes_without_redirecting() {
        let stage = HttpsEnforcementStage::builder(HttpsEnforcementStageConfig {
            enforce_https: true,
            passive_mode: true,
            ..HttpsEnforcementStageConfig::default()
        })
        .build()
        .expect("valid");
        assert!(
            stage
                .decide("/x", "http", None, None, "https://host/x")
                .is_none(),
            "passive mode never answers the redirect"
        );
    }

    #[test]
    fn a_forged_forwarded_proto_never_upgrades() {
        let stage = HttpsEnforcementStage::builder(HttpsEnforcementStageConfig {
            enforce_https: true,
            trust_x_forwarded_proto: true,
            ..HttpsEnforcementStageConfig::default()
        })
        .trusted_proxies(["10.0.0.0/8"])
        .build()
        .expect("valid");
        assert!(
            stage
                .decide("/x", "http", Some("203.0.113.9"), Some("https"), "")
                .is_some(),
            "an untrusted client's header is ignored"
        );
        assert!(
            stage
                .decide("/x", "http", Some("10.1.2.3"), Some("https"), "")
                .is_none(),
            "a trusted proxy's header upgrades the request"
        );
    }

    #[test]
    fn the_builder_fails_closed_on_a_bad_proxy_entry() {
        let error = HttpsEnforcementStage::builder(HttpsEnforcementStageConfig::default())
            .trusted_proxies(["not-an-ip"])
            .build()
            .unwrap_err();
        assert_eq!(error.list, "trusted_proxies");
    }

    #[test]
    fn the_connecting_host_strips_the_port_and_the_v6_brackets() {
        // The `client_host` the trusted-proxy arm compares must be the
        // bare host: a port-bearing authority reads as the port string
        // otherwise, and no proxy entry can ever match it.
        assert_eq!(host_of_authority("10.1.2.3:8080"), "10.1.2.3");
        assert_eq!(host_of_authority("host.example"), "host.example");
        assert_eq!(host_of_authority("host.example:443"), "host.example");
        assert_eq!(host_of_authority("[2001:db8::1]:8080"), "2001:db8::1");
        assert_eq!(host_of_authority("[2001:db8::1]"), "2001:db8::1");
        assert_eq!(host_of_authority("2001:db8::1"), "2001:db8::1");
    }

    fn recording_bus() -> (
        Arc<std::sync::Mutex<Vec<SecurityEvent>>>,
        Arc<SecurityEventBus>,
    ) {
        let log = Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = Arc::clone(&log);
        let bus = Arc::new(SecurityEventBus::new(true).on_event(Arc::new(
            move |event: &SecurityEvent| {
                sink.lock().expect("sink").push(event.clone());
            },
        )));
        (log, bus)
    }

    #[test]
    fn the_violation_fires_the_route_and_global_event_split() {
        let (log, bus) = recording_bus();
        let stage = HttpsEnforcementStage::builder(HttpsEnforcementStageConfig::default())
            .enforce_https(true)
            .events(Arc::clone(&bus))
            .build()
            .expect("valid");
        // The global arm fires `https_enforced`.
        stage
            .decide("/x", "http", None, None, "https://host.example/x")
            .expect("redirected");
        // The route arm fires `decorator_violation`.
        let route_stage = HttpsEnforcementStage::builder(HttpsEnforcementStageConfig::default())
            .route_resolver(Arc::new(|_: &str| Some(true)))
            .events(bus)
            .build()
            .expect("valid");
        route_stage
            .decide("/secure", "http", None, None, "https://host.example/secure")
            .expect("redirected");

        let events = log.lock().expect("sink").clone();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].event_type, EVENT_HTTPS_ENFORCED);
        assert_eq!(events[0].action_taken, "https_redirect");
        assert_eq!(
            events[0].reason,
            "HTTP request redirected to HTTPS for security"
        );
        assert_eq!(
            events[0].metadata["original_scheme"], "http",
            "the reference metadata rides along"
        );
        assert_eq!(
            events[0].metadata["redirect_url"],
            serde_json::json!("https://host.example/x")
        );
        assert_eq!(events[1].event_type, EVENT_DECORATOR_VIOLATION);
        assert_eq!(events[1].decorator_type.as_deref(), Some("authentication"));
        assert_eq!(events[1].metadata["violation_type"], "require_https");
        assert_eq!(
            events[1].reason,
            "Route requires HTTPS but request was HTTP"
        );
    }

    #[test]
    fn passive_mode_still_observes_the_https_violation() {
        // The reference emits the event before its passive-mode branch.
        let (log, bus) = recording_bus();
        let stage = HttpsEnforcementStage::builder(HttpsEnforcementStageConfig {
            enforce_https: true,
            passive_mode: true,
            ..HttpsEnforcementStageConfig::default()
        })
        .events(bus)
        .build()
        .expect("valid");
        assert!(
            stage
                .decide("/x", "http", None, None, "https://host/x")
                .is_none()
        );
        let events = log.lock().expect("sink").clone();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, EVENT_HTTPS_ENFORCED);
    }

    #[test]
    fn the_sensitive_sets_redact_the_emitted_redirect_target() {
        // The `sensitive` builder seam feeds the `redirect_url` and
        // `endpoint` redaction the reference event carries: an extra
        // param name nobody defaults to still redacts its value.
        let (log, bus) = recording_bus();
        let stage = HttpsEnforcementStage::builder(HttpsEnforcementStageConfig::default())
            .enforce_https(true)
            .sensitive(SensitiveNames::new(
                None,
                Some(&std::collections::HashSet::from([String::from(
                    "guard_test_param",
                )])),
                None,
            ))
            .events(bus)
            .build()
            .expect("valid");
        stage
            .decide(
                "/x?guard_test_param=leaked",
                "http",
                None,
                None,
                "https://host.example/x?guard_test_param=leaked",
            )
            .expect("redirected");
        let events = log.lock().expect("sink").clone();
        assert_eq!(events.len(), 1);
        assert_eq!(
            events[0].metadata["redirect_url"],
            serde_json::json!("https://host.example/x?guard_test_param=[REDACTED]")
        );
        assert_eq!(
            events[0].endpoint.as_deref(),
            Some("/x?guard_test_param=[REDACTED]")
        );
    }

    /// The future the plumbing tests drive.
    fn block_on<F: Future>(future: F) -> F::Output {
        let mut future = std::pin::pin!(future);
        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        loop {
            match future.as_mut().poll(&mut cx) {
                Poll::Ready(output) => return output,
                Poll::Pending => std::hint::spin_loop(),
            }
        }
    }

    #[derive(Clone)]
    struct Inner {
        calls: Arc<std::sync::atomic::AtomicUsize>,
    }

    impl Inner {
        fn new() -> Self {
            Self {
                calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            }
        }
    }

    impl ::tower::Service<Request<&'static str>> for Inner {
        type Response = Response<&'static str>;
        type Error = Infallible;
        type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Infallible>> + Send>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, _request: Request<&'static str>) -> Self::Future {
            self.calls
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            Box::pin(async move { Ok(Response::new("inner")) })
        }
    }

    fn request_to(uri: &str) -> Request<&'static str> {
        Request::builder().uri(uri).body("body").expect("request")
    }

    #[test]
    fn the_layer_redirects_http_and_forwards_https() {
        let layer = HttpsEnforcementStageLayer::new(stage());
        let inner = Inner::new();
        let mut service = ::tower::ServiceBuilder::new()
            .layer(layer)
            .service(inner.clone());

        let response =
            block_on(service.call(request_to("http://host/private?q=1"))).expect("ready");
        assert_eq!(response.status(), StatusCode::MOVED_PERMANENTLY);
        assert_eq!(
            response
                .headers()
                .get(http::header::LOCATION)
                .expect("location"),
            "https://host/private?q=1"
        );
        assert_eq!(
            inner.calls.load(std::sync::atomic::Ordering::Relaxed),
            0,
            "the redirected request never hits the inner service"
        );

        let response = block_on(service.call(request_to("https://host/private"))).expect("ready");
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.body(), &"inner");
    }

    #[test]
    fn the_stage_and_layer_render_debug_and_the_service_readies() {
        let built = stage();
        assert!(format!("{built:?}").starts_with("HttpsEnforcementStage"));

        let layer = HttpsEnforcementStageLayer::new(stage());
        assert!(format!("{layer:?}").starts_with("HttpsEnforcementStageLayer"));

        let mut service = ::tower::ServiceBuilder::new()
            .layer(layer)
            .service(Inner::new());
        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        assert_eq!(
            ::tower::Service::<Request<&'static str>>::poll_ready(&mut service, &mut cx),
            Poll::Ready(Ok(()))
        );
    }

    #[test]
    fn a_path_only_request_takes_the_host_header() {
        let layer = HttpsEnforcementStageLayer::new(stage());
        let mut service = ::tower::ServiceBuilder::new()
            .layer(layer)
            .service(Inner::new());

        // No authority in the URI: the Host header (port included) composes
        // the redirect target, and the client host feeds the proxy arm. The
        // forwarded header rides along (ignored: the stage trusts no proxy).
        let request = Request::builder()
            .uri("/private")
            .header(http::header::HOST, "host.example:8443")
            .header("x-forwarded-proto", "https")
            .body("body")
            .expect("request");
        let response = block_on(service.call(request)).expect("ready");
        assert_eq!(response.status(), StatusCode::MOVED_PERMANENTLY);
        assert_eq!(
            response
                .headers()
                .get(http::header::LOCATION)
                .expect("location"),
            "https://host.example:8443/private"
        );
    }

    /// An inner service whose first answer waits one poll before replying.
    #[derive(Clone)]
    struct InnerYieldsOnce {
        yielded: Arc<std::sync::atomic::AtomicBool>,
    }

    struct YieldOnce {
        yielded: bool,
    }

    impl Future for YieldOnce {
        type Output = ();

        fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
            if self.yielded {
                Poll::Ready(())
            } else {
                self.yielded = true;
                cx.waker().wake_by_ref();
                Poll::Pending
            }
        }
    }

    impl ::tower::Service<Request<&'static str>> for InnerYieldsOnce {
        type Response = Response<&'static str>;
        type Error = Infallible;
        type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Infallible>> + Send>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, _request: Request<&'static str>) -> Self::Future {
            let yielded = Arc::clone(&self.yielded);
            Box::pin(async move {
                YieldOnce {
                    yielded: yielded.load(std::sync::atomic::Ordering::Relaxed),
                }
                .await;
                // record that the second poll answered
                yielded.store(true, std::sync::atomic::Ordering::Relaxed);
                Ok(Response::new("inner"))
            })
        }
    }

    #[test]
    fn the_helper_block_on_spins_a_pending_future_once() {
        struct PendingOnce {
            polled: std::cell::Cell<bool>,
        }
        impl Future for PendingOnce {
            type Output = u8;

            fn poll(self: std::pin::Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<u8> {
                if self.polled.get() {
                    Poll::Ready(7)
                } else {
                    self.polled.set(true);
                    Poll::Pending
                }
            }
        }
        let future = PendingOnce {
            polled: std::cell::Cell::new(false),
        };
        assert_eq!(block_on(future), 7, "the second poll answers");

        // The plumbing future yields once too: the block_on loop spins a
        // Pending service answer before it resolves. The yielding inner
        // then sees the whole stage surface: pass-through, a redirect, and
        // a Host fallback with a query and a forwarded header.
        let layer = HttpsEnforcementStageLayer::new(stage());
        let mut service = ::tower::ServiceBuilder::new()
            .layer(layer)
            .service(InnerYieldsOnce {
                yielded: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            });
        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        assert_eq!(
            ::tower::Service::<Request<&'static str>>::poll_ready(&mut service, &mut cx),
            Poll::Ready(Ok(()))
        );

        let response = block_on(service.call(request_to("https://host/private"))).expect("ready");
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.body(), &"inner");

        let response =
            block_on(service.call(request_to("http://host/private?q=1"))).expect("ready");
        assert_eq!(response.status(), StatusCode::MOVED_PERMANENTLY);

        let request = Request::builder()
            .uri("/private?q=1")
            .header(http::header::HOST, "host.example:8443")
            .header("x-forwarded-proto", "https")
            .body("body")
            .expect("request");
        let response = block_on(service.call(request)).expect("ready");
        assert_eq!(response.status(), StatusCode::MOVED_PERMANENTLY);
    }
}