ntex 4.6.0

Framework for composable network services
Documentation
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! `Middleware` for compressing response body.
use crate::http::encoding::Encoder;
use crate::http::header::{ACCEPT_ENCODING, ContentEncoding};
use crate::service::{Ctx, Middleware, Service};
use crate::web::{BodyEncoding, State, WebRequest, WebResponse};

#[derive(Debug, Clone)]
/// `Middleware` for compressing response body.
///
/// Bodies with a known size below 1KiB are sent uncompressed.
/// Use `BodyEncoding` trait for overriding response compression.
/// To disable compression set encoding to `ContentEncoding::Identity` value.
///
/// Each compressed response keeps its encoder until the body ends, up to
/// 1.5MiB for `zstd`, see [`crate::http::encoding`].
///
/// ```rust
/// use ntex::web::{self, middleware, App, HttpResponse};
///
/// fn main() {
///     let app = App::default()
///         .middleware(middleware::Compress::default())
///         .service(
///             web::resource("/test")
///                 .route(web::get().to(async || { HttpResponse::Ok() }))
///                 .route(web::head().to(async || { HttpResponse::MethodNotAllowed() }))
///         );
/// }
/// ```
pub struct Compress {
    enc: ContentEncoding,
}

impl Compress {
    /// Create new `Compress` middleware with the specified encoding.
    ///
    /// Use `Compress::default()` to select the encoding automatically
    /// ([`ContentEncoding::Auto`]).
    pub fn new(encoding: ContentEncoding) -> Self {
        Compress { enc: encoding }
    }
}

impl Default for Compress {
    fn default() -> Self {
        Compress::new(ContentEncoding::Auto)
    }
}

impl<S, St> Middleware<S, St> for Compress {
    type Service = CompressMiddleware<S>;

    fn create(&self, _: &St, service: S) -> Self::Service {
        CompressMiddleware {
            service,
            encoding: self.enc,
        }
    }
}

#[derive(Debug)]
pub struct CompressMiddleware<S> {
    service: S,
    encoding: ContentEncoding,
}

impl<S, St, In> Service<St, WebRequest<In>> for CompressMiddleware<S>
where
    S: Service<St, WebRequest<In>, Res = WebResponse>,
    St: State,
{
    type Res = WebResponse;
    type Error = S::Error;

    crate::forward!(St, service);

    async fn call(
        &self,
        req: WebRequest<In>,
        ctx: Ctx<'_, Self, St>,
    ) -> Result<WebResponse, S::Error> {
        // negotiate content-encoding
        let values = req
            .headers()
            .get_all(&ACCEPT_ENCODING)
            .filter_map(|val| val.to_str().ok());
        let encoding = AcceptEncoding::parse(values, self.encoding);

        let resp = ctx.call(&self.service, req).await?;

        let enc = if let Some(enc) = resp.response().get_encoding() {
            enc
        } else {
            encoding
        };

        Ok(resp.map_body(move |head, body| Encoder::response(enc, head, body)))
    }
}

/// Encodings that can be picked for a `*` entry.
const WILDCARD: [ContentEncoding; 3] = [
    ContentEncoding::Zstd,
    ContentEncoding::Gzip,
    ContentEncoding::Deflate,
];

#[derive(Debug, PartialEq)]
struct AcceptEncoding {
    /// `None` for the `*` entry
    encoding: Option<ContentEncoding>,
    /// Client weight in thousandths, `0..=1000`
    q: u16,
}

impl AcceptEncoding {
    fn new(tag: &str) -> Option<AcceptEncoding> {
        let mut parts = tag.split(';');
        let name = parts.next()?.trim();
        if name.is_empty() {
            return None;
        }
        let encoding = if name == "*" {
            None
        } else {
            Some(ContentEncoding::from(name))
        };

        // a malformed weight makes the entry unacceptable
        let q = parts
            .filter_map(|param| param.split_once('='))
            .find(|(name, _)| name.trim().eq_ignore_ascii_case("q"))
            .map_or(1000, |(_, val)| parse_q(val.trim()).unwrap_or(0));
        Some(AcceptEncoding { encoding, q })
    }

