Skip to main content

ntex/web/
request.rs

1use std::{cell::Ref, cell::RefMut, fmt, net};
2
3use urly::Url;
4
5use crate::http::header;
6use crate::http::{HeaderMap, HttpMessage, Method, Payload, RequestHead, Response, Version};
7use crate::io::{IoRef, types};
8use crate::router::{Path, Resource};
9use crate::util::Extensions;
10
11use super::config::WebAppConfig;
12use super::info::ConnectionInfo;
13use super::rmap::ResourceMap;
14use super::{HttpRequest, State, WebResponse, WebResponseError};
15
16/// An service http request
17///
18/// `WebRequest` allows mutable access to request's internal structures
19pub struct WebRequest<St = ()> {
20    pub(crate) req: HttpRequest,
21    payload: Payload,
22    state: St,
23}
24
25impl<St> WebRequest<St> {
26    /// Construct web request
27    pub(crate) fn new(req: HttpRequest, payload: Payload, state: St) -> Self {
28        WebRequest {
29            req,
30            payload,
31            state,
32        }
33    }
34
35    /// Create web response for error
36    #[inline]
37    pub fn error_response<AppSt, E>(self, st: &AppSt, err: &E) -> WebResponse
38    where
39        AppSt: State,
40        E: WebResponseError<AppSt, AppSt::Error>,
41    {
42        WebResponse::new(err.error_response(st), self.req)
43    }
44}
45
46impl WebRequest<()> {
47    /// Construct request from request.
48    pub fn from_request(req: HttpRequest) -> Self {
49        WebRequest {
50            req,
51            payload: Payload::None,
52            state: (),
53        }
54    }
55}
56
57impl<St> WebRequest<St> {
58    /// Deconstruct request into parts
59    pub fn into_parts(self) -> (HttpRequest, Payload, St) {
60        (self.req, self.payload, self.state)
61    }
62
63    /// Construct request from parts.
64    pub fn from_parts(req: HttpRequest, payload: Payload, state: St) -> Self {
65        WebRequest {
66            req,
67            payload,
68            state,
69        }
70    }
71
72    /// Create web response
73    #[inline]
74    pub fn into_response<R: Into<Response>>(self, res: R) -> WebResponse {
75        WebResponse::new(res.into(), self.req)
76    }
77
78    /// Io reference for current connection
79    #[inline]
80    pub fn io(&self) -> Option<&IoRef> {
81        self.head().io.as_ref()
82    }
83
84    /// This method returns reference to the request head
85    #[inline]
86    pub fn head(&self) -> &RequestHead {
87        self.req.head()
88    }
89
90    /// This method returns mutable reference to the request head
91    #[inline]
92    pub fn head_mut(&mut self) -> &mut RequestHead {
93        self.req.head_mut()
94    }
95
96    /// Request's uri.
97    #[inline]
98    pub fn uri(&self) -> &Url {
99        &self.head().uri
100    }
101
102    /// Read the Request method.
103    #[inline]
104    pub fn method(&self) -> &Method {
105        &self.head().method
106    }
107
108    /// Read the Request Version.
109    #[inline]
110    pub fn version(&self) -> Version {
111        self.head().version
112    }
113
114    /// Returns request's headers.
115    #[inline]
116    pub fn headers(&self) -> &HeaderMap {
117        &self.head().headers
118    }
119
120    /// Returns mutable request's headers.
121    pub fn headers_mut(&mut self) -> &mut HeaderMap {
122        &mut self.head_mut().headers
123    }
124
125    /// The target path of this Request.
126    #[inline]
127    pub fn path(&self) -> &str {
128        self.head().uri.path().as_str()
129    }
130
131    /// The query string in the URL.
132    ///
133    /// E.g., id=10
134    #[inline]
135    pub fn query_string(&self) -> &str {
136        self.uri().query().map_or("", urly::Query::as_str)
137    }
138
139    /// Peer socket address
140    ///
141    /// Peer address is actual socket address, if proxy is used in front of
142    /// ntex http server, then peer address would be address of this proxy.
143    ///
144    /// To get client connection information `ConnectionInfo` should be used.
145    #[inline]
146    pub fn peer_addr(&self) -> Option<net::SocketAddr> {
147        self.head()
148            .io
149            .as_ref()
150            .and_then(|io| io.query::<types::PeerAddr>().get().map(|addr| addr.0))
151    }
152
153    /// Take request's payload.
154    ///
155    /// The payload is replaced with an empty one, so subsequent calls return
156    /// an empty payload.
157    #[inline]
158    pub fn take_payload(&mut self) -> Payload {
159        self.payload.take()
160    }
161
162    /// Set request payload.
163    pub fn set_payload(&mut self, payload: Payload) {
164        self.payload = payload;
165    }
166
167    /// Get `ConnectionInfo` for the current request.
168    ///
169    /// Forwarding headers are used as configured by
170    /// [`WebAppConfig::set_forwarded`](crate::web::WebAppConfig::set_forwarded).
171    pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
172        ConnectionInfo::get(self.head(), self.app_config())
173    }
174
175    /// Get a reference to the Path parameters.
176    ///
177    /// Params is a container for url parameters.
178    /// A variable segment is specified in the form `{identifier}`,
179    /// where the identifier can be used later in a request handler to
180    /// access the matched value for that segment.
181    #[inline]
182    pub fn match_info(&self) -> &Path<Url> {
183        self.req.match_info()
184    }
185
186    /// Get a mutable reference to the Path parameters.
187    #[inline]
188    pub fn match_info_mut(&mut self) -> &mut Path<Url> {
189        self.req.match_info_mut()
190    }
191
192    /// Get a reference to a `ResourceMap` of current application.
193    #[inline]
194    pub fn resource_map(&self) -> &ResourceMap {
195        self.req.resource_map()
196    }
197
198    /// Service configuration
199    #[inline]
200    pub fn app_config(&self) -> &WebAppConfig {
201        self.req.app_config()
202    }
203
204    /// Get a configuration value stored with [`WebAppConfig::set_value()`].
205    #[inline]
206    pub fn app_value<T: 'static>(&self) -> Option<&T> {
207        self.req.app_value()
208    }
209
210    #[inline]
211    #[doc(hidden)]
212    #[deprecated(since = "4.7.0", note = "use `WebRequest::app_value()` instead")]
213    pub fn app_state<T: 'static>(&self) -> Option<&T> {
214        self.app_value()
215    }
216
217    /// Request extensions
218    #[inline]
219    pub fn extensions(&self) -> Ref<'_, Extensions> {
220        self.req.extensions()
221    }
222
223    /// Mutable reference to a the request's extensions
224    #[inline]
225    pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
226        self.req.extensions_mut()
227    }
228
229    /// Get request state ref.
230    #[inline]
231    pub fn st(&self) -> &St {
232        &self.state
233    }
234
235    /// Get request state mut ref
236    #[inline]
237    pub fn st_mut(&mut self) -> &mut St {
238        &mut self.state
239    }
240
241    /// Transform the request state into a new type.
242    ///
243    /// This method consumes the request and returns request with different
244    /// state a `WebRequest<NewSt>`. The HTTP request and payload are preserved.
245    /// It is useful in application and resource filters that add
246    /// request-specific data before passing the request to the next service.
247    ///
248    /// Application state is not affected; only the state stored in this
249    /// `WebRequest` is replaced.
250    ///
251    /// ```rust
252    /// use std::convert::Infallible;
253    /// use ntex::web::{self, WebRequest};
254    ///
255    /// async fn index(_: &(), user_id: usize) -> String {
256    ///     format!("User {user_id}")
257    /// }
258    ///
259    /// web::App::default()
260    ///     .filter(async |req: WebRequest<()>| {
261    ///         Ok::<_, Infallible>(req.map_state(|()| 42usize))
262    ///     })
263    ///     .service(web::resource("/").to_with_state(index));
264    /// ```
265    #[inline]
266    pub fn map_state<F, NewSt>(self, f: F) -> WebRequest<NewSt>
267    where
268        F: FnOnce(St) -> NewSt,
269    {
270        let WebRequest {
271            req,
272            payload,
273            state,
274        } = self;
275
276        WebRequest {
277            req,
278            payload,
279            state: f(state),
280        }
281    }
282}
283
284impl<St> Resource<Url> for WebRequest<St> {
285    fn path(&self) -> &str {
286        self.match_info().path()
287    }
288
289    fn resource_path(&mut self) -> &mut Path<Url> {
290        self.match_info_mut()
291    }
292}
293
294impl<St> HttpMessage for WebRequest<St> {
295    #[inline]
296    /// Returns Request's headers.
297    fn message_headers(&self) -> &HeaderMap {
298        &self.head().headers
299    }
300
301    /// Request extensions
302    #[inline]
303    fn message_extensions(&self) -> Ref<'_, Extensions> {
304        self.req.extensions()
305    }
306
307    /// Mutable reference to a the request's extensions
308    #[inline]
309    fn message_extensions_mut(&self) -> RefMut<'_, Extensions> {
310        self.req.extensions_mut()
311    }
312}
313
314impl<St> fmt::Debug for WebRequest<St> {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        writeln!(
317            f,
318            "\nWebRequest {:?} {}:{}",
319            self.head().version,
320            self.head().method,
321            self.path()
322        )?;
323        if !self.query_string().is_empty() {
324            writeln!(f, "  query: ?{:?}", self.query_string())?;
325        }
326        if !self.match_info().is_empty() {
327            writeln!(f, "  params: {:?}", self.match_info())?;
328        }
329        writeln!(f, "  headers:")?;
330        for (key, val) in self.headers() {
331            if key == header::AUTHORIZATION {
332                writeln!(f, "    {key:?}: <REDACTED>")?;
333            } else {
334                writeln!(f, "    {key:?}: {val:?}")?;
335            }
336        }
337        Ok(())
338    }
339}
340
341#[cfg(test)]
342mod tests {
343    use crate::http::{self, HttpMessage, header};
344    use crate::web::{HttpResponse, test::TestRequest};
345
346    /// STATEMENT: `WebRequest` exposes mutable message data and redacts authorization in debug output.
347    ///
348    /// HOW:
349    /// - Check the default version and absent peer, then render an overflow error as status 413.
350    /// - Mutate headers and extensions through both accessor families and assert shared changes.
351    /// - Format the request and assert its authorization header is redacted.
352    #[test]
353    fn test_request() {
354        let mut req = TestRequest::default().to_srv_request();
355        assert_eq!(req.head_mut().version, http::Version::HTTP_11);
356        assert!(req.peer_addr().is_none());
357        let err = http::error::PayloadError::Overflow;
358
359        let res: HttpResponse = req.error_response::<(), _>(&(), &err).into();
360        assert_eq!(res.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
361
362        let mut req = TestRequest::default().to_srv_request();
363        req.headers_mut().insert(
364            header::CONTENT_TYPE,
365            header::HeaderValue::from_static("text"),
366        );
367        req.headers_mut().insert(
368            header::AUTHORIZATION,
369            header::HeaderValue::from_static("text"),
370        );
371        req.headers_mut().remove(header::CONTENT_TYPE);
372        assert!(!req.headers().contains_key(header::CONTENT_TYPE));
373        assert!(!req.message_headers().contains_key(header::CONTENT_TYPE));
374
375        req.extensions_mut().insert("TEXT".to_string());
376        assert_eq!(req.message_extensions().get::<String>().unwrap(), "TEXT");
377        req.message_extensions_mut().remove::<String>();
378        assert!(!req.extensions().contains::<String>());
379
380        let t = format!("{req:?}");
381        assert!(t.contains("\"authorization\": <REDACTED>"));
382    }
383
384    /// STATEMENT: Request reconstruction preserves paths and state and transfers payload ownership.
385    ///
386    /// HOW:
387    /// - Reconstruct `/path` and assert its path, absent I/O, missing resource, and empty payload.
388    /// - Take a nonempty payload, verify its source is drained, and install it on another request.
389    /// - Build from parts with numeric state and assert that state is retained.
390    #[test]
391    fn test_request_parts() {
392        use crate::web::{WebRequest, types::Payload};
393
394        let (req, _, ()) = TestRequest::with_uri("/path").to_http_parts();
395        let mut wreq = WebRequest::from_request(req.clone());
396        assert_eq!(wreq.path(), "/path");
397        assert!(wreq.io().is_none());
398        assert!(
399            wreq.resource_map()
400                .url_for(&req, "unknown", [""; 0])
401                .is_err()
402        );
403
404        assert!(matches!(wreq.take_payload(), crate::http::Payload::None));
405
406        let mut preq = TestRequest::default().payload("data").to_srv_request();
407        let payload = Payload(preq.take_payload()).into_inner();
408        assert!(!matches!(payload, crate::http::Payload::None));
409        assert!(matches!(preq.take_payload(), crate::http::Payload::None));
410        wreq.set_payload(payload);
411        assert!(!matches!(wreq.take_payload(), crate::http::Payload::None));
412
413        let wreq = WebRequest::from_parts(req, crate::http::Payload::None, 10usize);
414        assert_eq!(*wreq.st(), 10);
415    }
416
417    /// STATEMENT: Debug output includes route parameters for both web and HTTP requests.
418    ///
419    /// HOW:
420    /// - Build each request kind with an `id` parameter and format it with `Debug`.
421    /// - Assert both include a parameters section and the web request includes the parameter name.
422    #[test]
423    fn test_request_debug_params() {
424        let req = TestRequest::with_uri("/test")
425            .param("id", "10")
426            .to_srv_request();
427        let s = format!("{req:?}");
428        assert!(s.contains("params:"), "{s}");
429        assert!(s.contains("id"), "{s}");
430
431        let req = TestRequest::with_uri("/test")
432            .param("id", "10")
433            .to_http_request();
434        let s = format!("{req:?}");
435        assert!(s.contains("params:"), "{s}");
436    }
437}