ntex 4.0.0-beta.17

Framework for composable network services
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use std::{cell::Ref, cell::RefMut, fmt, net};

use urly::Url;

use crate::http::header;
use crate::http::{HeaderMap, HttpMessage, Method, Payload, RequestHead, Response, Version};
use crate::io::{IoRef, types};
use crate::router::{Path, Resource};
use crate::util::Extensions;

use super::config::WebAppConfig;
use super::info::ConnectionInfo;
use super::rmap::ResourceMap;
use super::{HttpRequest, State, WebResponse, WebResponseError};

/// An service http request
///
/// `WebRequest` allows mutable access to request's internal structures
pub struct WebRequest<St = ()> {
    pub(crate) req: HttpRequest,
    payload: Payload,
    state: St,
}

impl<St> WebRequest<St> {
    /// Construct web request
    pub(crate) fn new(req: HttpRequest, payload: Payload, state: St) -> Self {
        WebRequest {
            req,
            payload,
            state,
        }
    }

    /// Create web response for error
    #[inline]
    pub fn error_response<AppSt, E>(self, st: &AppSt, err: &E) -> WebResponse
    where
        AppSt: State,
        E: WebResponseError<AppSt, AppSt::Error>,
    {
        WebResponse::new(err.error_response(st), self.req)
    }
}

impl WebRequest<()> {
    /// Construct request from request.
    pub fn from_request(req: HttpRequest) -> Self {
        WebRequest {
            req,
            payload: Payload::None,
            state: (),
        }
    }
}

impl<St> WebRequest<St> {
    /// Deconstruct request into parts
    pub fn into_parts(self) -> (HttpRequest, Payload, St) {
        (self.req, self.payload, self.state)
    }

    /// Construct request from parts.
    pub fn from_parts(req: HttpRequest, payload: Payload, state: St) -> Self {
        WebRequest {
            req,
            payload,
            state,
        }
    }

    /// Create web response
    #[inline]
    pub fn into_response<R: Into<Response>>(self, res: R) -> WebResponse {
        WebResponse::new(res.into(), self.req)
    }

    /// Io reference for current connection
    #[inline]
    pub fn io(&self) -> Option<&IoRef> {
        self.head().io.as_ref()
    }

    /// This method returns reference to the request head
    #[inline]
    pub fn head(&self) -> &RequestHead {
        self.req.head()
    }

    /// This method returns mutable reference to the request head
    #[inline]
    pub fn head_mut(&mut self) -> &mut RequestHead {
        self.req.head_mut()
    }

    /// Request's uri.
    #[inline]
    pub fn uri(&self) -> &Url {
        &self.head().uri
    }

    /// Read the Request method.
    #[inline]
    pub fn method(&self) -> &Method {
        &self.head().method
    }

    /// Read the Request Version.
    #[inline]
    pub fn version(&self) -> Version {
        self.head().version
    }

    /// Returns request's headers.
    #[inline]
    pub fn headers(&self) -> &HeaderMap {
        &self.head().headers
    }

    /// Returns mutable request's headers.
    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        &mut self.head_mut().headers
    }

    /// The target path of this Request.
    #[inline]
    pub fn path(&self) -> &str {
        self.head().uri.path().as_str()
    }

    /// The query string in the URL.
    ///
    /// E.g., id=10
    #[inline]
    pub fn query_string(&self) -> &str {
        self.uri().query().map_or("", urly::Query::as_str)
    }

    /// Peer socket address
    ///
    /// Peer address is actual socket address, if proxy is used in front of
    /// ntex http server, then peer address would be address of this proxy.
    ///
    /// To get client connection information `ConnectionInfo` should be used.
    #[inline]
    pub fn peer_addr(&self) -> Option<net::SocketAddr> {
        self.head()
            .io
            .as_ref()
            .and_then(|io| io.query::<types::PeerAddr>().get().map(|addr| addr.0))
    }

    /// Take request's payload.
    ///
    /// The payload is replaced with an empty one, so subsequent calls return
    /// an empty payload.
    #[inline]
    pub fn take_payload(&mut self) -> Payload {
        self.payload.take()
    }

    /// Set request payload.
    pub fn set_payload(&mut self, payload: Payload) {
        self.payload = payload;
    }

    /// Get `ConnectionInfo` for the current request.
    pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
        ConnectionInfo::get(self.head(), self.app_config())
    }

    /// Get a reference to the Path parameters.
    ///
    /// Params is a container for url parameters.
    /// A variable segment is specified in the form `{identifier}`,
    /// where the identifier can be used later in a request handler to
    /// access the matched value for that segment.
    #[inline]
    pub fn match_info(&self) -> &Path<Url> {
        self.req.match_info()
    }

    /// Get a mutable reference to the Path parameters.
    #[inline]
    pub fn match_info_mut(&mut self) -> &mut Path<Url> {
        self.req.match_info_mut()
    }

    /// Get a reference to a `ResourceMap` of current application.
    #[inline]
    pub fn resource_map(&self) -> &ResourceMap {
        self.req.resource_map()
    }

    /// Service configuration
    #[inline]
    pub fn app_config(&self) -> &WebAppConfig {
        self.req.app_config()
    }

    /// Get an application state.
    #[inline]
    pub fn app_state<T: 'static>(&self) -> Option<&T> {
        (self.req).app_config().state()
    }

    /// Request extensions
    #[inline]
    pub fn extensions(&self) -> Ref<'_, Extensions> {
        self.req.extensions()
    }

    /// Mutable reference to a the request's extensions
    #[inline]
    pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
        self.req.extensions_mut()
    }

    /// Get request state ref.
    #[inline]
    pub fn st(&self) -> &St {
        &self.state
    }

    /// Get request state mut ref
    #[inline]
    pub fn st_mut(&mut self) -> &mut St {
        &mut self.state
    }

    /// Transform the request state into a new type.
    ///
    /// This method consumes the request and returns request with different
    /// state a `WebRequest<NewSt>`. The HTTP request and payload are preserved.
    /// It is useful in application and resource filters that add
    /// request-specific data before passing the request to the next service.
    ///
    /// Application state is not affected; only the state stored in this
    /// `WebRequest` is replaced.
    ///
    /// ```rust
    /// use std::convert::Infallible;
    /// use ntex::web::{self, WebRequest};
    ///
    /// async fn index(_: &(), user_id: usize) -> String {
    ///     format!("User {user_id}")
    /// }
    ///
    /// web::App::default()
    ///     .filter(async |req: WebRequest<()>| {
    ///         Ok::<_, Infallible>(req.map_state(|()| 42usize))
    ///     })
    ///     .service(web::resource("/").to_with_state(index));
    /// ```
    #[inline]
    pub fn map_state<F, NewSt>(self, f: F) -> WebRequest<NewSt>
    where
        F: FnOnce(St) -> NewSt,
    {
        let WebRequest {
            req,
            payload,
            state,
        } = self;

        WebRequest {
            req,
            payload,
            state: f(state),
        }
    }
}