    /// Pick a response encoding from the `Accept-Encoding` header values.
    ///
    /// Entries are ranked by the client's `q` value, ties go to the
    /// server's preference. `q=0` means "not acceptable" and `*` covers
    /// every encoding the client did not list.
    fn parse<'a, I>(values: I, encoding: ContentEncoding) -> ContentEncoding
    where
        I: Iterator<Item = &'a str>,
    {
        let mut listed: Vec<(ContentEncoding, u16)> = Vec::new();
        let mut wildcard = None;
        for item in values.flat_map(|val| val.split(',')) {
            match AcceptEncoding::new(item) {
                Some(AcceptEncoding {
                    encoding: Some(enc),
                    q,
                }) => listed.push((enc, q)),
                Some(AcceptEncoding { encoding: None, q }) => {
                    wildcard.get_or_insert(q);
                }
                None => {}
            }
        }
        let weight = |enc: ContentEncoding| {
            listed
                .iter()
                .find(|(e, _)| *e == enc)
                .map(|(_, q)| *q)
                .or(wildcard)
                .unwrap_or(0)
        };

        if encoding != ContentEncoding::Auto {
            return if weight(encoding) > 0 {
                encoding
            } else {
                ContentEncoding::Identity
            };
        }

        let mut best: Option<(ContentEncoding, u16)> = None;
        let candidates = listed.iter().map(|(enc, _)| *enc).chain(WILDCARD);
        for enc in candidates.filter(|enc| Encoder::can_encode(*enc)) {
            let q = weight(enc);
            let better = match best {
                None => q > 0,
                Some((b, bq)) => q > bq || (q == bq && enc.quality() > b.quality()),
            };
            if better {
                best = Some((enc, q));
            }
        }
        best.map_or(ContentEncoding::Identity, |(enc, _)| enc)
    }
}

