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
use std::cell::{Ref, RefMut};
use std::str;
use encoding_rs::{Encoding, UTF_8};
use mime::Mime;
use ntex_http::header;
#[cfg(feature = "cookie")]
use coo_kie::Cookie;
use super::error::{ContentTypeError, DecodeError};
use super::header::HeaderMap;
use crate::util::Extensions;
#[cfg(feature = "cookie")]
struct Cookies(Vec<Cookie<'static>>);
/// Common operations for HTTP requests and responses.
pub trait HttpMessage: Sized {
/// Returns the message headers.
fn message_headers(&self) -> &HeaderMap;
/// Returns the message extensions.
fn message_extensions(&self) -> Ref<'_, Extensions>;
/// Returns mutable access to the message extensions.
fn message_extensions_mut(&self) -> RefMut<'_, Extensions>;
/// Returns the media type from the `Content-Type` header.
///
/// Parameters such as `charset` are omitted. Returns an empty string when
/// the header is missing or is not valid UTF-8.
fn content_type(&self) -> &str {
if let Some(content_type) = self.message_headers().get(header::CONTENT_TYPE)
&& let Ok(content_type) = content_type.to_str()
{
return content_type.split(';').next().unwrap().trim();
}
""
}
/// Returns the character encoding declared by `Content-Type`.
///
/// UTF-8 is returned when the header or its `charset` parameter is absent.
///
/// # Errors
///
/// Returns [`ContentTypeError::ParseError`] for an invalid media type or
/// [`ContentTypeError::UnknownEncoding`] for an unknown charset.
fn encoding(&self) -> Result<&'static Encoding, ContentTypeError> {
if let Some(mime_type) = self.mime_type()? {
if let Some(charset) = mime_type.get_param("charset") {
if let Some(enc) = Encoding::for_label_no_replacement(charset.as_str().as_bytes()) {
Ok(enc)
} else {
Err(ContentTypeError::UnknownEncoding)
}
} else {
Ok(UTF_8)
}
} else {
Ok(UTF_8)
}
}
/// Parses the `Content-Type` header as a MIME type.
///
/// # Errors
///
/// Returns [`ContentTypeError::ParseError`] when the header is not valid
/// UTF-8 or does not contain a valid MIME value.
fn mime_type(&self) -> Result<Option<Mime>, ContentTypeError> {
if let Some(content_type) = self.message_headers().get(header::CONTENT_TYPE) {
if let Ok(content_type) = content_type.to_str() {
return match content_type.parse() {
Ok(mt) => Ok(Some(mt)),
Err(_) => Err(ContentTypeError::ParseError),
};
}
Err(ContentTypeError::ParseError)
} else {
Ok(None)
}
}
/// Returns whether `Transfer-Encoding` contains `chunked`.
///
/// # Errors
///
/// Returns [`DecodeError::Header`] when the header value is not valid
/// UTF-8.
fn chunked(&self) -> Result<bool, DecodeError> {
if let Some(encodings) = self.message_headers().get(header::TRANSFER_ENCODING) {
if let Ok(s) = encodings.to_str() {
Ok(s.to_lowercase().contains("chunked"))
} else {
Err(DecodeError::Header)
}
} else {
Ok(false)
}
}
#[cfg(feature = "cookie")]
/// Parses and caches cookies from the `Cookie` headers.
///
/// Each `name=value` pair is parsed separately; pairs that are not valid
/// UTF-8 or cannot be parsed are skipped.
///
/// # Errors
///
/// The default implementation does not return an error.
fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, coo_kie::ParseError> {
if self.message_extensions().get::<Cookies>().is_none() {
let mut cookies = Vec::new();
for hdr in self.message_headers().get_all(header::COOKIE) {
for pair in hdr.as_bytes().split(|b| *b == b';') {
if let Ok(pair) = str::from_utf8(pair)
&& let Ok(cookie) = Cookie::parse_encoded(pair)
{
cookies.push(cookie.into_owned());
}
}
}
self.message_extensions_mut().insert(Cookies(cookies));
}
Ok(Ref::map(self.message_extensions(), |ext| {
&ext.get::<Cookies>().unwrap().0
}))
}
#[cfg(feature = "cookie")]
/// Returns the first request cookie with the given name.
fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
if let Ok(cookies) = self.cookies() {
for cookie in cookies.iter() {
if cookie.name() == name {
return Some(cookie.to_owned());
}
}
}
None
}
}
#[cfg(test)]
mod tests {
use encoding_rs::ISO_8859_2;
use super::*;
use crate::http::test::TestRequest;
/// STATEMENT: Content-type access returns only the media type and treats an absent header as empty.
///
/// HOW:
/// - Query plain, parameterized, and missing content-type headers and compare their strings.
#[test]
fn test_content_type() {
let req = TestRequest::with_header("content-type", "text/plain").build();
assert_eq!(req.content_type(), "text/plain");
let req =
TestRequest::with_header("content-type", "application/json; charset=utf=8").build();
assert_eq!(req.content_type(), "application/json");
let req = TestRequest::builder().build();
assert_eq!(req.content_type(), "");
}
/// STATEMENT: MIME parsing preserves media type parameters and distinguishes a missing header.
///
/// HOW:
/// - Parse JSON headers with and without a charset and inspect type, subtype, and parameter values.
/// - Verify an absent header yields no MIME type.
#[test]
fn test_mime_type() {
let req = TestRequest::with_header("content-type", "application/json").build();
assert_eq!(req.mime_type().unwrap(), Some(mime::APPLICATION_JSON));
let req = TestRequest::builder().build();
assert_eq!(req.mime_type().unwrap(), None);
let req =
TestRequest::with_header("content-type", "application/json; charset=utf-8").build();
let mt = req.mime_type().unwrap().unwrap();
assert_eq!(mt.get_param(mime::CHARSET), Some(mime::UTF_8));
assert_eq!(mt.type_(), mime::APPLICATION);
assert_eq!(mt.subtype(), mime::JSON);
}
/// STATEMENT: Malformed media types return a content-type parse error.
///
/// HOW:
/// - Supply a content type without valid type/subtype syntax and inspect the error.
#[test]
fn test_mime_type_error() {
let req =
TestRequest::with_header("content-type", "applicationadfadsfasdflknadsfklnadsfjson")
.build();
assert_eq!(Err(ContentTypeError::ParseError), req.mime_type());
}
/// STATEMENT: Message encoding defaults to UTF-8 and honors a recognized charset.
///
/// HOW:
/// - Inspect encoding with no header, JSON without charset, and an explicit ISO-8859-2 charset.
#[test]
fn test_encoding() {
let req = TestRequest::builder().build();
assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
let req = TestRequest::with_header("content-type", "application/json").build();
assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
let req = TestRequest::with_header("content-type", "application/json; charset=ISO-8859-2")
.build();
assert_eq!(ISO_8859_2, req.encoding().unwrap());
}
/// STATEMENT: Encoding lookup distinguishes malformed content types from unknown charsets.
///
/// HOW:
/// - Supply each invalid form and compare the parse and unknown-encoding errors.
#[test]
fn test_encoding_error() {
let req = TestRequest::with_header("content-type", "applicatjson").build();
assert_eq!(Some(ContentTypeError::ParseError), req.encoding().err());
let req =
TestRequest::with_header("content-type", "application/json; charset=kkkttktk").build();
assert_eq!(
Some(ContentTypeError::UnknownEncoding),
req.encoding().err()
);
}
/// STATEMENT: Chunked detection handles absent, valid, and non-text transfer-encoding headers.
///
/// HOW:
/// - Query requests with each header form and verify false, true, and error results respectively.
#[test]
fn test_chunked() {
let req = TestRequest::builder().build();
assert!(!req.chunked().unwrap());
let req = TestRequest::with_header(header::TRANSFER_ENCODING, "chunked").build();
assert!(req.chunked().unwrap());
let req = TestRequest::builder()
.header(
header::TRANSFER_ENCODING,
b"some va\xadscc\xacas0xsdasdlue".as_ref(),
)
.build();
assert!(req.chunked().is_err());
}
/// STATEMENT: MIME parsing rejects content-type values containing non-UTF-8 bytes.
///
/// HOW:
/// - Construct a raw header containing an invalid byte and verify a parse error.
#[test]
fn test_mime_type_not_utf8() {
let req = TestRequest::default()
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_bytes(b"text/\xff").unwrap(),
)
.build();
assert_eq!(req.mime_type(), Err(ContentTypeError::ParseError));
}
/// STATEMENT: A malformed request cookie pair is skipped without hiding the valid pairs
/// around it.
///
/// HOW:
/// - Send `Cookie` headers `sid=ok; garbage; =x; a=b` and `c\xff=1; d=2`, where
/// `garbage`, `=x`, and the non-UTF-8 pair cannot be parsed.
/// - Confirm `cookies` returns `sid`, `a`, and `d` in order and `cookie("sid")` finds `ok`.
#[cfg(feature = "cookie")]
#[test]
fn test_cookie_malformed_pair() {
let req = TestRequest::default()
.header(header::COOKIE, "sid=ok; garbage; =x; a=b")
.header(
header::COOKIE,
header::HeaderValue::from_bytes(b"c\xff=1; d=2").unwrap(),
)
.build();
let names: Vec<_> = req
.cookies()
.unwrap()
.iter()
.map(|c| (c.name().to_owned(), c.value().to_owned()))
.collect();
assert_eq!(
names,
[
("sid".into(), "ok".into()),
("a".into(), "b".into()),
("d".into(), "2".into())
]
);
assert_eq!(req.cookie("sid").unwrap().value(), "ok");
}
/// STATEMENT: Cookie lookup returns no match for an absent name after parsing a trailing separator.
///
/// HOW:
/// - Parse one cookie followed by a semicolon, verify the parsed count, and query a different name.
#[cfg(feature = "cookie")]
#[test]
fn test_cookie_not_found() {
let req = TestRequest::default()
.header(header::COOKIE, "c1=v1; ")
.build();
assert_eq!(req.cookies().unwrap().len(), 1);
assert!(req.cookie("c2").is_none());
}
}