Skip to main content

ntex/web/middleware/
compress.rs

1//! `Middleware` for compressing response body.
2use crate::http::encoding::Encoder;
3use crate::http::header::{
4    ACCEPT_ENCODING, CONTENT_ENCODING, ContentEncoding, HeaderMap, HeaderValue, VARY,
5};
6use crate::service::{Ctx, Middleware, Service};
7use crate::web::{BodyEncoding, State, WebRequest, WebResponse};
8
9#[derive(Debug, Clone)]
10/// `Middleware` for compressing response body.
11///
12/// Bodies with a known size below 1KiB are sent uncompressed.
13/// Use `BodyEncoding` trait for overriding response compression.
14/// To disable compression set encoding to `ContentEncoding::Identity` value.
15///
16/// The encoding is negotiated from the request's `Accept-Encoding` header.
17/// `identity` is used instead of compression only if the client gives it a
18/// strictly higher weight, explicitly or via `*`. Responses whose encoding is
19/// negotiated get `Vary: Accept-Encoding`, so caches keep one copy per
20/// encoding. The header is not added if compression is disabled, if the
21/// response selects its encoding with `BodyEncoding` or already has a
22/// `Content-Encoding` header.
23///
24/// Each compressed response keeps its encoder until the body ends, up to
25/// 1.5MiB for `zstd`, see [`crate::http::encoding`].
26///
27/// ```rust
28/// use ntex::web::{self, middleware, App, HttpResponse};
29///
30/// fn main() {
31///     let app = App::default()
32///         .middleware(middleware::Compress::default())
33///         .service(
34///             web::resource("/test")
35///                 .route(web::get().to(async || { HttpResponse::Ok() }))
36///                 .route(web::head().to(async || { HttpResponse::MethodNotAllowed() }))
37///         );
38/// }
39/// ```
40pub struct Compress {
41    enc: ContentEncoding,
42}
43
44impl Compress {
45    /// Create new `Compress` middleware with the specified encoding.
46    ///
47    /// Use `Compress::default()` to select the encoding automatically
48    /// ([`ContentEncoding::Auto`]).
49    pub fn new(encoding: ContentEncoding) -> Self {
50        Compress { enc: encoding }
51    }
52}
53
54impl Default for Compress {
55    fn default() -> Self {
56        Compress::new(ContentEncoding::Auto)
57    }
58}
59
60impl<S, St> Middleware<S, St> for Compress {
61    type Service = CompressMiddleware<S>;
62
63    fn create(&self, _: &St, service: S) -> Self::Service {
64        CompressMiddleware {
65            service,
66            encoding: self.enc,
67        }
68    }
69}
70
71#[derive(Debug)]
72pub struct CompressMiddleware<S> {
73    service: S,
74    encoding: ContentEncoding,
75}
76
77impl<S, St, In> Service<St, WebRequest<In>> for CompressMiddleware<S>
78where
79    S: Service<St, WebRequest<In>, Res = WebResponse>,
80    St: State,
81{
82    type Res = WebResponse;
83    type Error = S::Error;
84
85    crate::forward!(St, service);
86
87    async fn call(
88        &self,
89        req: WebRequest<In>,
90        ctx: Ctx<'_, Self, St>,
91    ) -> Result<WebResponse, S::Error> {
92        // negotiate content-encoding
93        let values = req
94            .headers()
95            .get_all(&ACCEPT_ENCODING)
96            .filter_map(|val| val.to_str().ok());
97        let encoding = AcceptEncoding::parse(values, self.encoding);
98
99        let mut resp = ctx.call(&self.service, req).await?;
100
101        let enc = if let Some(enc) = resp.response().get_encoding() {
102            enc
103        } else {
104            if self.encoding != ContentEncoding::Identity
105                && !resp.headers().contains_key(CONTENT_ENCODING)
106            {
107                add_vary(resp.headers_mut());
108            }
109            encoding
110        };
111
112        Ok(resp.map_body(move |head, body| Encoder::response(enc, head, body)))
113    }
114}
115
116/// Add `accept-encoding` to the `Vary` header unless it is already covered.
117fn add_vary(headers: &mut HeaderMap) {
118    let covered = headers
119        .get_all(VARY)
120        .filter_map(|val| val.to_str().ok())
121        .flat_map(|val| val.split(','))
122        .map(str::trim)
123        .any(|name| name == "*" || name.eq_ignore_ascii_case("accept-encoding"));
124    if !covered {
125        headers.append(VARY, HeaderValue::from_static("accept-encoding"));
126    }
127}
128
129/// Encodings that can be picked for a `*` entry.
130const WILDCARD: [ContentEncoding; 3] = [
131    ContentEncoding::Zstd,
132    ContentEncoding::Gzip,
133    ContentEncoding::Deflate,
134];
135
136#[derive(Debug, PartialEq)]
137struct AcceptEncoding {
138    /// `None` for the `*` entry
139    encoding: Option<ContentEncoding>,
140    /// Client weight in thousandths, `0..=1000`
141    q: u16,
142}
143
144impl AcceptEncoding {
145    fn new(tag: &str) -> Option<AcceptEncoding> {
146        let mut parts = tag.split(';');
147        let name = parts.next()?.trim();
148        if name.is_empty() {
149            return None;
150        }
151        // unsupported codings cannot be selected, skip them
152        let encoding = if name == "*" {
153            None
154        } else {
155            Some(name.parse().ok()?)
156        };
157
158        // a malformed weight makes the entry unacceptable
159        let q = parts
160            .filter_map(|param| param.split_once('='))
161            .find(|(name, _)| name.trim().eq_ignore_ascii_case("q"))
162            .map_or(1000, |(_, val)| parse_q(val.trim()).unwrap_or(0));
163        Some(AcceptEncoding { encoding, q })
164    }
165
166    /// Pick a response encoding from the `Accept-Encoding` header values.
167    ///
168    /// Entries are ranked by the client's `q` value, ties go to the
169    /// server's preference. `q=0` means "not acceptable" and `*` covers
170    /// every encoding the client did not list. `identity` wins only if its
171    /// explicit or `*` weight is strictly higher than the best compression.
172    fn parse<'a, I>(values: I, encoding: ContentEncoding) -> ContentEncoding
173    where
174        I: Iterator<Item = &'a str>,
175    {
176        let mut listed: Vec<(ContentEncoding, u16)> = Vec::new();
177        let mut wildcard = None;
178        for item in values.flat_map(|val| val.split(',')) {
179            match AcceptEncoding::new(item) {
180                Some(AcceptEncoding {
181                    encoding: Some(enc),
182                    q,
183                }) => listed.push((enc, q)),
184                Some(AcceptEncoding { encoding: None, q }) => {
185                    wildcard.get_or_insert(q);
186                }
187                None => {}
188            }
189        }
190        let weight = |enc: ContentEncoding| {
191            listed
192                .iter()
193                .find(|(e, _)| *e == enc)
194                .map(|(_, q)| *q)
195                .or(wildcard)
196                .unwrap_or(0)
197        };
198        let identity = weight(ContentEncoding::Identity);
199
200        if encoding != ContentEncoding::Auto {
201            let q = weight(encoding);
202            return if q > 0 && q >= identity {
203                encoding
204            } else {
205                ContentEncoding::Identity
206            };
207        }
208
209        let mut best: Option<(ContentEncoding, u16)> = None;
210        let candidates = listed.iter().map(|(enc, _)| *enc).chain(WILDCARD);
211        for enc in candidates.filter(|enc| Encoder::can_encode(*enc)) {
212            let q = weight(enc);
213            let better = match best {
214                None => q > 0,
215                Some((b, bq)) => q > bq || (q == bq && enc.quality() > b.quality()),
216            };
217            if better {
218                best = Some((enc, q));
219            }
220        }
221        match best {
222            Some((enc, q)) if q >= identity => enc,
223            _ => ContentEncoding::Identity,
224        }
225    }
226}
227
228/// Parse an RFC 9110 `qvalue` into thousandths.
229fn parse_q(val: &str) -> Option<u16> {
230    let (int, frac) = match val.split_once('.') {
231        Some((int, frac)) => (int, frac),
232        None => (val, ""),
233    };
234    if frac.len() > 3 || !frac.bytes().all(|b| b.is_ascii_digit()) {
235        return None;
236    }
237    let int = match int {
238        "0" => 0,
239        "1" => 1000,
240        _ => return None,
241    };
242    let frac = frac
243        .bytes()
244        .zip([100, 10, 1])
245        .map(|(b, scale)| u16::from(b - b'0') * scale)
246        .sum::<u16>();
247    if int + frac > 1000 { None } else { Some(int + frac) }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    fn parse(raw: &str, encoding: ContentEncoding) -> ContentEncoding {
255        AcceptEncoding::parse([raw].into_iter(), encoding)
256    }
257
258    /// STATEMENT: Quality parsing accepts HTTP q-values with at most three fractional digits.
259    ///
260    /// HOW:
261    /// - Parse valid zero/one and fractional values and assert their thousandths representation.
262    /// - Assert empty, malformed, overprecise, negative, and out-of-range values are rejected.
263    #[test]
264    fn test_parse_q() {
265        for (val, q) in [
266            ("0", 0),
267            ("0.", 0),
268            ("0.5", 500),
269            ("0.05", 50),
270            ("0.125", 125),
271            ("0.999", 999),
272            ("1", 1000),
273            ("1.", 1000),
274            ("1.000", 1000),
275        ] {
276            assert_eq!(parse_q(val), Some(q), "{val}");
277        }
278        for val in [
279            "", ".5", "0.1234", "1.001", "1.5", "2", "-0", "0.a", "0.00a", "01", "abc",
280        ] {
281            assert_eq!(parse_q(val), None, "{val}");
282        }
283    }
284
285    /// STATEMENT: Encoding entries parse tokens, optional quality parameters, and wildcard values.
286    ///
287    /// HOW:
288    /// - Check gzip defaults, whitespace, case-insensitive `q`, extra parameters, and invalid quality.
289    /// - Assert wildcard has no specific encoding, `identity` is kept, and empty or
290    ///   unsupported coding entries are ignored.
291    #[test]
292    fn test_accept_encoding_entry() {
293        let entry = |tag| AcceptEncoding::new(tag).unwrap();
294        assert_eq!(
295            entry("gzip"),
296            AcceptEncoding {
297                encoding: Some(ContentEncoding::Gzip),
298                q: 1000
299            }
300        );
301        assert_eq!(entry(" gzip ; q=0.5 ").q, 500);
302        assert_eq!(entry("gzip;Q=0.5").q, 500);
303        assert_eq!(entry("gzip;level=1;q=0.25").q, 250);
304        assert_eq!(entry("gzip;q=abc").q, 0);
305        assert_eq!(entry("gzip;0.8").q, 1000);
306        assert_eq!(entry("*;q=0.1").encoding, None);
307        assert_eq!(
308            entry("identity;q=0").encoding,
309            Some(ContentEncoding::Identity)
310        );
311        assert!(AcceptEncoding::new(" ").is_none());
312        assert!(AcceptEncoding::new("compress").is_none());
313        assert!(AcceptEncoding::new("gizp;q=1").is_none());
314    }
315
316    /// STATEMENT: Automatic compression selects supported encodings rather than unsupported preferences.
317    ///
318    /// HOW:
319    /// - Parse combinations of zstd, gzip, deflate, and Brotli with automatic selection.
320    /// - Assert supported server preferences, identity fallback, whitespace handling, and explicit Brotli selection.
321    #[test]
322    fn test_auto_skips_unsupported_encodings() {
323        let auto = ContentEncoding::Auto;
324        assert_eq!(
325            parse("gzip, deflate, br, zstd", auto),
326            ContentEncoding::Zstd
327        );
328        assert_eq!(parse("gzip, deflate, br", auto), ContentEncoding::Gzip);
329        assert_eq!(parse("br, deflate", auto), ContentEncoding::Deflate);
330        assert_eq!(parse("br", auto), ContentEncoding::Identity);
331        assert_eq!(parse("gzip, br", ContentEncoding::Br), ContentEncoding::Br);
332        assert_eq!(parse(" br ,  gzip ; q=1.0 ", auto), ContentEncoding::Gzip);
333        assert_eq!(parse("", auto), ContentEncoding::Identity);
334    }
335
336    /// STATEMENT: Automatic compression honors quality weights, first duplicates, and server tie-breaking.
337    ///
338    /// HOW:
339    /// - Parse unequal, zero, malformed, and duplicate quality entries and assert the selected encoding.
340    /// - Check equal weights follow server preference and `x-gzip` resolves to gzip.
341    #[test]
342    fn test_auto_honours_q() {
343        let auto = ContentEncoding::Auto;
344        assert_eq!(parse("gzip;q=0.5, zstd;q=0.1", auto), ContentEncoding::Gzip);
345        assert_eq!(
346            parse("deflate;q=0.9, gzip;q=0.8", auto),
347            ContentEncoding::Deflate
348        );
349        assert_eq!(parse("zstd;q=0, gzip", auto), ContentEncoding::Gzip);
350        assert_eq!(parse("gzip;q=0", auto), ContentEncoding::Identity);
351        assert_eq!(parse("gzip;q=abc", auto), ContentEncoding::Identity);
352        assert_eq!(parse("gzip;q=2, deflate", auto), ContentEncoding::Deflate);
353        assert_eq!(parse("gzip, zstd;q=0", auto), ContentEncoding::Gzip);
354        // the first entry for an encoding wins
355        assert_eq!(parse("gzip;q=0, gzip", auto), ContentEncoding::Identity);
356        // equal weights go to the server's preference
357        assert_eq!(
358            parse("deflate;q=0.5, gzip;q=0.5, zstd;q=0.5", auto),
359            ContentEncoding::Zstd
360        );
361        assert_eq!(parse("deflate, gzip", auto), ContentEncoding::Gzip);
362        assert_eq!(parse("x-gzip", auto), ContentEncoding::Gzip);
363    }
364
365    /// STATEMENT: Wildcard quality supplies defaults while explicit encoding weights take precedence.
366    ///
367    /// HOW:
368    /// - Combine wildcard entries with explicit exclusions and weighted supported encodings.
369    /// - Assert the selected encoding follows explicit weights, first wildcard, and identity fallback.
370    #[test]
371    fn test_auto_wildcard() {
372        let auto = ContentEncoding::Auto;
373        assert_eq!(parse("*", auto), ContentEncoding::Zstd);
374        assert_eq!(parse("*;q=0", auto), ContentEncoding::Identity);
375        assert_eq!(parse("*;q=0.5, zstd;q=0", auto), ContentEncoding::Gzip);
376        assert_eq!(
377            parse("zstd;q=0, gzip;q=0, *", auto),
378            ContentEncoding::Deflate
379        );
380        assert_eq!(parse("*;q=0.5, deflate", auto), ContentEncoding::Deflate);
381        assert_eq!(parse("gzip;q=0.1, *;q=0.5", auto), ContentEncoding::Zstd);
382        assert_eq!(parse("*;q=0, gzip;q=0.1", auto), ContentEncoding::Gzip);
383        assert_eq!(parse("*;q=0.5, *", auto), ContentEncoding::Zstd);
384        assert_eq!(parse("*;q=0, *, zstd;q=0", auto), ContentEncoding::Identity);
385    }
386
387    /// STATEMENT: Explicit compression uses only the configured encoding when the client accepts it.
388    ///
389    /// HOW:
390    /// - Configure gzip and parse direct matches, other encodings, zero/positive qualities, and wildcards.
391    /// - Assert gzip is selected only when accepted, with explicit gzip weights overriding wildcards.
392    #[test]
393    fn test_explicit_encoding() {
394        let gzip = ContentEncoding::Gzip;
395        assert_eq!(parse("gzip", gzip), gzip);
396        assert_eq!(parse("zstd", gzip), ContentEncoding::Identity);
397        assert_eq!(parse("gzip;q=0", gzip), ContentEncoding::Identity);
398        assert_eq!(parse("gzip;q=0.001", gzip), gzip);
399        assert_eq!(parse("*", gzip), gzip);
400        assert_eq!(parse("*;q=0", gzip), ContentEncoding::Identity);
401        assert_eq!(parse("*, gzip;q=0", gzip), ContentEncoding::Identity);
402        assert_eq!(parse("*;q=0, gzip", gzip), gzip);
403    }
404
405    /// STATEMENT: `identity` is chosen over compression only when the client weights it
406    /// strictly higher.
407    ///
408    /// HOW:
409    /// - Parse headers that weight `identity`, explicitly or via `*`, above, equal to and
410    ///   below the best compression, for both automatic and fixed gzip encoding.
411    /// - Assert `Identity` is selected only for a strictly higher weight, and an
412    ///   unlisted `identity` does not compete.
413    #[test]
414    fn test_identity_preference() {
415        let auto = ContentEncoding::Auto;
416        let gzip = ContentEncoding::Gzip;
417        let id = ContentEncoding::Identity;
418        assert_eq!(parse("identity;q=1, gzip;q=0.1", auto), id);
419        assert_eq!(parse("identity;q=0.5, gzip;q=0.5", auto), gzip);
420        assert_eq!(parse("identity;q=0.4, gzip;q=0.5", auto), gzip);
421        assert_eq!(parse("*, gzip;q=0.1", auto), ContentEncoding::Zstd);
422        assert_eq!(parse("*, zstd;q=0.1, gzip;q=0.1, deflate;q=0.1", auto), id);
423        assert_eq!(parse("gzip;q=0.1", auto), gzip);
424        assert_eq!(parse("identity;q=1, gzip;q=0.1", gzip), id);
425        assert_eq!(parse("identity;q=0.1, gzip;q=0.1", gzip), gzip);
426        assert_eq!(parse("*, gzip;q=0.5", gzip), id);
427        assert_eq!(parse("identity;q=0, *;q=0.5, gzip;q=0.1", gzip), gzip);
428    }
429
430    /// STATEMENT: Encoding negotiation considers values from repeated request headers together.
431    ///
432    /// HOW:
433    /// - Parse separate header values excluding zstd and weighting gzip above deflate.
434    /// - Assert automatic negotiation selects gzip.
435    #[test]
436    fn test_repeated_headers() {
437        let values = ["zstd;q=0", "gzip;q=0.5, deflate;q=0.1"];
438        assert_eq!(
439            AcceptEncoding::parse(values.into_iter(), ContentEncoding::Auto),
440            ContentEncoding::Gzip
441        );
442    }
443
444    /// STATEMENT: Compression middleware negotiates valid repeated headers and skips invalid or disabled encodings.
445    ///
446    /// HOW:
447    /// - Serve a compressible body and assert gzip requests receive `Content-Encoding: gzip`.
448    /// - Assert invalid-only and zero-quality headers produce no encoding.
449    /// - Combine repeated valid/invalid values and assert gzip or deflate is selected from valid entries.
450    #[crate::rt_test]
451    async fn test_compress_accept_encoding() {
452        use crate::http::header::{CONTENT_ENCODING, HeaderValue};
453        use crate::web::test::{TestRequest, call_service, init_service};
454        use crate::web::{self, App, HttpResponse};
455
456        let srv = init_service(App::new().middleware(Compress::default()).route(
457            "/",
458            web::get().to(async || HttpResponse::Ok().body("a".repeat(1024))),
459        ))
460        .await;
461
462        let req = TestRequest::default()
463            .header(ACCEPT_ENCODING, "gzip")
464            .to_request();
465        let resp = call_service(&srv, req).await;
466        assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "gzip");
467
468        let req = TestRequest::default()
469            .header(
470                ACCEPT_ENCODING,
471                HeaderValue::from_bytes(b"gzip\xff").unwrap(),
472            )
473            .to_request();
474        let resp = call_service(&srv, req).await;
475        assert!(resp.headers().get(CONTENT_ENCODING).is_none());
476
477        let req = TestRequest::default()
478            .header(ACCEPT_ENCODING, "zstd;q=0")
479            .header(ACCEPT_ENCODING, "gzip;q=0.5")
480            .to_request();
481        let resp = call_service(&srv, req).await;
482        assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "gzip");
483
484        let req = TestRequest::default()
485            .header(
486                ACCEPT_ENCODING,
487                HeaderValue::from_bytes(b"zstd\xff").unwrap(),
488            )
489            .header(ACCEPT_ENCODING, "deflate")
490            .to_request();
491        let resp = call_service(&srv, req).await;
492        assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "deflate");
493
494        let req = TestRequest::default()
495            .header(ACCEPT_ENCODING, "gzip;q=0")
496            .to_request();
497        let resp = call_service(&srv, req).await;
498        assert!(resp.headers().get(CONTENT_ENCODING).is_none());
499    }
500
501    /// STATEMENT: Negotiated responses get `Vary: Accept-Encoding` exactly once, and
502    /// responses whose encoding is not negotiated do not.
503    ///
504    /// HOW:
505    /// - Serve compressed, uncompressed and existing-`Vary` responses through
506    ///   `Compress::default()` and assert a single `accept-encoding` entry next to other
507    ///   `Vary` values, and none added when `Vary: *` or `Vary: Accept-Encoding` is set.
508    /// - Assert no `Vary` is added with `ContentEncoding::Identity`, for a
509    ///   `BodyEncoding` override, or when the handler sets `Content-Encoding`.
510    #[crate::rt_test]
511    async fn test_compress_vary() {
512        use crate::http::header::{CONTENT_ENCODING, VARY};
513        use crate::web::test::{TestRequest, call_service, init_service};
514        use crate::web::{self, App, HttpResponse};
515
516        fn body() -> String {
517            "a".repeat(1024)
518        }
519        let srv = init_service(
520            App::new()
521                .middleware(Compress::default())
522                .route("/", web::get().to(async || HttpResponse::Ok().body(body())))
523                .route(
524                    "/vary",
525                    web::get().to(async || HttpResponse::Ok().header(VARY, "origin").body(body())),
526                )
527                .route(
528                    "/star",
529                    web::get().to(async || HttpResponse::Ok().header(VARY, "*").body(body())),
530                )
531                .route(
532                    "/has",
533                    web::get().to(async || {
534                        HttpResponse::Ok()
535                            .header(VARY, "Origin, Accept-Encoding")
536                            .body(body())
537                    }),
538                )
539                .route(
540                    "/override",
541                    web::get().to(async || {
542                        HttpResponse::Ok()
543                            .encoding(ContentEncoding::Identity)
544                            .body("a".repeat(1024))
545                    }),
546                )
547                .route(
548                    "/encoded",
549                    web::get()
550                        .to(async || HttpResponse::Ok().header(CONTENT_ENCODING, "br").body("a")),
551                ),
552        )
553        .await;
554        let vary = async |path: &str, accept: &str| {
555            let req = TestRequest::with_uri(path)
556                .header(ACCEPT_ENCODING, accept)
557                .to_request();
558            let resp = call_service(&srv, req).await;
559            resp.headers()
560                .get_all(VARY)
561                .map(|v| v.to_str().unwrap().to_string())
562                .collect::<Vec<_>>()
563        };
564
565        assert_eq!(vary("/", "gzip").await, ["accept-encoding"]);
566        assert_eq!(vary("/", "identity").await, ["accept-encoding"]);
567        assert_eq!(vary("/vary", "gzip").await, ["origin", "accept-encoding"]);
568        assert_eq!(vary("/star", "gzip").await, ["*"]);
569        assert_eq!(vary("/has", "gzip").await, ["Origin, Accept-Encoding"]);
570        assert_eq!(vary("/override", "gzip").await, Vec::<String>::new());
571        assert_eq!(vary("/encoded", "gzip").await, Vec::<String>::new());
572
573        let srv = init_service(
574            App::new()
575                .middleware(Compress::new(ContentEncoding::Identity))
576                .route("/", web::get().to(async || HttpResponse::Ok().body(body()))),
577        )
578        .await;
579        let req = TestRequest::default()
580            .header(ACCEPT_ENCODING, "gzip")
581            .to_request();
582        let resp = call_service(&srv, req).await;
583        assert!(resp.headers().get(VARY).is_none());
584        assert!(resp.headers().get(CONTENT_ENCODING).is_none());
585    }
586}