1#![allow(non_snake_case)]
30
31use std::{borrow::Cow, fmt};
32
33use urly::Url;
34
35use crate::http::{Method, RequestHead, header};
36
37pub trait Guard {
43 fn check(&self, request: &RequestHead) -> bool;
45
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 f.debug_tuple("Guard").finish()
49 }
50}
51
52pub 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 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
111pub fn Any<F: Guard + 'static>(guard: F) -> AnyGuard {
125 AnyGuard(vec![Box::new(guard)])
126}
127
128#[derive(Default)]
129pub struct AnyGuard(pub Vec<Box<dyn Guard>>);
131
132impl AnyGuard {
133 #[must_use]
134 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 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
167pub fn All<F: Guard + 'static>(guard: F) -> AllGuard {
182 AllGuard(vec![Box::new(guard)])
183}
184
185#[derive(Default)]
186pub struct AllGuard(pub(super) Vec<Box<dyn Guard>>);
188
189impl AllGuard {
190 #[must_use]
191 pub fn and<F: Guard + 'static>(mut self, guard: F) -> Self {
193 self.0.push(Box::new(guard));
194 self
195 }
196
197 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 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
229pub 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 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#[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 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 fmt::Debug::fmt(self, f)
269 }
270}
271
272pub fn Get() -> MethodGuard {
274 MethodGuard(Method::GET)
275}
276
277pub fn Post() -> MethodGuard {
279 MethodGuard(Method::POST)
280}
281
282pub fn Put() -> MethodGuard {
284 MethodGuard(Method::PUT)
285}
286
287pub fn Delete() -> MethodGuard {
289 MethodGuard(Method::DELETE)
290}
291
292pub fn Head() -> MethodGuard {
294 MethodGuard(Method::HEAD)
295}
296
297pub fn Options() -> MethodGuard {
299 MethodGuard(Method::OPTIONS)
300}
301
302pub fn Connect() -> MethodGuard {
304 MethodGuard(Method::CONNECT)
305}
306
307pub fn Patch() -> MethodGuard {
309 MethodGuard(Method::PATCH)
310}
311
312pub fn Trace() -> MethodGuard {
314 MethodGuard(Method::TRACE)
315}
316
317pub fn Query() -> MethodGuard {
319 MethodGuard(Method::QUERY)
320}
321
322pub fn Method(method: Method) -> MethodGuard {
324 MethodGuard(method)
325}
326
327pub 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 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350 fmt::Debug::fmt(self, f)
351 }
352}
353
354pub 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 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 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 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 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 #[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 #[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 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 #[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 #[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 #[test]
572 fn test_host_absolute_form() {
573 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 #[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 #[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 #[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 #[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 #[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 #[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}