Skip to main content

ntex/http/
httpmessage.rs

1use std::cell::{Ref, RefMut};
2use std::str;
3
4use encoding_rs::{Encoding, UTF_8};
5use mime::Mime;
6use ntex_http::header;
7
8#[cfg(feature = "cookie")]
9use coo_kie::Cookie;
10
11use super::error::{ContentTypeError, DecodeError};
12use super::header::HeaderMap;
13use crate::util::Extensions;
14
15#[cfg(feature = "cookie")]
16struct Cookies(Vec<Cookie<'static>>);
17
18/// Common operations for HTTP requests and responses.
19pub trait HttpMessage: Sized {
20    /// Returns the message headers.
21    fn message_headers(&self) -> &HeaderMap;
22
23    /// Returns the message extensions.
24    fn message_extensions(&self) -> Ref<'_, Extensions>;
25
26    /// Returns mutable access to the message extensions.
27    fn message_extensions_mut(&self) -> RefMut<'_, Extensions>;
28
29    /// Returns the media type from the `Content-Type` header.
30    ///
31    /// Parameters such as `charset` are omitted. Returns an empty string when
32    /// the header is missing or is not valid UTF-8.
33    fn content_type(&self) -> &str {
34        if let Some(content_type) = self.message_headers().get(header::CONTENT_TYPE)
35            && let Ok(content_type) = content_type.to_str()
36        {
37            return content_type.split(';').next().unwrap().trim();
38        }
39        ""
40    }
41
42    /// Returns the character encoding declared by `Content-Type`.
43    ///
44    /// UTF-8 is returned when the header or its `charset` parameter is absent.
45    ///
46    /// # Errors
47    ///
48    /// Returns [`ContentTypeError::ParseError`] for an invalid media type or
49    /// [`ContentTypeError::UnknownEncoding`] for an unknown charset.
50    fn encoding(&self) -> Result<&'static Encoding, ContentTypeError> {
51        if let Some(mime_type) = self.mime_type()? {
52            if let Some(charset) = mime_type.get_param("charset") {
53                if let Some(enc) = Encoding::for_label_no_replacement(charset.as_str().as_bytes()) {
54                    Ok(enc)
55                } else {
56                    Err(ContentTypeError::UnknownEncoding)
57                }
58            } else {
59                Ok(UTF_8)
60            }
61        } else {
62            Ok(UTF_8)
63        }
64    }
65
66    /// Parses the `Content-Type` header as a MIME type.
67    ///
68    /// # Errors
69    ///
70    /// Returns [`ContentTypeError::ParseError`] when the header is not valid
71    /// UTF-8 or does not contain a valid MIME value.
72    fn mime_type(&self) -> Result<Option<Mime>, ContentTypeError> {
73        if let Some(content_type) = self.message_headers().get(header::CONTENT_TYPE) {
74            if let Ok(content_type) = content_type.to_str() {
75                return match content_type.parse() {
76                    Ok(mt) => Ok(Some(mt)),
77                    Err(_) => Err(ContentTypeError::ParseError),
78                };
79            }
80            Err(ContentTypeError::ParseError)
81        } else {
82            Ok(None)
83        }
84    }
85
86    /// Returns whether `Transfer-Encoding` contains `chunked`.
87    ///
88    /// # Errors
89    ///
90    /// Returns [`DecodeError::Header`] when the header value is not valid
91    /// UTF-8.
92    fn chunked(&self) -> Result<bool, DecodeError> {
93        if let Some(encodings) = self.message_headers().get(header::TRANSFER_ENCODING) {
94            if let Ok(s) = encodings.to_str() {
95                Ok(s.to_lowercase().contains("chunked"))
96            } else {
97                Err(DecodeError::Header)
98            }
99        } else {
100            Ok(false)
101        }
102    }
103
104    #[cfg(feature = "cookie")]
105    /// Parses and caches cookies from the `Cookie` headers.
106    ///
107    /// Each `name=value` pair is parsed separately; pairs that are not valid
108    /// UTF-8 or cannot be parsed are skipped.
109    ///
110    /// # Errors
111    ///
112    /// The default implementation does not return an error.
113    fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, coo_kie::ParseError> {
114        if self.message_extensions().get::<Cookies>().is_none() {
115            let mut cookies = Vec::new();
116            for hdr in self.message_headers().get_all(header::COOKIE) {
117                for pair in hdr.as_bytes().split(|b| *b == b';') {
118                    if let Ok(pair) = str::from_utf8(pair)
119                        && let Ok(cookie) = Cookie::parse_encoded(pair)
120                    {
121                        cookies.push(cookie.into_owned());
122                    }
123                }
124            }
125            self.message_extensions_mut().insert(Cookies(cookies));
126        }
127        Ok(Ref::map(self.message_extensions(), |ext| {
128            &ext.get::<Cookies>().unwrap().0
129        }))
130    }
131
132    #[cfg(feature = "cookie")]
133    /// Returns the first request cookie with the given name.
134    fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
135        if let Ok(cookies) = self.cookies() {
136            for cookie in cookies.iter() {
137                if cookie.name() == name {
138                    return Some(cookie.to_owned());
139                }
140            }
141        }
142        None
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use encoding_rs::ISO_8859_2;
149
150    use super::*;
151    use crate::http::test::TestRequest;
152
153    /// STATEMENT: Content-type access returns only the media type and treats an absent header as empty.
154    ///
155    /// HOW:
156    /// - Query plain, parameterized, and missing content-type headers and compare their strings.
157    #[test]
158    fn test_content_type() {
159        let req = TestRequest::with_header("content-type", "text/plain").build();
160        assert_eq!(req.content_type(), "text/plain");
161        let req =
162            TestRequest::with_header("content-type", "application/json; charset=utf=8").build();
163        assert_eq!(req.content_type(), "application/json");
164        let req = TestRequest::builder().build();
165        assert_eq!(req.content_type(), "");
166    }
167
168    /// STATEMENT: MIME parsing preserves media type parameters and distinguishes a missing header.
169    ///
170    /// HOW:
171    /// - Parse JSON headers with and without a charset and inspect type, subtype, and parameter values.
172    /// - Verify an absent header yields no MIME type.
173    #[test]
174    fn test_mime_type() {
175        let req = TestRequest::with_header("content-type", "application/json").build();
176        assert_eq!(req.mime_type().unwrap(), Some(mime::APPLICATION_JSON));
177        let req = TestRequest::builder().build();
178        assert_eq!(req.mime_type().unwrap(), None);
179        let req =
180            TestRequest::with_header("content-type", "application/json; charset=utf-8").build();
181        let mt = req.mime_type().unwrap().unwrap();
182        assert_eq!(mt.get_param(mime::CHARSET), Some(mime::UTF_8));
183        assert_eq!(mt.type_(), mime::APPLICATION);
184        assert_eq!(mt.subtype(), mime::JSON);
185    }
186
187    /// STATEMENT: Malformed media types return a content-type parse error.
188    ///
189    /// HOW:
190    /// - Supply a content type without valid type/subtype syntax and inspect the error.
191    #[test]
192    fn test_mime_type_error() {
193        let req =
194            TestRequest::with_header("content-type", "applicationadfadsfasdflknadsfklnadsfjson")
195                .build();
196        assert_eq!(Err(ContentTypeError::ParseError), req.mime_type());
197    }
198
199    /// STATEMENT: Message encoding defaults to UTF-8 and honors a recognized charset.
200    ///
201    /// HOW:
202    /// - Inspect encoding with no header, JSON without charset, and an explicit ISO-8859-2 charset.
203    #[test]
204    fn test_encoding() {
205        let req = TestRequest::builder().build();
206        assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
207
208        let req = TestRequest::with_header("content-type", "application/json").build();
209        assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
210
211        let req = TestRequest::with_header("content-type", "application/json; charset=ISO-8859-2")
212            .build();
213        assert_eq!(ISO_8859_2, req.encoding().unwrap());
214    }
215
216    /// STATEMENT: Encoding lookup distinguishes malformed content types from unknown charsets.
217    ///
218    /// HOW:
219    /// - Supply each invalid form and compare the parse and unknown-encoding errors.
220    #[test]
221    fn test_encoding_error() {
222        let req = TestRequest::with_header("content-type", "applicatjson").build();
223        assert_eq!(Some(ContentTypeError::ParseError), req.encoding().err());
224
225        let req =
226            TestRequest::with_header("content-type", "application/json; charset=kkkttktk").build();
227        assert_eq!(
228            Some(ContentTypeError::UnknownEncoding),
229            req.encoding().err()
230        );
231    }
232
233    /// STATEMENT: Chunked detection handles absent, valid, and non-text transfer-encoding headers.
234    ///
235    /// HOW:
236    /// - Query requests with each header form and verify false, true, and error results respectively.
237    #[test]
238    fn test_chunked() {
239        let req = TestRequest::builder().build();
240        assert!(!req.chunked().unwrap());
241
242        let req = TestRequest::with_header(header::TRANSFER_ENCODING, "chunked").build();
243        assert!(req.chunked().unwrap());
244
245        let req = TestRequest::builder()
246            .header(
247                header::TRANSFER_ENCODING,
248                b"some va\xadscc\xacas0xsdasdlue".as_ref(),
249            )
250            .build();
251        assert!(req.chunked().is_err());
252    }
253
254    /// STATEMENT: MIME parsing rejects content-type values containing non-UTF-8 bytes.
255    ///
256    /// HOW:
257    /// - Construct a raw header containing an invalid byte and verify a parse error.
258    #[test]
259    fn test_mime_type_not_utf8() {
260        let req = TestRequest::default()
261            .header(
262                header::CONTENT_TYPE,
263                header::HeaderValue::from_bytes(b"text/\xff").unwrap(),
264            )
265            .build();
266        assert_eq!(req.mime_type(), Err(ContentTypeError::ParseError));
267    }
268
269    /// STATEMENT: A malformed request cookie pair is skipped without hiding the valid pairs
270    /// around it.
271    ///
272    /// HOW:
273    /// - Send `Cookie` headers `sid=ok; garbage; =x; a=b` and `c\xff=1; d=2`, where
274    ///   `garbage`, `=x`, and the non-UTF-8 pair cannot be parsed.
275    /// - Confirm `cookies` returns `sid`, `a`, and `d` in order and `cookie("sid")` finds `ok`.
276    #[cfg(feature = "cookie")]
277    #[test]
278    fn test_cookie_malformed_pair() {
279        let req = TestRequest::default()
280            .header(header::COOKIE, "sid=ok; garbage; =x; a=b")
281            .header(
282                header::COOKIE,
283                header::HeaderValue::from_bytes(b"c\xff=1; d=2").unwrap(),
284            )
285            .build();
286        let names: Vec<_> = req
287            .cookies()
288            .unwrap()
289            .iter()
290            .map(|c| (c.name().to_owned(), c.value().to_owned()))
291            .collect();
292        assert_eq!(
293            names,
294            [
295                ("sid".into(), "ok".into()),
296                ("a".into(), "b".into()),
297                ("d".into(), "2".into())
298            ]
299        );
300        assert_eq!(req.cookie("sid").unwrap().value(), "ok");
301    }
302
303    /// STATEMENT: Cookie lookup returns no match for an absent name after parsing a trailing separator.
304    ///
305    /// HOW:
306    /// - Parse one cookie followed by a semicolon, verify the parsed count, and query a different name.
307    #[cfg(feature = "cookie")]
308    #[test]
309    fn test_cookie_not_found() {
310        let req = TestRequest::default()
311            .header(header::COOKIE, "c1=v1; ")
312            .build();
313        assert_eq!(req.cookies().unwrap().len(), 1);
314        assert!(req.cookie("c2").is_none());
315    }
316}