1use std::{
2 cell::{Cell, Ref, RefCell, RefMut},
3 collections::HashMap,
4 fmt,
5 hash::{BuildHasher, Hash},
6 net,
7 rc::Rc,
8 str,
9};
10
11use actix_http::{Message, RequestHead};
12use actix_router::{Path, Url};
13#[expect(deprecated, reason = "preserve the public ready future type")]
14use actix_utils::future::{ready, Ready};
15#[cfg(feature = "cookies")]
16use cookie::{Cookie, ParseError as CookieParseError};
17use smallvec::SmallVec;
18
19use crate::{
20 app_service::AppInitServiceState,
21 config::AppConfig,
22 dev::{Extensions, Payload},
23 error::UrlGenerationError,
24 http::{header::HeaderMap, Method, Uri, Version},
25 info::ConnectionInfo,
26 rmap::ResourceMap,
27 Error, FromRequest, HttpMessage,
28};
29
30#[cfg(feature = "cookies")]
31struct Cookies(Vec<Cookie<'static>>);
32
33#[cfg(feature = "cookies")]
34struct RawCookies(Vec<Cookie<'static>>);
35
36#[derive(Clone)]
38pub struct HttpRequest {
39 pub(crate) inner: Rc<HttpRequestInner>,
44}
45
46pub(crate) struct HttpRequestInner {
47 pub(crate) head: Message<RequestHead>,
48 pub(crate) path: Path<Url>,
49 pub(crate) resource_path: SmallVec<[u16; 4]>,
50 pub(crate) resource_path_matched: bool,
51 pub(crate) app_data: SmallVec<[Rc<Extensions>; 4]>,
52 pub(crate) conn_data: Option<Rc<Extensions>>,
53 pub(crate) extensions: Rc<RefCell<Extensions>>,
54 app_state: Rc<AppInitServiceState>,
55}
56
57impl HttpRequest {
58 #[inline]
59 pub(crate) fn new(
60 path: Path<Url>,
61 head: Message<RequestHead>,
62 app_state: Rc<AppInitServiceState>,
63 app_data: Rc<Extensions>,
64 conn_data: Option<Rc<Extensions>>,
65 extensions: Rc<RefCell<Extensions>>,
66 ) -> HttpRequest {
67 let mut data = SmallVec::<[Rc<Extensions>; 4]>::new();
68 data.push(app_data);
69
70 HttpRequest {
71 inner: Rc::new(HttpRequestInner {
72 head,
73 path,
74 resource_path: SmallVec::new(),
75 resource_path_matched: false,
76 app_state,
77 app_data: data,
78 conn_data,
79 extensions,
80 }),
81 }
82 }
83}
84
85impl HttpRequest {
86 #[inline]
88 pub fn head(&self) -> &RequestHead {
89 &self.inner.head
90 }
91
92 #[inline]
98 pub(crate) fn head_mut(&mut self) -> &mut RequestHead {
99 &mut Rc::get_mut(&mut self.inner).unwrap().head
100 }
101
102 #[inline]
104 pub fn uri(&self) -> &Uri {
105 &self.head().uri
106 }
107
108 pub fn full_url(&self) -> url::Url {
131 let info = self.connection_info();
132 let scheme = info.scheme();
133 let host = info.host();
134 let path_and_query = self
135 .uri()
136 .path_and_query()
137 .map(|paq| paq.as_str())
138 .unwrap_or("/");
139
140 url::Url::parse(&format!("{scheme}://{host}{path_and_query}")).unwrap()
141 }
142
143 #[inline]
145 pub fn method(&self) -> &Method {
146 &self.head().method
147 }
148
149 #[inline]
151 pub fn version(&self) -> Version {
152 self.head().version
153 }
154
155 #[inline]
156 pub fn headers(&self) -> &HeaderMap {
158 &self.head().headers
159 }
160
161 #[inline]
163 pub fn path(&self) -> &str {
164 self.head().uri.path()
165 }
166
167 #[inline]
171 pub fn query_string(&self) -> &str {
172 self.uri().query().unwrap_or_default()
173 }
174
175 #[inline]
187 pub fn match_info(&self) -> &Path<Url> {
188 &self.inner.path
189 }
190
191 #[inline]
196 pub(crate) fn match_info_mut(&mut self) -> &mut Path<Url> {
197 &mut Rc::get_mut(&mut self.inner).unwrap().path
198 }
199
200 #[inline]
201 pub(crate) fn push_resource_id(&mut self, id: u16) {
202 Rc::get_mut(&mut self.inner).unwrap().resource_path.push(id);
203 }
204
205 #[inline]
206 pub(crate) fn mark_resource_path(&mut self, is_matched: bool) {
207 Rc::get_mut(&mut self.inner).unwrap().resource_path_matched = is_matched;
208 }
209
210 #[inline]
211 pub(crate) fn resource_path(&self) -> &[u16] {
212 &self.inner.resource_path
213 }
214
215 #[inline]
216 pub(crate) fn is_resource_path_matched(&self) -> bool {
217 self.inner.resource_path_matched
218 }
219
220 #[inline]
227 pub fn match_pattern(&self) -> Option<String> {
228 if self.is_resource_path_matched() {
229 if let Some(pattern) = self
230 .resource_map()
231 .match_pattern_by_resource_path(self.resource_path())
232 {
233 return Some(pattern);
234 }
235 }
236
237 self.resource_map().match_pattern(self.path())
238 }
239
240 #[inline]
244 pub fn match_name(&self) -> Option<&str> {
245 if self.is_resource_path_matched() {
246 if let Some(name) = self
247 .resource_map()
248 .match_name_by_resource_path(self.resource_path())
249 {
250 return Some(name);
251 }
252 }
253
254 self.resource_map().match_name(self.path())
255 }
256
257 pub fn conn_data<T: 'static>(&self) -> Option<&T> {
265 self.inner
266 .conn_data
267 .as_deref()
268 .and_then(|container| container.get::<T>())
269 }
270
271 pub fn url_for<U, I>(&self, name: &str, elements: U) -> Result<url::Url, UrlGenerationError>
296 where
297 U: IntoIterator<Item = I>,
298 I: AsRef<str>,
299 {
300 self.resource_map().url_for(self, name, elements)
301 }
302
303 pub fn url_for_map<K, V, S>(
327 &self,
328 name: &str,
329 elements: &HashMap<K, V, S>,
330 ) -> Result<url::Url, UrlGenerationError>
331 where
332 K: std::borrow::Borrow<str> + Eq + Hash,
333 V: AsRef<str>,
334 S: BuildHasher,
335 {
336 self.resource_map().url_for_map(self, name, elements)
337 }
338
339 pub fn url_for_iter<K, V, I>(
361 &self,
362 name: &str,
363 elements: I,
364 ) -> Result<url::Url, UrlGenerationError>
365 where
366 I: IntoIterator<Item = (K, V)>,
367 K: std::borrow::Borrow<str> + Eq + Hash,
368 V: AsRef<str>,
369 {
370 self.resource_map().url_for_iter(self, name, elements)
371 }
372
373 pub fn url_for_static(&self, name: &str) -> Result<url::Url, UrlGenerationError> {
378 const NO_PARAMS: [&str; 0] = [];
379 self.url_for(name, NO_PARAMS)
380 }
381
382 #[inline]
384 pub fn resource_map(&self) -> &ResourceMap {
385 self.app_state().rmap()
386 }
387
388 #[inline]
402 pub fn peer_addr(&self) -> Option<net::SocketAddr> {
403 self.head().peer_addr
404 }
405
406 #[inline]
413 pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
414 if !self.extensions().contains::<ConnectionInfo>() {
415 let info = ConnectionInfo::new(self.head(), self.app_config());
416 self.extensions_mut().insert(info);
417 }
418
419 Ref::map(self.extensions(), |data| data.get().unwrap())
420 }
421
422 #[inline]
424 pub fn app_config(&self) -> &AppConfig {
425 self.app_state().config()
426 }
427
428 #[doc(alias = "state")]
456 pub fn app_data<T: 'static>(&self) -> Option<&T> {
457 for container in self.inner.app_data.iter().rev() {
458 if let Some(data) = container.get::<T>() {
459 return Some(data);
460 }
461 }
462
463 None
464 }
465
466 #[inline]
467 fn app_state(&self) -> &AppInitServiceState {
468 &self.inner.app_state
469 }
470
471 #[cfg(feature = "cookies-0_18")]
473 pub fn cookies_0_18(&self) -> Result<Vec<cookie_0_18::Cookie<'_>>, cookie_0_18::ParseError> {
474 self.parse_cookies_0_18(cookie_0_18::Cookie::split_parse_encoded)
475 }
476
477 #[cfg(feature = "cookies-0_18")]
479 pub fn cookies_raw_0_18(
480 &self,
481 ) -> Result<Vec<cookie_0_18::Cookie<'_>>, cookie_0_18::ParseError> {
482 self.parse_cookies_0_18(cookie_0_18::Cookie::split_parse)
483 }
484
485 #[cfg(feature = "cookies-0_18")]
487 pub fn cookie_0_18(&self, name: &str) -> Option<cookie_0_18::Cookie<'_>> {
488 self.cookies_0_18()
489 .ok()?
490 .into_iter()
491 .find(|cookie| cookie.name() == name)
492 }
493
494 #[cfg(feature = "cookies-0_18")]
496 pub fn cookie_raw_0_18(&self, name: &str) -> Option<cookie_0_18::Cookie<'_>> {
497 self.cookies_raw_0_18()
498 .ok()?
499 .into_iter()
500 .find(|cookie| cookie.name() == name)
501 }
502
503 #[cfg(feature = "cookies-0_18")]
504 fn parse_cookies_0_18<'a>(
505 &'a self,
506 parse: impl Fn(&'a str) -> cookie_0_18::SplitCookies<'a>,
507 ) -> Result<Vec<cookie_0_18::Cookie<'a>>, cookie_0_18::ParseError> {
508 let mut cookies = Vec::new();
509 for header in self.headers().get_all(actix_http::header::COOKIE) {
510 cookies.extend(parse(str::from_utf8(header.as_bytes())?).flatten());
511 }
512 Ok(cookies)
513 }
514
515 #[cfg(feature = "cookies")]
522 pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
523 use actix_http::header::COOKIE;
524
525 if self.extensions().get::<Cookies>().is_none() {
526 let mut cookies = Vec::new();
527 for hdr in self.headers().get_all(COOKIE) {
528 let s = str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?;
529 for cookie_str in s.split(';').map(|s| s.trim()).filter(|s| !s.is_empty()) {
530 if let Ok(cookie) = Cookie::parse_encoded(cookie_str) {
531 cookies.push(cookie.into_owned());
532 }
533 }
534 }
535 self.extensions_mut().insert(Cookies(cookies));
536 }
537
538 Ok(Ref::map(self.extensions(), |ext| {
539 &ext.get::<Cookies>().unwrap().0
540 }))
541 }
542
543 #[cfg(feature = "cookies")]
548 pub fn cookies_raw(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
549 use actix_http::header::COOKIE;
550
551 if self.extensions().get::<RawCookies>().is_none() {
552 let mut cookies = Vec::new();
553 for hdr in self.headers().get_all(COOKIE) {
554 let s = str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?;
555 for cookie_str in s.split(';').map(|s| s.trim()).filter(|s| !s.is_empty()) {
556 if let Ok(cookie) = Cookie::parse(cookie_str) {
557 cookies.push(cookie.into_owned());
558 }
559 }
560 }
561 self.extensions_mut().insert(RawCookies(cookies));
562 }
563
564 Ok(Ref::map(self.extensions(), |ext| {
565 &ext.get::<RawCookies>().unwrap().0
566 }))
567 }
568
569 #[cfg(feature = "cookies")]
571 pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
572 if let Ok(cookies) = self.cookies() {
573 return cookies.iter().find(|cookie| cookie.name() == name).cloned();
574 }
575
576 None
577 }
578
579 #[cfg(feature = "cookies")]
581 pub fn cookie_raw(&self, name: &str) -> Option<Cookie<'static>> {
582 if let Ok(cookies) = self.cookies_raw() {
583 return cookies.iter().find(|cookie| cookie.name() == name).cloned();
584 }
585
586 None
587 }
588}
589
590impl HttpMessage for HttpRequest {
591 type Stream = ();
592
593 #[inline]
594 fn headers(&self) -> &HeaderMap {
595 &self.head().headers
596 }
597
598 #[inline]
599 fn extensions(&self) -> Ref<'_, Extensions> {
600 self.inner.extensions.borrow()
601 }
602
603 #[inline]
604 fn extensions_mut(&self) -> RefMut<'_, Extensions> {
605 self.inner.extensions.borrow_mut()
606 }
607
608 #[inline]
609 fn take_payload(&mut self) -> Payload<Self::Stream> {
610 Payload::None
611 }
612}
613
614impl Drop for HttpRequest {
615 fn drop(&mut self) {
616 if let Some(inner) = Rc::get_mut(&mut self.inner) {
620 if inner.app_state.pool().is_available() {
621 inner.app_data.truncate(1);
623
624 Rc::get_mut(&mut inner.extensions)
627 .unwrap()
628 .get_mut()
629 .clear();
630
631 inner.conn_data = None;
634
635 let req = Rc::clone(&self.inner);
637 self.app_state().pool().push(req);
638 }
639 }
640 }
641}
642
643#[expect(deprecated, reason = "preserve the public ready future type")]
661impl FromRequest for HttpRequest {
662 type Error = Error;
663 type Future = Ready<Result<Self, Error>>;
664
665 #[inline]
666 fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
667 ready(Ok(req.clone()))
668 }
669}
670
671impl fmt::Debug for HttpRequest {
672 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673 writeln!(
674 f,
675 "\nHttpRequest {:?} {}:{}",
676 self.inner.head.version,
677 self.inner.head.method,
678 self.path()
679 )?;
680
681 if !self.query_string().is_empty() {
682 writeln!(f, " query: ?{:?}", self.query_string())?;
683 }
684
685 if !self.match_info().is_empty() {
686 writeln!(f, " params: {:?}", self.match_info())?;
687 }
688
689 writeln!(f, " headers:")?;
690
691 for (key, val) in self.headers().iter() {
692 match key {
693 &crate::http::header::AUTHORIZATION
695 | &crate::http::header::PROXY_AUTHORIZATION
696 | &crate::http::header::COOKIE => writeln!(f, " {:?}: {:?}", key, "*redacted*")?,
697
698 _ => writeln!(f, " {:?}: {:?}", key, val)?,
699 }
700 }
701
702 Ok(())
703 }
704}
705
706pub(crate) struct HttpRequestPool {
717 inner: RefCell<Vec<Rc<HttpRequestInner>>>,
718 enabled: Cell<bool>,
719 cap: usize,
720}
721
722impl Default for HttpRequestPool {
723 fn default() -> Self {
724 Self::with_capacity(128)
725 }
726}
727
728impl HttpRequestPool {
729 pub(crate) fn with_capacity(cap: usize) -> Self {
730 HttpRequestPool {
731 inner: RefCell::new(Vec::with_capacity(cap)),
732 enabled: Cell::new(true),
733 cap,
734 }
735 }
736
737 #[inline]
739 pub(crate) fn pop(&self) -> Option<HttpRequest> {
740 self.inner
741 .borrow_mut()
742 .pop()
743 .map(|inner| HttpRequest { inner })
744 }
745
746 #[inline]
748 pub(crate) fn is_available(&self) -> bool {
749 self.enabled.get() && self.inner.borrow().len() < self.cap
750 }
751
752 #[inline]
754 pub(crate) fn push(&self, req: Rc<HttpRequestInner>) {
755 self.inner.borrow_mut().push(req);
756 }
757
758 pub(crate) fn disable(&self) {
760 self.enabled.set(false);
761 self.inner.borrow_mut().clear();
762 }
763}
764
765#[cfg(test)]
766mod tests {
767 use std::{collections::HashMap, sync::Arc};
768
769 use bytes::Bytes;
770
771 use super::*;
772 use crate::{
773 dev::{ResourceDef, Service},
774 guard,
775 http::{header, StatusCode},
776 test::{self, call_service, init_service, read_body, TestRequest},
777 web, App, HttpResponse,
778 };
779
780 #[test]
781 fn test_debug() {
782 let req = TestRequest::default()
783 .insert_header(("content-type", "text/plain"))
784 .to_http_request();
785 let dbg = format!("{:?}", req);
786 assert!(dbg.contains("HttpRequest"));
787 }
788
789 #[test]
790 #[cfg(feature = "cookies")]
791 fn test_no_request_cookies() {
792 let req = TestRequest::default().to_http_request();
793 assert!(req.cookies().unwrap().is_empty());
794 }
795
796 #[test]
797 #[cfg(feature = "cookies")]
798 fn test_request_cookies() {
799 let req = TestRequest::default()
800 .append_header((header::COOKIE, "cookie1=value1"))
801 .append_header((header::COOKIE, "cookie2=value2"))
802 .to_http_request();
803 {
804 let cookies = req.cookies().unwrap();
805 assert_eq!(cookies.len(), 2);
806 assert_eq!(cookies[0].name(), "cookie1");
807 assert_eq!(cookies[0].value(), "value1");
808 assert_eq!(cookies[1].name(), "cookie2");
809 assert_eq!(cookies[1].value(), "value2");
810 }
811
812 let cookie = req.cookie("cookie1");
813 assert!(cookie.is_some());
814 let cookie = cookie.unwrap();
815 assert_eq!(cookie.name(), "cookie1");
816 assert_eq!(cookie.value(), "value1");
817
818 let cookie = req.cookie("cookie-unknown");
819 assert!(cookie.is_none());
820 }
821
822 #[test]
823 #[cfg(feature = "cookies")]
824 fn test_request_cookies_raw() {
825 let req = TestRequest::default()
826 .append_header((header::COOKIE, "cookie1=hello%20world"))
827 .append_header((header::COOKIE, "cookie2=%db"))
828 .to_http_request();
829 {
830 let cookies = req.cookies_raw().unwrap();
831 assert_eq!(cookies.len(), 2);
832 assert_eq!(cookies[0].name(), "cookie1");
833 assert_eq!(cookies[0].value(), "hello%20world");
834 assert_eq!(cookies[1].name(), "cookie2");
835 assert_eq!(cookies[1].value(), "%db");
836 }
837
838 let cookie = req.cookie_raw("cookie1");
839 assert!(cookie.is_some());
840 let cookie = cookie.unwrap();
841 assert_eq!(cookie.name(), "cookie1");
842 assert_eq!(cookie.value(), "hello%20world");
843
844 let cookie = req.cookie_raw("cookie2");
845 assert!(cookie.is_some());
846 let cookie = cookie.unwrap();
847 assert_eq!(cookie.name(), "cookie2");
848 assert_eq!(cookie.value(), "%db");
849 }
850
851 #[test]
852 #[cfg(feature = "cookies")]
853 fn test_request_cookies_raw_is_independent_from_encoded_cookies() {
854 let req = TestRequest::default()
855 .append_header((header::COOKIE, "cookie=%20"))
856 .to_http_request();
857
858 let cookie = req.cookie("cookie").unwrap();
859 assert_eq!(cookie.value(), " ");
860
861 let raw_cookie = req.cookie_raw("cookie").unwrap();
862 assert_eq!(raw_cookie.value(), "%20");
863 }
864
865 #[test]
866 #[cfg(feature = "cookies")]
867 fn test_empty_key() {
868 let req = TestRequest::default()
869 .append_header((header::COOKIE, "cookie1=value1; value2; cookie3=value3"))
870 .to_http_request();
871 {
872 let cookies = req.cookies().unwrap();
873 assert_eq!(cookies.len(), 2);
874 assert_eq!(cookies[0].name(), "cookie1");
875 assert_eq!(cookies[0].value(), "value1");
876 assert_eq!(cookies[1].name(), "cookie3");
877 assert_eq!(cookies[1].value(), "value3");
878 }
879 }
880
881 #[test]
882 fn test_request_query() {
883 let req = TestRequest::with_uri("/?id=test").to_http_request();
884 assert_eq!(req.query_string(), "id=test");
885 }
886
887 #[test]
888 fn test_url_for() {
889 let mut res = ResourceDef::new("/user/{name}.{ext}");
890 res.set_name("index");
891
892 let mut rmap = ResourceMap::new(ResourceDef::prefix(""));
893 rmap.add(&mut res, None);
894 assert!(rmap.has_resource("/user/test.html"));
895 assert!(!rmap.has_resource("/test/unknown"));
896
897 let req = TestRequest::default()
898 .insert_header((header::HOST, "www.rust-lang.org"))
899 .rmap(rmap)
900 .to_http_request();
901
902 assert_eq!(
903 req.url_for("unknown", ["test"]),
904 Err(UrlGenerationError::ResourceNotFound)
905 );
906 assert_eq!(
907 req.url_for("index", ["test"]),
908 Err(UrlGenerationError::NotEnoughElements)
909 );
910 let url = req.url_for("index", ["test", "html"]);
911 assert_eq!(
912 url.ok().unwrap().as_str(),
913 "http://www.rust-lang.org/user/test.html"
914 );
915 }
916
917 #[test]
918 fn test_url_for_map() {
919 let mut res = ResourceDef::new("/user/{name}.{ext}");
920 res.set_name("index");
921
922 let mut rmap = ResourceMap::new(ResourceDef::prefix(""));
923 rmap.add(&mut res, None);
924
925 let req = TestRequest::default()
926 .insert_header((header::HOST, "www.actix.rs"))
927 .rmap(rmap)
928 .to_http_request();
929
930 let mut params = HashMap::new();
931 params.insert("name", "test");
932 params.insert("ext", "html");
933
934 let url = req.url_for_map("index", ¶ms);
935 assert_eq!(
936 url.ok().unwrap().as_str(),
937 "http://www.actix.rs/user/test.html"
938 );
939
940 params.remove("ext");
941 assert_eq!(
942 req.url_for_map("index", ¶ms),
943 Err(UrlGenerationError::NotEnoughElements)
944 );
945 }
946
947 #[test]
948 fn test_url_for_iter() {
949 let mut res = ResourceDef::new("/user/{name}.{ext}");
950 res.set_name("index");
951
952 let mut rmap = ResourceMap::new(ResourceDef::prefix(""));
953 rmap.add(&mut res, None);
954
955 let req = TestRequest::default()
956 .insert_header((header::HOST, "www.actix.rs"))
957 .rmap(rmap)
958 .to_http_request();
959
960 let url = req.url_for_iter("index", [("ext", "html"), ("name", "test")]);
961 assert_eq!(
962 url.ok().unwrap().as_str(),
963 "http://www.actix.rs/user/test.html"
964 );
965
966 let url = req.url_for_iter("index", [("name", "test")]);
967 assert_eq!(url, Err(UrlGenerationError::NotEnoughElements));
968 }
969
970 #[test]
971 fn test_url_for_static() {
972 let mut rdef = ResourceDef::new("/index.html");
973 rdef.set_name("index");
974
975 let mut rmap = ResourceMap::new(ResourceDef::prefix(""));
976 rmap.add(&mut rdef, None);
977
978 assert!(rmap.has_resource("/index.html"));
979
980 let req = TestRequest::with_uri("/test")
981 .insert_header((header::HOST, "www.rust-lang.org"))
982 .rmap(rmap)
983 .to_http_request();
984 let url = req.url_for_static("index");
985 assert_eq!(
986 url.ok().unwrap().as_str(),
987 "http://www.rust-lang.org/index.html"
988 );
989 }
990
991 #[test]
992 fn test_match_name() {
993 let mut rdef = ResourceDef::new("/index.html");
994 rdef.set_name("index");
995
996 let mut rmap = ResourceMap::new(ResourceDef::prefix(""));
997 rmap.add(&mut rdef, None);
998
999 assert!(rmap.has_resource("/index.html"));
1000
1001 let req = TestRequest::default()
1002 .uri("/index.html")
1003 .rmap(rmap)
1004 .to_http_request();
1005
1006 assert_eq!(req.match_name(), Some("index"));
1007 }
1008
1009 #[test]
1010 fn test_url_for_external() {
1011 let mut rdef = ResourceDef::new("https://youtube.com/watch/{video_id}");
1012
1013 rdef.set_name("youtube");
1014
1015 let mut rmap = ResourceMap::new(ResourceDef::prefix(""));
1016 rmap.add(&mut rdef, None);
1017
1018 let req = TestRequest::default().rmap(rmap).to_http_request();
1019 let url = req.url_for("youtube", ["oHg5SJYRHA0"]);
1020 assert_eq!(
1021 url.ok().unwrap().as_str(),
1022 "https://youtube.com/watch/oHg5SJYRHA0"
1023 );
1024 }
1025
1026 #[tokio::test(flavor = "local")]
1027 async fn test_drop_http_request_pool() {
1028 let srv = init_service(
1029 App::new().service(web::resource("/").to(|req: HttpRequest| {
1030 HttpResponse::Ok()
1031 .insert_header(("pool_cap", req.app_state().pool().cap))
1032 .finish()
1033 })),
1034 )
1035 .await;
1036
1037 let req = TestRequest::default().to_request();
1038 let resp = call_service(&srv, req).await;
1039
1040 drop(srv);
1041
1042 assert_eq!(resp.headers().get("pool_cap").unwrap(), "128");
1043 }
1044
1045 #[tokio::test(flavor = "local")]
1046 async fn test_request_dropped_after_service_does_not_reenter_pool() {
1047 struct State {
1048 _data: Arc<String>,
1049 }
1050
1051 let (weak_data, app_data) = {
1052 let data = Arc::new("data".to_owned());
1053 (Arc::downgrade(&data), web::Data::new(State { _data: data }))
1054 };
1055
1056 let held_req = Rc::new(RefCell::new(None));
1057
1058 {
1059 let held_req = Rc::clone(&held_req);
1060 let srv = init_service(App::new().app_data(app_data).service(web::resource("/").to(
1061 move |req: HttpRequest| {
1062 *held_req.borrow_mut() = Some(req.clone());
1063 HttpResponse::Ok()
1064 },
1065 )))
1066 .await;
1067
1068 let resp = call_service(&srv, TestRequest::default().to_request()).await;
1069 assert_eq!(resp.status(), StatusCode::OK);
1070
1071 drop(resp);
1072 drop(srv);
1073 }
1074
1075 assert!(weak_data.upgrade().is_some());
1076 drop(held_req.borrow_mut().take());
1077 assert!(weak_data.upgrade().is_none());
1078 }
1079
1080 #[tokio::test(flavor = "local")]
1081 async fn test_data() {
1082 let srv = init_service(App::new().app_data(10usize).service(web::resource("/").to(
1083 |req: HttpRequest| {
1084 if req.app_data::<usize>().is_some() {
1085 HttpResponse::Ok()
1086 } else {
1087 HttpResponse::BadRequest()
1088 }
1089 },
1090 )))
1091 .await;
1092
1093 let req = TestRequest::default().to_request();
1094 let resp = call_service(&srv, req).await;
1095 assert_eq!(resp.status(), StatusCode::OK);
1096
1097 let srv = init_service(App::new().app_data(10u32).service(web::resource("/").to(
1098 |req: HttpRequest| {
1099 if req.app_data::<usize>().is_some() {
1100 HttpResponse::Ok()
1101 } else {
1102 HttpResponse::BadRequest()
1103 }
1104 },
1105 )))
1106 .await;
1107
1108 let req = TestRequest::default().to_request();
1109 let resp = call_service(&srv, req).await;
1110 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1111 }
1112
1113 #[tokio::test(flavor = "local")]
1114 async fn test_cascading_data() {
1115 #[allow(dead_code)]
1116 fn echo_usize(req: HttpRequest) -> HttpResponse {
1117 let num = req.app_data::<usize>().unwrap();
1118 HttpResponse::Ok().body(num.to_string())
1119 }
1120
1121 let srv = init_service(
1122 App::new()
1123 .app_data(88usize)
1124 .service(web::resource("/").route(web::get().to(echo_usize)))
1125 .service(
1126 web::resource("/one")
1127 .app_data(1u32)
1128 .route(web::get().to(echo_usize)),
1129 ),
1130 )
1131 .await;
1132
1133 let req = TestRequest::get().uri("/").to_request();
1134 let resp = srv.call(req).await.unwrap();
1135 let body = read_body(resp).await;
1136 assert_eq!(body, Bytes::from_static(b"88"));
1137
1138 let req = TestRequest::get().uri("/one").to_request();
1139 let resp = srv.call(req).await.unwrap();
1140 let body = read_body(resp).await;
1141 assert_eq!(body, Bytes::from_static(b"88"));
1142 }
1143
1144 #[tokio::test(flavor = "local")]
1145 async fn test_overwrite_data() {
1146 #[allow(dead_code)]
1147 fn echo_usize(req: HttpRequest) -> HttpResponse {
1148 let num = req.app_data::<usize>().unwrap();
1149 HttpResponse::Ok().body(num.to_string())
1150 }
1151
1152 let srv = init_service(
1153 App::new()
1154 .app_data(88usize)
1155 .service(web::resource("/").route(web::get().to(echo_usize)))
1156 .service(
1157 web::resource("/one")
1158 .app_data(1usize)
1159 .route(web::get().to(echo_usize)),
1160 ),
1161 )
1162 .await;
1163
1164 let req = TestRequest::get().uri("/").to_request();
1165 let resp = srv.call(req).await.unwrap();
1166 let body = read_body(resp).await;
1167 assert_eq!(body, Bytes::from_static(b"88"));
1168
1169 let req = TestRequest::get().uri("/one").to_request();
1170 let resp = srv.call(req).await.unwrap();
1171 let body = read_body(resp).await;
1172 assert_eq!(body, Bytes::from_static(b"1"));
1173 }
1174
1175 #[tokio::test(flavor = "local")]
1176 async fn test_app_data_dropped() {
1177 struct Tracker {
1178 pub dropped: bool,
1179 }
1180 struct Foo {
1181 tracker: Rc<RefCell<Tracker>>,
1182 }
1183 impl Drop for Foo {
1184 fn drop(&mut self) {
1185 self.tracker.borrow_mut().dropped = true;
1186 }
1187 }
1188
1189 let tracker = Rc::new(RefCell::new(Tracker { dropped: false }));
1190 {
1191 let tracker2 = Rc::clone(&tracker);
1192 let srv = init_service(App::new().service(web::resource("/").to(
1193 move |req: HttpRequest| {
1194 req.extensions_mut().insert(Foo {
1195 tracker: Rc::clone(&tracker2),
1196 });
1197 HttpResponse::Ok()
1198 },
1199 )))
1200 .await;
1201
1202 let req = TestRequest::default().to_request();
1203 let resp = call_service(&srv, req).await;
1204 assert_eq!(resp.status(), StatusCode::OK);
1205 }
1206
1207 assert!(tracker.borrow().dropped);
1208 }
1209
1210 #[tokio::test(flavor = "local")]
1211 async fn extract_path_pattern() {
1212 let srv = init_service(
1213 App::new().service(
1214 web::scope("/user/{id}")
1215 .service(web::resource("/profile").route(web::get().to(
1216 move |req: HttpRequest| {
1217 assert_eq!(req.match_pattern(), Some("/user/{id}/profile".to_owned()));
1218
1219 HttpResponse::Ok().finish()
1220 },
1221 )))
1222 .default_service(web::to(move |req: HttpRequest| {
1223 assert!(req.match_pattern().is_none());
1224 HttpResponse::Ok().finish()
1225 })),
1226 ),
1227 )
1228 .await;
1229
1230 let req = TestRequest::get().uri("/user/22/profile").to_request();
1231 let res = call_service(&srv, req).await;
1232 assert_eq!(res.status(), StatusCode::OK);
1233
1234 let req = TestRequest::get().uri("/user/22/not-exist").to_request();
1235 let res = call_service(&srv, req).await;
1236 assert_eq!(res.status(), StatusCode::OK);
1237 }
1238
1239 #[tokio::test(flavor = "local")]
1240 async fn extract_path_pattern_with_guards() {
1241 let srv = init_service(
1242 App::new().service(
1243 web::scope("/widgets")
1244 .service(
1245 web::resource("/{id}")
1246 .name("get_widget")
1247 .guard(guard::Get())
1248 .to(|req: HttpRequest| {
1249 assert_eq!(req.match_pattern(), Some("/widgets/{id}".to_owned()));
1250 assert_eq!(req.match_name(), Some("get_widget"));
1251 HttpResponse::Ok().finish()
1252 }),
1253 )
1254 .service(
1255 web::resource("/action")
1256 .name("widget_action")
1257 .guard(guard::Post())
1258 .to(|req: HttpRequest| {
1259 assert_eq!(req.match_pattern(), Some("/widgets/action".to_owned()));
1260 assert_eq!(req.match_name(), Some("widget_action"));
1261 HttpResponse::Ok().finish()
1262 }),
1263 ),
1264 ),
1265 )
1266 .await;
1267
1268 let req = TestRequest::get().uri("/widgets/42").to_request();
1269 let res = call_service(&srv, req).await;
1270 assert_eq!(res.status(), StatusCode::OK);
1271
1272 let req = TestRequest::post().uri("/widgets/action").to_request();
1273 let res = call_service(&srv, req).await;
1274 assert_eq!(res.status(), StatusCode::OK);
1275 }
1276
1277 #[tokio::test(flavor = "local")]
1278 async fn extract_path_pattern_complex() {
1279 let srv = init_service(
1280 App::new()
1281 .service(web::scope("/user").service(web::scope("/{id}").service(
1282 web::resource("").to(move |req: HttpRequest| {
1283 assert_eq!(req.match_pattern(), Some("/user/{id}".to_owned()));
1284
1285 HttpResponse::Ok().finish()
1286 }),
1287 )))
1288 .service(web::resource("/").to(move |req: HttpRequest| {
1289 assert_eq!(req.match_pattern(), Some("/".to_owned()));
1290
1291 HttpResponse::Ok().finish()
1292 }))
1293 .default_service(web::to(move |req: HttpRequest| {
1294 assert!(req.match_pattern().is_none());
1295 HttpResponse::Ok().finish()
1296 })),
1297 )
1298 .await;
1299
1300 let req = TestRequest::get().uri("/user/test").to_request();
1301 let res = call_service(&srv, req).await;
1302 assert_eq!(res.status(), StatusCode::OK);
1303
1304 let req = TestRequest::get().uri("/").to_request();
1305 let res = call_service(&srv, req).await;
1306 assert_eq!(res.status(), StatusCode::OK);
1307
1308 let req = TestRequest::get().uri("/not-exist").to_request();
1309 let res = call_service(&srv, req).await;
1310 assert_eq!(res.status(), StatusCode::OK);
1311 }
1312
1313 #[tokio::test(flavor = "local")]
1314 async fn url_for_closest_named_resource() {
1315 let srv = test::init_service(
1317 App::new()
1318 .service(
1319 web::scope("/foo")
1320 .service(web::resource("/nested").name("nested").route(web::get().to(
1321 |req: HttpRequest| {
1322 HttpResponse::Ok()
1323 .body(format!("{}", req.url_for_static("nested").unwrap()))
1324 },
1325 )))
1326 .service(web::scope("/baz").service(web::resource("deep")))
1327 .service(web::resource("{foo_param}")),
1328 )
1329 .service(web::scope("/bar").service(
1330 web::resource("/nested").name("nested").route(web::get().to(
1331 |req: HttpRequest| {
1332 HttpResponse::Ok()
1333 .body(format!("{}", req.url_for_static("nested").unwrap()))
1334 },
1335 )),
1336 )),
1337 )
1338 .await;
1339
1340 let foo_resp =
1341 test::call_service(&srv, TestRequest::with_uri("/foo/nested").to_request()).await;
1342 assert_eq!(foo_resp.status(), StatusCode::OK);
1343 let body = read_body(foo_resp).await;
1344 assert_eq!(body, "http://localhost:8080/bar/nested");
1349
1350 let bar_resp =
1351 test::call_service(&srv, TestRequest::with_uri("/bar/nested").to_request()).await;
1352 assert_eq!(bar_resp.status(), StatusCode::OK);
1353 let body = read_body(bar_resp).await;
1354 assert_eq!(body, "http://localhost:8080/bar/nested");
1355 }
1356
1357 #[test]
1358 fn authorization_header_hidden_in_debug() {
1359 let authorization_header = "Basic bXkgdXNlcm5hbWU6bXkgcGFzc3dvcmQK";
1360 let req = TestRequest::get()
1361 .insert_header((crate::http::header::AUTHORIZATION, authorization_header))
1362 .to_http_request();
1363
1364 assert!(!format!("{:?}", req).contains(authorization_header));
1365 }
1366
1367 #[test]
1368 fn proxy_authorization_header_hidden_in_debug() {
1369 let proxy_authorization_header = "secret value";
1370 let req = TestRequest::get()
1371 .insert_header((
1372 crate::http::header::PROXY_AUTHORIZATION,
1373 proxy_authorization_header,
1374 ))
1375 .to_http_request();
1376
1377 assert!(!format!("{:?}", req).contains(proxy_authorization_header));
1378 }
1379
1380 #[test]
1381 fn cookie_header_hidden_in_debug() {
1382 let cookie_header = "secret";
1383 let req = TestRequest::get()
1384 .insert_header((crate::http::header::COOKIE, cookie_header))
1385 .to_http_request();
1386
1387 assert!(!format!("{:?}", req).contains(cookie_header));
1388 }
1389
1390 #[test]
1391 fn other_header_visible_in_debug() {
1392 let location_header = "192.0.0.1";
1393 let req = TestRequest::get()
1394 .insert_header((crate::http::header::LOCATION, location_header))
1395 .to_http_request();
1396
1397 assert!(format!("{:?}", req).contains(location_header));
1398 }
1399
1400 #[test]
1401 fn check_full_url() {
1402 let req = TestRequest::with_uri("/api?id=4&name=foo").to_http_request();
1403 assert_eq!(
1404 req.full_url().as_str(),
1405 "http://localhost:8080/api?id=4&name=foo",
1406 );
1407
1408 let req = TestRequest::with_uri("https://example.com/api?id=4&name=foo").to_http_request();
1409 assert_eq!(
1410 req.full_url().as_str(),
1411 "https://example.com/api?id=4&name=foo",
1412 );
1413
1414 let req = TestRequest::with_uri("http://10.1.2.3:8443/api?id=4&name=foo")
1415 .insert_header(("host", "example.com"))
1416 .to_http_request();
1417 assert_eq!(
1418 req.full_url().as_str(),
1419 "http://example.com/api?id=4&name=foo",
1420 );
1421 }
1422}