Skip to main content

ntex/web/
guard.rs

1//! Route match guards.
2//!
3//! Guards are one of the ways how ntex web router chooses a
4//! handler service. In essence it is just a function that accepts a
5//! reference to a `RequestHead` instance and returns a boolean.
6//! It is possible to add guards to *scopes*, *resources*
7//! and *routes*. ntex provide several guards by default, like various
8//! http methods, header, etc. To become a guard, type must implement `Guard`
9//! trait. Simple functions can be used as guards as well, see [`fn_guard`].
10//!
11//! Multiple guards on the same route, resource, or scope must all match.
12//!
13//! Guards can not modify the request object. But it is possible
14//! to store extra attributes on a request by using the `Extensions` container.
15//! Extensions containers are available via the `RequestHead::extensions()` method.
16//!
17//! ```rust
18//! use ntex::web::{self, guard, App, HttpResponse};
19//!
20//! fn main() {
21//!     App::default().service(web::resource("/index.html").route(
22//!         web::route()
23//!              .guard(guard::Post())
24//!              .guard(guard::fn_guard(|head| head.headers.contains_key("x-api-key")))
25//!              .to(async || { HttpResponse::Ok() }))
26//!     );
27//! }
28//! ```
29#![allow(non_snake_case)]
30
31use std::{borrow::Cow, fmt};
32
33use urly::Url;
34
35use crate::http::{Method, RequestHead, header};
36
37/// Trait defines resource guards. Guards are used for route selection.
38///
39/// Guards can not modify the request object. But it is possible
40/// to store extra attributes on a request by using the `Extensions` container.
41/// Extensions containers are available via the `RequestHead::extensions()` method.
42pub trait Guard {
43    /// Check if request matches predicate
44    fn check(&self, request: &RequestHead) -> bool;
45
46    /// Debug format
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.debug_tuple("Guard").finish()
49    }
50}
51
52/// Create guard object for supplied function.
53///
54/// ```rust
55/// use ntex::web::{self, guard, App, HttpResponse};
56///
57/// fn main() {
58///     App::default().service(web::resource("/index.html").route(
59///         web::route()
60///             .guard(
61///                 guard::fn_guard(
62///                     |req| req.headers()
63///                              .contains_key("content-type")))
64///             .to(async || { HttpResponse::MethodNotAllowed() }))
65///     );
66/// }
67/// ```
68pub fn fn_guard<F>(f: F) -> impl Guard
69where
70    F: Fn(&RequestHead) -> bool,
71{
72    FnGuard(f)
73}
74
75struct FnGuard<F: Fn(&RequestHead) -> bool>(F);
76
77impl<F> Guard for FnGuard<F>
78where
79    F: Fn(&RequestHead) -> bool,
80{
81    fn check(&self, head: &RequestHead) -> bool {
82        (self.0)(head)
83    }
84
85    /// Debug format
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        f.debug_tuple("FnGuard")
88            .field(&std::any::type_name::<F>())
89            .finish()
90    }
91}
92
93impl<F> fmt::Debug for FnGuard<F>
94where
95    F: Fn(&RequestHead) -> bool,
96{
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        Guard::fmt(self, f)
99    }
100}
101
102impl<F> Guard for F
103where
104    F: Fn(&RequestHead) -> bool,
105{
106    fn check(&self, head: &RequestHead) -> bool {
107        (self)(head)
108    }
109}
110
111/// Return guard that matches if any of supplied guards.
112///
113/// ```rust
114/// use ntex::web::{self, guard, App, HttpResponse};
115///
116/// fn main() {
117///     App::default().service(web::resource("/index.html").route(
118///         web::route()
119///              .guard(guard::Any(guard::Get()).or(guard::Post()))
120///              .to(async || { HttpResponse::MethodNotAllowed() }))
121///     );
122/// }
123/// ```
124pub fn Any<F: Guard + 'static>(guard: F) -> AnyGuard {
125    AnyGuard(vec![Box::new(guard)])
126}
127
128#[derive(Default)]
129/// Matches any of supplied guards match.
130pub struct AnyGuard(pub Vec<Box<dyn Guard>>);
131
132impl AnyGuard {
133    #[must_use]
134    /// Add guard to a list of guards to check.
135    pub fn or<F: Guard + 'static>(mut self, guard: F) -> Self {
136        self.0.push(Box::new(guard));
137        self
138    }
139}
140
141impl Guard for AnyGuard {
142    fn check(&self, req: &RequestHead) -> bool {
143        for p in &self.0 {
144            if p.check(req) {
145                return true;
146            }
147        }
148        false
149    }
150
151    /// Debug format
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        write!(f, "AnyGuard(")?;
154        self.0.iter().for_each(|t| {
155            let _ = t.fmt(f);
156        });
157        write!(f, ")")
158    }
159}
160
161impl fmt::Debug for AnyGuard {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        Guard::fmt(self, f)
164    }
165}
166
167/// Return guard that matches if all of the supplied guards.
168///
169/// ```rust
170/// use ntex::web::{self, guard, App, HttpResponse};
171///
172/// fn main() {
173///     App::default().service(web::resource("/index.html").route(
174///         web::route()
175///             .guard(
176///                 guard::All(guard::Get()).and(guard::Header("content-type", "text/plain")))
177///             .to(async || { HttpResponse::MethodNotAllowed() }))
178///     );
179/// }
180/// ```
181pub fn All<F: Guard + 'static>(guard: F) -> AllGuard {
182    AllGuard(vec![Box::new(guard)])
183}
184
185#[derive(Default)]
186/// Matches all of supplied guards..
187pub struct AllGuard(pub(super) Vec<Box<dyn Guard>>);
188
189impl AllGuard {
190    #[must_use]
191    /// Add new guard to the list of guards to check.
192    pub fn and<F: Guard + 'static>(mut self, guard: F) -> Self {
193        self.0.push(Box::new(guard));
194        self
195    }
196
197    /// Add guard to a list of guards to check.
198    pub fn add<F: Guard + 'static>(&mut self, guard: F) {
199        self.0.push(Box::new(guard));
200    }
201}
202
203impl Guard for AllGuard {
204    fn check(&self, request: &RequestHead) -> bool {
205        for p in &self.0 {
206            if !p.check(request) {
207                return false;
208            }
209        }
210        true
211    }
212
213    /// Debug format
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        write!(f, "AllGuard(")?;
216        self.0.iter().for_each(|t| {
217            let _ = t.fmt(f);
218        });
219        write!(f, ")")
220    }
221}
222
223impl fmt::Debug for AllGuard {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        Guard::fmt(self, f)
226    }
227}
228
229/// Return guard that matches if supplied guard does not match.
230pub fn Not<F: Guard + 'static>(guard: F) -> NotGuard {
231    NotGuard(Box::new(guard))
232}
233
234#[doc(hidden)]
235pub struct NotGuard(Box<dyn Guard>);
236
237impl Guard for NotGuard {
238    fn check(&self, request: &RequestHead) -> bool {
239        !self.0.check(request)
240    }
241
242    /// Debug format
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        write!(f, "NotGuard(")?;
245        self.0.fmt(f)?;
246        write!(f, ")")
247    }
248}
249
250impl fmt::Debug for NotGuard {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        Guard::fmt(self, f)
253    }
254}
255
256/// Http method guard
257#[doc(hidden)]
258#[derive(Debug)]
259pub struct MethodGuard(Method);
260
261impl Guard for MethodGuard {
262    fn check(&self, request: &RequestHead) -> bool {
263        request.method == self.0
264    }
265
266    /// Debug format
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        fmt::Debug::fmt(self, f)
269    }
270}
271
272/// Guard to match *GET* http method
273pub fn Get() -> MethodGuard {
274    MethodGuard(Method::GET)
275}
276
277/// Predicate to match *POST* http method
278pub fn Post() -> MethodGuard {
279    MethodGuard(Method::POST)
280}
281
282/// Predicate to match *PUT* http method
283pub fn Put() -> MethodGuard {
284    MethodGuard(Method::PUT)
285}
286
287/// Predicate to match *DELETE* http method
288pub fn Delete() -> MethodGuard {
289    MethodGuard(Method::DELETE)
290}
291
292/// Predicate to match *HEAD* http method
293pub fn Head() -> MethodGuard {
294    MethodGuard(Method::HEAD)
295}
296
297/// Predicate to match *OPTIONS* http method
298pub fn Options() -> MethodGuard {
299    MethodGuard(Method::OPTIONS)
300}
301
302/// Predicate to match *CONNECT* http method
303pub fn Connect() -> MethodGuard {
304    MethodGuard(Method::CONNECT)
305}
306
307/// Predicate to match *PATCH* http method
308pub fn Patch() -> MethodGuard {
309    MethodGuard(Method::PATCH)
310}
311
312/// Predicate to match *TRACE* http method
313pub fn Trace() -> MethodGuard {
314    MethodGuard(Method::TRACE)
315}
316
317/// Predicate to match *QUERY* http method
318pub fn Query() -> MethodGuard {
319    MethodGuard(Method::QUERY)
320}
321
322/// Predicate to match specified http method
323pub fn Method(method: Method) -> MethodGuard {
324    MethodGuard(method)
325}
326
327/// Return predicate that matches if request contains specified header and
328/// value.
329pub fn Header(name: &'static str, value: &'static str) -> HeaderGuard {
330    HeaderGuard(
331        header::HeaderName::try_from(name).unwrap(),
332        header::HeaderValue::from_static(value),
333    )
334}
335
336#[doc(hidden)]
337#[derive(Debug)]
338pub struct HeaderGuard(header::HeaderName, header::HeaderValue);
339
340impl Guard for HeaderGuard {
341    fn check(&self, req: &RequestHead) -> bool {
342        if let Some(val) = req.headers.get(&self.0) {
343            return val == self.1;
344        }
345        false
346    }
347
348    /// Debug format
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        fmt::Debug::fmt(self, f)
351    }
352}
353
354/// Return predicate that matches if request contains specified Host name.
355///
356/// ```rust
357/// use ntex::web::{self, guard::Host, App, HttpResponse};
358///
359/// fn main() {
360///     App::default().service(
361///         web::resource("/index.html")
362///             .guard(Host("www.rust-lang.org"))
363///             .to(async || { HttpResponse::MethodNotAllowed() })
364///     );
365/// }
366/// ```
367pub fn Host<H: AsRef<str>>(host: H) -> HostGuard {
368    HostGuard(host.as_ref().to_string(), None)
369}
370
371fn get_host_uri(req: &RequestHead) -> Option<Cow<'_, Url>> {
372    // the authority of an absolute-form target takes precedence over `Host`,
373    // see RFC 9112 section 3.2.2
374    if req.uri.authority().is_some() {
375        return Some(Cow::Borrowed(&req.uri));
376    }
377    let host = req.headers.get(header::HOST)?.to_str().ok()?;
378    if host.contains("://") {
379        Url::try_from(host).ok().map(Cow::Owned)
380    } else {
381        Url::parse(host).ok().map(Cow::Owned)
382    }
383}
384
385#[doc(hidden)]
386#[derive(Debug)]
387pub struct HostGuard(String, Option<String>);
388
389impl HostGuard {
390    #[must_use]
391    /// Set request scheme to match.
392    ///
393    /// The scheme is taken from the request uri if it is in absolute-form, from
394    /// the `:scheme` pseudo-header of an HTTP/2 request, or from the `Host`
395    /// header value otherwise. The guard fails closed: a request
396    /// that carries no scheme does not match. Ordinary HTTP/1 origin-form requests
397    /// (`GET /path` with `Host: example.com`) and authority-form `CONNECT`
398    /// requests carry no scheme, so a guard with a scheme rejects them. The
399    /// scheme is not derived from the connection, so this does not tell whether
400    /// the request arrived over TLS; do not rely on it for security decisions.
401    pub fn scheme<H: AsRef<str>>(mut self, scheme: H) -> HostGuard {
402        self.1 = Some(scheme.as_ref().to_string());
403        self
404    }
405
406    fn matches(&self, host: Option<&str>, scheme: Option<&str>) -> bool {
407        host.is_some_and(|h| self.0.eq_ignore_ascii_case(h))
408            && self
409                .1
410                .as_ref()
411                .is_none_or(|s| scheme.is_some_and(|r| s.eq_ignore_ascii_case(r)))
412    }
413}
414
415impl Guard for HostGuard {
416    fn check(&self, req: &RequestHead) -> bool {
417        // an HTTP/2 request carries its authority in `:authority`, which takes
418        // precedence over `Host`, see RFC 9113 section 8.3.1
419        if req.uri.authority().is_none()
420            && let Some(authority) = req.authority.as_deref()
421        {
422            let uri = Url::from_target_parts(None, Some(authority), "").ok();
423            return self.matches(uri.as_ref().and_then(Url::host), req.scheme.as_deref());
424        }
425        let Some(uri) = get_host_uri(req) else {
426            return false;
427        };
428        self.matches(uri.host(), uri.scheme_str())
429    }
430
431    /// Debug format
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        fmt::Debug::fmt(self, f)
434    }
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440    use crate::web::test::TestRequest;
441
442    /// STATEMENT: Header guards require an existing header with the expected value.
443    ///
444    /// HOW:
445    /// - Check matching, mismatched, and absent headers against a chunked request.
446    /// - Assert only the matching value passes.
447    #[test]
448    fn test_header() {
449        let req = TestRequest::with_header(header::TRANSFER_ENCODING, "chunked").to_http_request();
450
451        let pred = Header("transfer-encoding", "chunked");
452        assert!(pred.check(req.head()));
453
454        let pred = Header("transfer-encoding", "other");
455        assert!(!pred.check(req.head()));
456
457        let pred = Header("content-type", "other");
458        assert!(!pred.check(req.head()));
459    }
460
461    /// STATEMENT: Host guards match a bare host, but a required scheme fails closed when the request carries none.
462    ///
463    /// HOW:
464    /// - Supply `www.rust-lang.org` in `Host` and check guards with and without a scheme.
465    /// - Assert the matching host passes without a scheme, `.scheme("https")` rejects it, and unrelated hosts fail.
466    #[test]
467    fn test_host() {
468        let req = TestRequest::default()
469            .header(
470                header::HOST,
471                header::HeaderValue::from_static("www.rust-lang.org"),
472            )
473            .to_http_request();
474
475        let pred = Host("www.rust-lang.org");
476        assert!(pred.check(req.head()));
477
478        // the request carries no scheme, so a scheme check fails closed
479        let pred = Host("www.rust-lang.org").scheme("https");
480        assert!(!pred.check(req.head()));
481
482        let pred = Host("blog.rust-lang.org");
483        assert!(!pred.check(req.head()));
484
485        let pred = Host("blog.rust-lang.org").scheme("https");
486        assert!(!pred.check(req.head()));
487
488        let pred = Host("crates.io");
489        assert!(!pred.check(req.head()));
490
491        let pred = Host("localhost");
492        assert!(!pred.check(req.head()));
493    }
494
495    /// STATEMENT: Host guards enforce a supplied request scheme as well as the hostname.
496    ///
497    /// HOW:
498    /// - Supply an HTTPS host value and check matching, omitted, and mismatched guard schemes.
499    /// - Assert unrelated hosts fail.
500    #[test]
501    fn test_host_scheme() {
502        let req = TestRequest::default()
503            .header(
504                header::HOST,
505                header::HeaderValue::from_static("https://www.rust-lang.org"),
506            )
507            .to_http_request();
508
509        let pred = Host("www.rust-lang.org").scheme("https");
510        assert!(pred.check(req.head()));
511
512        let pred = Host("www.rust-lang.org");
513        assert!(pred.check(req.head()));
514
515        let pred = Host("www.rust-lang.org").scheme("http");
516        assert!(!pred.check(req.head()));
517
518        let pred = Host("blog.rust-lang.org");
519        assert!(!pred.check(req.head()));
520
521        let pred = Host("blog.rust-lang.org").scheme("https");
522        assert!(!pred.check(req.head()));
523
524        let pred = Host("crates.io").scheme("https");
525        assert!(!pred.check(req.head()));
526
527        let pred = Host("localhost");
528        assert!(!pred.check(req.head()));
529    }
530
531    /// STATEMENT: Host guards use CONNECT authorities, not double-slash origin paths.
532    ///
533    /// HOW:
534    /// - Match an authority-form CONNECT request without a `Host` header.
535    /// - Check matching/nonmatching hosts, that a scheme check fails because the target carries no scheme,
536    ///   and confirm an origin path does not supply a host.
537    #[test]
538    fn test_host_without_header() {
539        let req = TestRequest::default()
540            .method(crate::http::Method::CONNECT)
541            .uri("www.rust-lang.org:443")
542            .to_http_request();
543
544        let pred = Host("www.rust-lang.org");
545        assert!(pred.check(req.head()));
546
547        let pred = Host("www.rust-lang.org").scheme("https");
548        assert!(!pred.check(req.head()));
549
550        let pred = Host("blog.rust-lang.org");
551        assert!(!pred.check(req.head()));
552
553        let pred = Host("blog.rust-lang.org").scheme("https");
554        assert!(!pred.check(req.head()));
555
556        let pred = Host("crates.io");
557        assert!(!pred.check(req.head()));
558
559        let pred = Host("localhost");
560        assert!(!pred.check(req.head()));
561
562        let req = TestRequest::with_uri("//www.rust-lang.org").to_http_request();
563        assert!(!Host("www.rust-lang.org").check(req.head()));
564    }
565
566    /// STATEMENT: Absolute request targets override `Host`, while malformed host values do not match.
567    ///
568    /// HOW:
569    /// - Supply conflicting absolute-target and header authorities and assert target host/scheme wins.
570    /// - Check a host with a port matches and a host containing a path does not.
571    #[test]
572    fn test_host_absolute_form() {
573        // the target authority takes precedence over `Host`
574        let req = TestRequest::with_uri("http://www.rust-lang.org/p")
575            .header(header::HOST, "crates.io")
576            .to_http_request();
577        assert!(Host("www.rust-lang.org").scheme("http").check(req.head()));
578        assert!(!Host("www.rust-lang.org").scheme("https").check(req.head()));
579        assert!(!Host("crates.io").check(req.head()));
580
581        let req = TestRequest::default()
582            .header(header::HOST, "www.rust-lang.org:8080")
583            .to_http_request();
584        assert!(Host("www.rust-lang.org").check(req.head()));
585
586        let req = TestRequest::default()
587            .header(header::HOST, "www.rust-lang.org/p")
588            .to_http_request();
589        assert!(!Host("www.rust-lang.org").check(req.head()));
590    }
591
592    /// STATEMENT: The HTTP/2 `:authority` and `:scheme` take precedence over `Host`.
593    ///
594    /// HOW:
595    /// - Set the head authority and scheme next to a conflicting `Host` header and assert
596    ///   the host and scheme come from the pseudo-headers only.
597    /// - Set an empty authority and assert no host matches, then clear it and assert
598    ///   `Host` is used again.
599    #[test]
600    fn test_host_h2_authority() {
601        let mut req = TestRequest::default()
602            .header(header::HOST, "crates.io")
603            .to_http_request();
604        req.head_mut().scheme = Some("https".into());
605        req.head_mut().authority = Some("www.rust-lang.org:8443".into());
606        assert!(Host("www.rust-lang.org").check(req.head()));
607        assert!(Host("www.rust-lang.org").scheme("https").check(req.head()));
608        assert!(!Host("www.rust-lang.org").scheme("http").check(req.head()));
609        assert!(!Host("crates.io").check(req.head()));
610
611        req.head_mut().authority = Some("".into());
612        assert!(!Host("crates.io").check(req.head()));
613        assert!(!Host("").check(req.head()));
614
615        req.head_mut().authority = None;
616        assert!(Host("crates.io").check(req.head()));
617    }
618
619    /// STATEMENT: Method guards accept their own HTTP method and reject other methods.
620    ///
621    /// HOW:
622    /// - Build requests for GET, POST, PUT, DELETE, HEAD, OPTIONS, CONNECT, PATCH, TRACE, and QUERY.
623    /// - Check each corresponding guard against matching and mismatched requests.
624    #[test]
625    fn test_methods() {
626        let req = TestRequest::default().to_http_request();
627        let req2 = TestRequest::default()
628            .method(Method::POST)
629            .to_http_request();
630
631        assert!(Get().check(req.head()));
632        assert!(!Get().check(req2.head()));
633        assert!(Post().check(req2.head()));
634        assert!(!Post().check(req.head()));
635
636        let r = TestRequest::default().method(Method::PUT).to_http_request();
637        assert!(Put().check(r.head()));
638        assert!(!Put().check(req.head()));
639
640        let r = TestRequest::default()
641            .method(Method::DELETE)
642            .to_http_request();
643        assert!(Delete().check(r.head()));
644        assert!(!Delete().check(req.head()));
645
646        let r = TestRequest::default()
647            .method(Method::HEAD)
648            .to_http_request();
649        assert!(Head().check(r.head()));
650        assert!(!Head().check(req.head()));
651
652        let r = TestRequest::default()
653            .method(Method::OPTIONS)
654            .to_http_request();
655        assert!(Options().check(r.head()));
656        assert!(!Options().check(req.head()));
657
658        let r = TestRequest::default()
659            .method(Method::CONNECT)
660            .to_http_request();
661        assert!(Connect().check(r.head()));
662        assert!(!Connect().check(req.head()));
663
664        let r = TestRequest::default()
665            .method(Method::PATCH)
666            .to_http_request();
667        assert!(Patch().check(r.head()));
668        assert!(!Patch().check(req.head()));
669
670        let r = TestRequest::default()
671            .method(Method::TRACE)
672            .to_http_request();
673        assert!(Trace().check(r.head()));
674        assert!(!Trace().check(req.head()));
675
676        let r = TestRequest::default()
677            .method(Method::QUERY)
678            .to_http_request();
679        assert!(Query().check(r.head()));
680        assert!(!Query().check(req.head()));
681    }
682
683    /// STATEMENT: `Not`, `All`, and `Any` compose method guards with their expected Boolean semantics.
684    ///
685    /// HOW:
686    /// - Check negated, conjunctive, and disjunctive guards against a TRACE request.
687    /// - Assert positive and negative outcomes and each composite guard's debug identity.
688    #[test]
689    fn test_preds() {
690        let r = TestRequest::default()
691            .method(Method::TRACE)
692            .to_http_request();
693
694        assert!(Not(Get()).check(r.head()));
695        assert!(!Not(Trace()).check(r.head()));
696        assert!(format!("{:?}", Not(Get())).contains("NotGuard"));
697
698        assert!(All(Trace()).and(Trace()).check(r.head()));
699        assert!(!All(Get()).and(Trace()).check(r.head()));
700        assert!(format!("{:?}", All(Get())).contains("AllGuard"));
701
702        assert!(Any(Get()).or(Trace()).check(r.head()));
703        assert!(!Any(Get()).or(Get()).check(r.head()));
704        assert!(format!("{:?}", Any(Get())).contains("AnyGuard"));
705    }
706
707    /// STATEMENT: Function guards and closures can inspect request headers.
708    ///
709    /// HOW:
710    /// - Check a content-type predicate through `fn_guard` and a direct closure.
711    /// - Assert both pass and `FnGuard` debug output identifies the wrapper.
712    #[test]
713    fn test_fn_guard() {
714        let req = TestRequest::with_header(header::CONTENT_TYPE, "text/plain").to_http_request();
715
716        let g = fn_guard(|req| req.headers().contains_key("content-type"));
717        assert!(g.check(req.head()));
718        let g = FnGuard(|req| req.headers().contains_key("content-type"));
719        assert!(format!("{g:?}").contains("FnGuard"));
720
721        let g = |req: &RequestHead| req.headers().contains_key("content-type");
722        assert!(g.check(req.head()));
723    }
724
725    /// STATEMENT: Composite guard debug output includes built-in and custom guard identities.
726    ///
727    /// HOW:
728    /// - Compose a header guard, host guard, and custom `Guard` implementation with `Any`.
729    /// - Format it and assert all three guard identities are present.
730    #[test]
731    fn test_guard_debug() {
732        struct Custom;
733
734        impl Guard for Custom {
735            fn check(&self, _: &RequestHead) -> bool {
736                true
737            }
738        }
739
740        let guard = Any(Header("content-type", "text/plain"))
741            .or(Host("localhost"))
742            .or(Custom);
743        let s = format!("{guard:?}");
744        assert!(s.contains("HeaderGuard"), "{s}");
745        assert!(s.contains("HostGuard"), "{s}");
746        assert!(s.contains("Guard"), "{s}");
747    }
748
749    /// STATEMENT: Invalid or path-only `Host` values cannot satisfy a hostname guard.
750    ///
751    /// HOW:
752    /// - Build requests with a space-containing host and a path-only host.
753    /// - Assert neither matches `Host("localhost")`.
754    #[test]
755    fn test_host_without_host_name() {
756        let req = TestRequest::default()
757            .header(header::HOST, header::HeaderValue::from_static("bad host"))
758            .to_http_request();
759        assert!(!Host("localhost").check(req.head()));
760
761        let req = TestRequest::default()
762            .header(header::HOST, header::HeaderValue::from_static("/path"))
763            .to_http_request();
764        assert!(!Host("localhost").check(req.head()));
765    }
766}