/// Parse an RFC 9110 `qvalue` into thousandths.
fn parse_q(val: &str) -> Option<u16> {
    let (int, frac) = match val.split_once('.') {
        Some((int, frac)) => (int, frac),
        None => (val, ""),
    };
    if frac.len() > 3 || !frac.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let int = match int {
        "0" => 0,
        "1" => 1000,
        _ => return None,
    };
    let frac = frac
        .bytes()
        .zip([100, 10, 1])
        .map(|(b, scale)| u16::from(b - b'0') * scale)
        .sum::<u16>();
    if int + frac > 1000 { None } else { Some(int + frac) }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(raw: &str, encoding: ContentEncoding) -> ContentEncoding {
        AcceptEncoding::parse([raw].into_iter(), encoding)
    }

    /// STATEMENT: Quality parsing accepts HTTP q-values with at most three fractional digits.
    ///
    /// HOW:
    /// - Parse valid zero/one and fractional values and assert their thousandths representation.
    /// - Assert empty, malformed, overprecise, negative, and out-of-range values are rejected.
    #[test]
    fn test_parse_q() {
        for (val, q) in [
            ("0", 0),
            ("0.", 0),
            ("0.5", 500),
            ("0.05", 50),
            ("0.125", 125),
            ("0.999", 999),
            ("1", 1000),
            ("1.", 1000),
            ("1.000", 1000),
        ] {
            assert_eq!(parse_q(val), Some(q), "{val}");
        }
        for val in [
            "", ".5", "0.1234", "1.001", "1.5", "2", "-0", "0.a", "0.00a", "01", "abc",
        ] {
            assert_eq!(parse_q(val), None, "{val}");
        }
    }

    /// STATEMENT: Encoding entries parse tokens, optional quality parameters, and wildcard values.
    ///
    /// HOW:
    /// - Check gzip defaults, whitespace, case-insensitive `q`, extra parameters, and invalid quality.
    /// - Assert wildcard has no specific encoding and an empty entry is ignored.
    #[test]
    fn test_accept_encoding_entry() {
        let entry = |tag| AcceptEncoding::new(tag).unwrap();
        assert_eq!(
            entry("gzip"),
            AcceptEncoding {
                encoding: Some(ContentEncoding::Gzip),
                q: 1000
            }
        );
        assert_eq!(entry(" gzip ; q=0.5 ").q, 500);
        assert_eq!(entry("gzip;Q=0.5").q, 500);
        assert_eq!(entry("gzip;level=1;q=0.25").q, 250);
        assert_eq!(entry("gzip;q=abc").q, 0);
        assert_eq!(entry("gzip;0.8").q, 1000);
        assert_eq!(entry("*;q=0.1").encoding, None);
        assert!(AcceptEncoding::new(" ").is_none());
    }

    /// STATEMENT: Automatic compression selects supported encodings rather than unsupported preferences.
    ///
    /// HOW:
    /// - Parse combinations of zstd, gzip, deflate, and Brotli with automatic selection.
    /// - Assert supported server preferences, identity fallback, whitespace handling, and explicit Brotli selection.
    #[test]
    fn test_auto_skips_unsupported_encodings() {
        let auto = ContentEncoding::Auto;
        assert_eq!(
            parse("gzip, deflate, br, zstd", auto),
            ContentEncoding::Zstd
        );
        assert_eq!(parse("gzip, deflate, br", auto), ContentEncoding::Gzip);
        assert_eq!(parse("br, deflate", auto), ContentEncoding::Deflate);
        assert_eq!(parse("br", auto), ContentEncoding::Identity);
        assert_eq!(parse("gzip, br", ContentEncoding::Br), ContentEncoding::Br);
        assert_eq!(parse(" br ,  gzip ; q=1.0 ", auto), ContentEncoding::Gzip);
        assert_eq!(parse("", auto), ContentEncoding::Identity);
    }

    /// STATEMENT: Automatic compression honors quality weights, first duplicates, and server tie-breaking.
    ///
    /// HOW:
    /// - Parse unequal, zero, malformed, and duplicate quality entries and assert the selected encoding.
    /// - Check equal weights follow server preference and `x-gzip` resolves to gzip.
    #[test]
    fn test_auto_honours_q() {
        let auto = ContentEncoding::Auto;
        assert_eq!(parse("gzip;q=0.5, zstd;q=0.1", auto), ContentEncoding::Gzip);
        assert_eq!(
            parse("deflate;q=0.9, gzip;q=0.8", auto),
            ContentEncoding::Deflate
        );
        assert_eq!(parse("zstd;q=0, gzip", auto), ContentEncoding::Gzip);
        assert_eq!(parse("gzip;q=0", auto), ContentEncoding::Identity);
        assert_eq!(parse("gzip;q=abc", auto), ContentEncoding::Identity);
        assert_eq!(parse("gzip;q=2, deflate", auto), ContentEncoding::Deflate);
        assert_eq!(parse("gzip, zstd;q=0", auto), ContentEncoding::Gzip);
        // the first entry for an encoding wins
        assert_eq!(parse("gzip;q=0, gzip", auto), ContentEncoding::Identity);
        // equal weights go to the server's preference
        assert_eq!(
            parse("deflate;q=0.5, gzip;q=0.5, zstd;q=0.5", auto),
            ContentEncoding::Zstd
        );
        assert_eq!(parse("deflate, gzip", auto), ContentEncoding::Gzip);
        assert_eq!(parse("x-gzip", auto), ContentEncoding::Gzip);
    }

    /// STATEMENT: Wildcard quality supplies defaults while explicit encoding weights take precedence.
    ///
    /// HOW:
    /// - Combine wildcard entries with explicit exclusions and weighted supported encodings.
    /// - Assert the selected encoding follows explicit weights, first wildcard, and identity fallback.
    #[test]
    fn test_auto_wildcard() {
        let auto = ContentEncoding::Auto;
        assert_eq!(parse("*", auto), ContentEncoding::Zstd);
        assert_eq!(parse("*;q=0", auto), ContentEncoding::Identity);
        assert_eq!(parse("*;q=0.5, zstd;q=0", auto), ContentEncoding::Gzip);
        assert_eq!(
            parse("zstd;q=0, gzip;q=0, *", auto),
            ContentEncoding::Deflate
        );
        assert_eq!(parse("*;q=0.5, deflate", auto), ContentEncoding::Deflate);
        assert_eq!(parse("gzip;q=0.1, *;q=0.5", auto), ContentEncoding::Zstd);
        assert_eq!(parse("*;q=0, gzip;q=0.1", auto), ContentEncoding::Gzip);
        assert_eq!(parse("*;q=0.5, *", auto), ContentEncoding::Zstd);
        assert_eq!(parse("*;q=0, *, zstd;q=0", auto), ContentEncoding::Identity);
    }

    /// STATEMENT: Explicit compression uses only the configured encoding when the client accepts it.
    ///
    /// HOW:
    /// - Configure gzip and parse direct matches, other encodings, zero/positive qualities, and wildcards.
    /// - Assert gzip is selected only when accepted, with explicit gzip weights overriding wildcards.
    #[test]
    fn test_explicit_encoding() {
        let gzip = ContentEncoding::Gzip;
        assert_eq!(parse("gzip", gzip), gzip);
        assert_eq!(parse("zstd", gzip), ContentEncoding::Identity);
        assert_eq!(parse("gzip;q=0", gzip), ContentEncoding::Identity);
        assert_eq!(parse("gzip;q=0.001", gzip), gzip);
        assert_eq!(parse("*", gzip), gzip);
        assert_eq!(parse("*;q=0", gzip), ContentEncoding::Identity);
        assert_eq!(parse("*, gzip;q=0", gzip), ContentEncoding::Identity);
        assert_eq!(parse("*;q=0, gzip", gzip), gzip);
    }

    /// STATEMENT: Encoding negotiation considers values from repeated request headers together.
    ///
    /// HOW:
    /// - Parse separate header values excluding zstd and weighting gzip above deflate.
    /// - Assert automatic negotiation selects gzip.
    #[test]
    fn test_repeated_headers() {
        let values = ["zstd;q=0", "gzip;q=0.5, deflate;q=0.1"];
        assert_eq!(
            AcceptEncoding::parse(values.into_iter(), ContentEncoding::Auto),
            ContentEncoding::Gzip
        );
    }

    /// STATEMENT: Compression middleware negotiates valid repeated headers and skips invalid or disabled encodings.
    ///
    /// HOW:
    /// - Serve a compressible body and assert gzip requests receive `Content-Encoding: gzip`.
    /// - Assert invalid-only and zero-quality headers produce no encoding.
    /// - Combine repeated valid/invalid values and assert gzip or deflate is selected from valid entries.
    #[crate::rt_test]
    async fn test_compress_accept_encoding() {
        use crate::http::header::{CONTENT_ENCODING, HeaderValue};
        use crate::web::test::{TestRequest, call_service, init_service};
        use crate::web::{self, App, HttpResponse};

        let srv = init_service(App::new().middleware(Compress::default()).route(
            "/",
            web::get().to(async || HttpResponse::Ok().body("a".repeat(1024))),
        ))
        .await;

        let req = TestRequest::default()
            .header(ACCEPT_ENCODING, "gzip")
            .to_request();
        let resp = call_service(&srv, req).await;
        assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "gzip");

        let req = TestRequest::default()
            .header(
                ACCEPT_ENCODING,
                HeaderValue::from_bytes(b"gzip\xff").unwrap(),
            )
            .to_request();
        let resp = call_service(&srv, req).await;
        assert!(resp.headers().get(CONTENT_ENCODING).is_none());

        let req = TestRequest::default()
            .header(ACCEPT_ENCODING, "zstd;q=0")
            .header(ACCEPT_ENCODING, "gzip;q=0.5")
            .to_request();
        let resp = call_service(&srv, req).await;
        assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "gzip");

        let req = TestRequest::default()
            .header(
                ACCEPT_ENCODING,
                HeaderValue::from_bytes(b"zstd\xff").unwrap(),
            )
            .header(ACCEPT_ENCODING, "deflate")
            .to_request();
        let resp = call_service(&srv, req).await;
        assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "deflate");

        let req = TestRequest::default()
            .header(ACCEPT_ENCODING, "gzip;q=0")
            .to_request();
        let resp = call_service(&srv, req).await;
        assert!(resp.headers().get(CONTENT_ENCODING).is_none());
    }
}