impl<St> Resource<Url> for WebRequest<St> {
    fn path(&self) -> &str {
        self.match_info().path()
    }

    fn resource_path(&mut self) -> &mut Path<Url> {
        self.match_info_mut()
    }
}

impl<St> HttpMessage for WebRequest<St> {
    #[inline]
    /// Returns Request's headers.
    fn message_headers(&self) -> &HeaderMap {
        &self.head().headers
    }

    /// Request extensions
    #[inline]
    fn message_extensions(&self) -> Ref<'_, Extensions> {
        self.req.extensions()
    }

    /// Mutable reference to a the request's extensions
    #[inline]
    fn message_extensions_mut(&self) -> RefMut<'_, Extensions> {
        self.req.extensions_mut()
    }
}

impl<St> fmt::Debug for WebRequest<St> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "\nWebRequest {:?} {}:{}",
            self.head().version,
            self.head().method,
            self.path()
        )?;
        if !self.query_string().is_empty() {
            writeln!(f, "  query: ?{:?}", self.query_string())?;
        }
        if !self.match_info().is_empty() {
            writeln!(f, "  params: {:?}", self.match_info())?;
        }
        writeln!(f, "  headers:")?;
        for (key, val) in self.headers() {
            if key == header::AUTHORIZATION {
                writeln!(f, "    {key:?}: <REDACTED>")?;
            } else {
                writeln!(f, "    {key:?}: {val:?}")?;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::http::{self, HttpMessage, header};
    use crate::web::{HttpResponse, test::TestRequest};

    #[test]
    fn test_request() {
        let mut req = TestRequest::default().to_srv_request();
        assert_eq!(req.head_mut().version, http::Version::HTTP_11);
        assert!(req.peer_addr().is_none());
        let err = http::error::PayloadError::Overflow;

        let res: HttpResponse = req.error_response::<(), _>(&(), &err).into();
        assert_eq!(res.status(), http::StatusCode::PAYLOAD_TOO_LARGE);

        let mut req = TestRequest::default().to_srv_request();
        req.headers_mut().insert(
            header::CONTENT_TYPE,
            header::HeaderValue::from_static("text"),
        );
        req.headers_mut().insert(
            header::AUTHORIZATION,
            header::HeaderValue::from_static("text"),
        );
        req.headers_mut().remove(header::CONTENT_TYPE);
        assert!(!req.headers().contains_key(header::CONTENT_TYPE));
        assert!(!req.message_headers().contains_key(header::CONTENT_TYPE));

        req.extensions_mut().insert("TEXT".to_string());
        assert_eq!(req.message_extensions().get::<String>().unwrap(), "TEXT");
        req.message_extensions_mut().remove::<String>();
        assert!(!req.extensions().contains::<String>());

        let t = format!("{req:?}");
        assert!(t.contains("\"authorization\": <REDACTED>"));
    }

    #[test]
    fn test_request_parts() {
        use crate::web::{WebRequest, types::Payload};

        let (req, _, ()) = TestRequest::with_uri("/path").to_http_parts();
        let mut wreq = WebRequest::from_request(req.clone());
        assert_eq!(wreq.path(), "/path");
        assert!(wreq.io().is_none());
        assert!(
            wreq.resource_map()
                .url_for(&req, "unknown", [""; 0])
                .is_err()
        );

        assert!(matches!(wreq.take_payload(), crate::http::Payload::None));

        let mut preq = TestRequest::default().payload("data").to_srv_request();
        let payload = Payload(preq.take_payload()).into_inner();
        assert!(!matches!(payload, crate::http::Payload::None));
        assert!(matches!(preq.take_payload(), crate::http::Payload::None));
        wreq.set_payload(payload);
        assert!(!matches!(wreq.take_payload(), crate::http::Payload::None));

        let wreq = WebRequest::from_parts(req, crate::http::Payload::None, 10usize);
        assert_eq!(*wreq.st(), 10);
    }

    #[test]
    fn test_request_debug_params() {
        let req = TestRequest::with_uri("/test")
            .param("id", "10")
            .to_srv_request();
        let s = format!("{req:?}");
        assert!(s.contains("params:"), "{s}");
        assert!(s.contains("id"), "{s}");

        let req = TestRequest::with_uri("/test")
            .param("id", "10")
            .to_http_request();
        let s = format!("{req:?}");
        assert!(s.contains("params:"), "{s}");
    }
}