1use std::{
53 cell::{Ref, RefMut},
54 rc::Rc,
55};
56
57use actix_http::{header, Extensions, Method as HttpMethod, RequestHead};
58
59use crate::{http::header::Header, service::ServiceRequest, HttpMessage as _};
60
61mod acceptable;
62mod host;
63
64pub use self::{
65 acceptable::Acceptable,
66 host::{Host, HostGuard},
67};
68
69#[cfg(feature = "experimental-introspection")]
71#[non_exhaustive]
72#[derive(Debug, Clone)]
73pub enum GuardDetail {
74 HttpMethods(Vec<String>),
76 Headers(Vec<(String, String)>),
78 Generic(String),
80}
81
82#[derive(Debug)]
84pub struct GuardContext<'a> {
85 pub(crate) req: &'a ServiceRequest,
86}
87
88impl<'a> GuardContext<'a> {
89 #[inline]
91 pub fn head(&self) -> &RequestHead {
92 self.req.head()
93 }
94
95 #[inline]
97 pub fn req_data(&self) -> Ref<'a, Extensions> {
98 self.req.extensions()
99 }
100
101 #[inline]
103 pub fn req_data_mut(&self) -> RefMut<'a, Extensions> {
104 self.req.extensions_mut()
105 }
106
107 #[inline]
123 pub fn header<H: Header>(&self) -> Option<H> {
124 H::parse(self.req).ok()
125 }
126
127 #[inline]
129 pub fn app_data<T: 'static>(&self) -> Option<&T> {
130 self.req.app_data()
131 }
132}
133
134pub trait Guard {
138 fn check(&self, ctx: &GuardContext<'_>) -> bool;
140
141 #[cfg(feature = "experimental-introspection")]
143 fn name(&self) -> String {
144 std::any::type_name::<Self>().to_string()
145 }
146
147 #[cfg(feature = "experimental-introspection")]
151 fn details(&self) -> Option<Vec<GuardDetail>> {
152 None
153 }
154}
155
156impl Guard for Rc<dyn Guard> {
157 fn check(&self, ctx: &GuardContext<'_>) -> bool {
158 (**self).check(ctx)
159 }
160
161 #[cfg(feature = "experimental-introspection")]
162 fn name(&self) -> String {
163 (**self).name()
164 }
165
166 #[cfg(feature = "experimental-introspection")]
167 fn details(&self) -> Option<Vec<GuardDetail>> {
168 (**self).details()
169 }
170}
171
172pub fn fn_guard<F>(f: F) -> impl Guard
185where
186 F: Fn(&GuardContext<'_>) -> bool,
187{
188 FnGuard(f)
189}
190
191struct FnGuard<F: Fn(&GuardContext<'_>) -> bool>(F);
192
193impl<F> Guard for FnGuard<F>
194where
195 F: Fn(&GuardContext<'_>) -> bool,
196{
197 fn check(&self, ctx: &GuardContext<'_>) -> bool {
198 (self.0)(ctx)
199 }
200}
201
202impl<F> Guard for F
203where
204 F: Fn(&GuardContext<'_>) -> bool,
205{
206 fn check(&self, ctx: &GuardContext<'_>) -> bool {
207 (self)(ctx)
208 }
209}
210
211#[allow(non_snake_case)]
225pub fn Any<F: Guard + 'static>(guard: F) -> AnyGuard {
226 AnyGuard {
227 guards: vec![Box::new(guard)],
228 }
229}
230
231pub struct AnyGuard {
237 guards: Vec<Box<dyn Guard>>,
238}
239
240impl AnyGuard {
241 pub fn or<F: Guard + 'static>(mut self, guard: F) -> Self {
243 self.guards.push(Box::new(guard));
244 self
245 }
246}
247
248impl Guard for AnyGuard {
249 #[inline]
250 fn check(&self, ctx: &GuardContext<'_>) -> bool {
251 for guard in &self.guards {
252 if guard.check(ctx) {
253 return true;
254 }
255 }
256
257 false
258 }
259
260 #[cfg(feature = "experimental-introspection")]
261 fn name(&self) -> String {
262 format!(
263 "AnyGuard({})",
264 self.guards
265 .iter()
266 .map(|g| g.name())
267 .collect::<Vec<_>>()
268 .join(", ")
269 )
270 }
271
272 #[cfg(feature = "experimental-introspection")]
273 fn details(&self) -> Option<Vec<GuardDetail>> {
274 Some(
275 self.guards
276 .iter()
277 .flat_map(|g| g.details().unwrap_or_default())
278 .collect(),
279 )
280 }
281}
282
283#[allow(non_snake_case)]
299pub fn All<F: Guard + 'static>(guard: F) -> AllGuard {
300 AllGuard {
301 guards: vec![Box::new(guard)],
302 }
303}
304
305pub struct AllGuard {
311 guards: Vec<Box<dyn Guard>>,
312}
313
314impl AllGuard {
315 pub fn and<F: Guard + 'static>(mut self, guard: F) -> Self {
317 self.guards.push(Box::new(guard));
318 self
319 }
320}
321
322impl Guard for AllGuard {
323 #[inline]
324 fn check(&self, ctx: &GuardContext<'_>) -> bool {
325 for guard in &self.guards {
326 if !guard.check(ctx) {
327 return false;
328 }
329 }
330
331 true
332 }
333
334 #[cfg(feature = "experimental-introspection")]
335 fn name(&self) -> String {
336 format!(
337 "AllGuard({})",
338 self.guards
339 .iter()
340 .map(|g| g.name())
341 .collect::<Vec<_>>()
342 .join(", ")
343 )
344 }
345
346 #[cfg(feature = "experimental-introspection")]
347 fn details(&self) -> Option<Vec<GuardDetail>> {
348 Some(
349 self.guards
350 .iter()
351 .flat_map(|g| g.details().unwrap_or_default())
352 .collect(),
353 )
354 }
355}
356
357pub struct Not<G>(pub G);
369
370impl<G: Guard> Guard for Not<G> {
371 #[inline]
372 fn check(&self, ctx: &GuardContext<'_>) -> bool {
373 !self.0.check(ctx)
374 }
375
376 #[cfg(feature = "experimental-introspection")]
377 fn name(&self) -> String {
378 format!("Not({})", self.0.name())
379 }
380
381 #[cfg(feature = "experimental-introspection")]
382 fn details(&self) -> Option<Vec<GuardDetail>> {
383 Some(vec![GuardDetail::Generic(self.name())])
384 }
385}
386
387#[allow(non_snake_case)]
389pub fn Method(method: HttpMethod) -> impl Guard {
390 MethodGuard(method)
391}
392
393#[derive(Debug, Clone)]
394pub(crate) struct RegisteredMethods(pub(crate) Vec<HttpMethod>);
395
396#[derive(Debug)]
398pub(crate) struct MethodGuard(HttpMethod);
399
400impl Guard for MethodGuard {
401 fn check(&self, ctx: &GuardContext<'_>) -> bool {
402 let mut extensions = ctx.req_data_mut();
403 let methods = extensions.get_or_insert_with(|| RegisteredMethods(Vec::new()));
404
405 if !methods.0.contains(&self.0) {
406 methods.0.push(self.0.clone());
407 }
408
409 ctx.head().method == self.0
410 }
411
412 #[cfg(feature = "experimental-introspection")]
413 fn name(&self) -> String {
414 self.0.to_string()
415 }
416
417 #[cfg(feature = "experimental-introspection")]
418 fn details(&self) -> Option<Vec<GuardDetail>> {
419 Some(vec![GuardDetail::HttpMethods(vec![self.0.to_string()])])
420 }
421}
422
423macro_rules! method_guard {
424 ($method_fn:ident, $method_const:ident) => {
425 #[doc = concat!("Creates a guard that matches the `", stringify!($method_const), "` request method.")]
426 #[doc = concat!("The route in this example will only respond to `", stringify!($method_const), "` requests.")]
429 #[doc = concat!(" .guard(guard::", stringify!($method_fn), "())")]
434 #[allow(non_snake_case)]
437 pub fn $method_fn() -> impl Guard {
438 MethodGuard(HttpMethod::$method_const)
439 }
440 };
441}
442
443method_guard!(Get, GET);
444method_guard!(Post, POST);
445method_guard!(Put, PUT);
446method_guard!(Delete, DELETE);
447method_guard!(Head, HEAD);
448method_guard!(Options, OPTIONS);
449method_guard!(Connect, CONNECT);
450method_guard!(Patch, PATCH);
451method_guard!(Trace, TRACE);
452
453#[allow(non_snake_case)]
467pub fn Query() -> impl Guard {
468 MethodGuard(HttpMethod::from_bytes(b"QUERY").unwrap())
469}
470
471#[allow(non_snake_case)]
484pub fn Header(name: &'static str, value: &'static str) -> impl Guard {
485 HeaderGuard(
486 header::HeaderName::try_from(name).unwrap(),
487 header::HeaderValue::from_static(value),
488 )
489}
490
491struct HeaderGuard(header::HeaderName, header::HeaderValue);
492
493impl Guard for HeaderGuard {
494 fn check(&self, ctx: &GuardContext<'_>) -> bool {
495 if let Some(val) = ctx.head().headers.get(&self.0) {
496 return val == self.1;
497 }
498
499 false
500 }
501
502 #[cfg(feature = "experimental-introspection")]
503 fn name(&self) -> String {
504 format!("Header({}, {})", self.0, self.1.to_str().unwrap_or(""))
505 }
506
507 #[cfg(feature = "experimental-introspection")]
508 fn details(&self) -> Option<Vec<GuardDetail>> {
509 Some(vec![GuardDetail::Headers(vec![(
510 self.0.to_string(),
511 self.1.to_str().unwrap_or("").to_string(),
512 )])])
513 }
514}
515
516#[cfg(test)]
517mod tests {
518 use actix_http::Method;
519
520 use super::*;
521 use crate::test::TestRequest;
522
523 #[test]
524 fn header_match() {
525 let req = TestRequest::default()
526 .insert_header((header::TRANSFER_ENCODING, "chunked"))
527 .to_srv_request();
528
529 let hdr = Header("transfer-encoding", "chunked");
530 assert!(hdr.check(&req.guard_ctx()));
531
532 let hdr = Header("transfer-encoding", "other");
533 assert!(!hdr.check(&req.guard_ctx()));
534
535 let hdr = Header("content-type", "chunked");
536 assert!(!hdr.check(&req.guard_ctx()));
537
538 let hdr = Header("content-type", "other");
539 assert!(!hdr.check(&req.guard_ctx()));
540 }
541
542 #[test]
543 fn method_guards() {
544 let get_req = TestRequest::get().to_srv_request();
545 let post_req = TestRequest::post().to_srv_request();
546
547 assert!(Get().check(&get_req.guard_ctx()));
548 assert!(!Get().check(&post_req.guard_ctx()));
549
550 assert!(Post().check(&post_req.guard_ctx()));
551 assert!(!Post().check(&get_req.guard_ctx()));
552
553 let req = TestRequest::put().to_srv_request();
554 assert!(Put().check(&req.guard_ctx()));
555 assert!(!Put().check(&get_req.guard_ctx()));
556
557 let req = TestRequest::patch().to_srv_request();
558 assert!(Patch().check(&req.guard_ctx()));
559 assert!(!Patch().check(&get_req.guard_ctx()));
560
561 let r = TestRequest::delete().to_srv_request();
562 assert!(Delete().check(&r.guard_ctx()));
563 assert!(!Delete().check(&get_req.guard_ctx()));
564
565 let req = TestRequest::default().method(Method::HEAD).to_srv_request();
566 assert!(Head().check(&req.guard_ctx()));
567 assert!(!Head().check(&get_req.guard_ctx()));
568
569 let req = TestRequest::default()
570 .method(Method::OPTIONS)
571 .to_srv_request();
572 assert!(Options().check(&req.guard_ctx()));
573 assert!(!Options().check(&get_req.guard_ctx()));
574
575 let req = TestRequest::default()
576 .method(Method::CONNECT)
577 .to_srv_request();
578 assert!(Connect().check(&req.guard_ctx()));
579 assert!(!Connect().check(&get_req.guard_ctx()));
580
581 let req = TestRequest::default()
582 .method(Method::TRACE)
583 .to_srv_request();
584 assert!(Trace().check(&req.guard_ctx()));
585 assert!(!Trace().check(&get_req.guard_ctx()));
586
587 let query_method = Method::from_bytes(b"QUERY").unwrap();
588 let req = TestRequest::default().method(query_method).to_srv_request();
589 assert!(Query().check(&req.guard_ctx()));
590 assert!(!Query().check(&get_req.guard_ctx()));
591
592 let other_req = TestRequest::default()
593 .method(Method::from_bytes(b"NOT_A_QUERY").unwrap())
594 .to_srv_request();
595 assert!(!Query().check(&other_req.guard_ctx()));
596 }
597
598 #[test]
599 fn aggregate_any() {
600 let req = TestRequest::default()
601 .method(Method::TRACE)
602 .to_srv_request();
603
604 assert!(Any(Trace()).check(&req.guard_ctx()));
605 assert!(Any(Trace()).or(Get()).check(&req.guard_ctx()));
606 assert!(!Any(Get()).or(Get()).check(&req.guard_ctx()));
607 }
608
609 #[test]
610 fn aggregate_all() {
611 let req = TestRequest::default()
612 .method(Method::TRACE)
613 .to_srv_request();
614
615 assert!(All(Trace()).check(&req.guard_ctx()));
616 assert!(All(Trace()).and(Trace()).check(&req.guard_ctx()));
617 assert!(!All(Trace()).and(Get()).check(&req.guard_ctx()));
618 }
619
620 #[test]
621 fn nested_not() {
622 let req = TestRequest::default().to_srv_request();
623
624 let get = Get();
625 assert!(get.check(&req.guard_ctx()));
626
627 let not_get = Not(get);
628 assert!(!not_get.check(&req.guard_ctx()));
629
630 let not_not_get = Not(not_get);
631 assert!(not_not_get.check(&req.guard_ctx()));
632 }
633
634 #[test]
635 fn function_guard() {
636 let domain = "rust-lang.org".to_owned();
637 let guard = fn_guard(|ctx| ctx.head().uri.host().unwrap().ends_with(&domain));
638
639 let req = TestRequest::default()
640 .uri("blog.rust-lang.org")
641 .to_srv_request();
642 assert!(guard.check(&req.guard_ctx()));
643
644 let req = TestRequest::default().uri("crates.io").to_srv_request();
645 assert!(!guard.check(&req.guard_ctx()));
646 }
647
648 #[test]
649 fn mega_nesting() {
650 let guard = fn_guard(|ctx| All(Not(Any(Not(Trace())))).check(ctx));
651
652 let req = TestRequest::default().to_srv_request();
653 assert!(!guard.check(&req.guard_ctx()));
654
655 let req = TestRequest::default()
656 .method(Method::TRACE)
657 .to_srv_request();
658 assert!(guard.check(&req.guard_ctx()));
659 }
660
661 #[test]
662 fn app_data() {
663 const TEST_VALUE: u32 = 42;
664 let guard = fn_guard(|ctx| ctx.app_data::<u32>() == Some(&TEST_VALUE));
665
666 let req = TestRequest::default().app_data(TEST_VALUE).to_srv_request();
667 assert!(guard.check(&req.guard_ctx()));
668
669 let req = TestRequest::default()
670 .app_data(TEST_VALUE * 2)
671 .to_srv_request();
672 assert!(!guard.check(&req.guard_ctx()));
673 }
674}