Skip to main content

navree_http/
compression.rs

1//! [`CompressionLayer`]: gzip for responses, on `flate2`. The HTTP
2//! pipeline installs it when `http.compression` is on (the default).
3
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::task::{Context, Poll};
8
9use bytes::Bytes;
10use http::header::{
11    ACCEPT_ENCODING, ACCEPT_RANGES, CACHE_CONTROL, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_RANGE,
12    CONTENT_TYPE, ETAG, VARY,
13};
14use http::{HeaderMap, HeaderValue, Method, Request, Response, StatusCode};
15use http_body::Body as HttpBody;
16use navree_kernel::BoxError;
17use pin_project_lite::pin_project;
18use tower::{Layer, Service};
19
20use crate::body::Body;
21use crate::route::RouteMeta;
22
23mod gzip;
24
25use gzip::GzipBody;
26
27/// Bodies of fewer bytes than this are sent as they are.
28const MIN_SIZE: u64 = 32;
29
30/// A Tower layer that gzips responses for clients that accept it.
31///
32/// - **The client chooses** with `Accept-Encoding`. Its items are read as
33///   `gzip` or `x-gzip` and `identity` (any case), each with an optional
34///   `;q=` weight of `0` to `1` with up to three decimals; other codings
35///   are ignored, and so is an item whose parameter is anything but a valid
36///   weight. The response is gzipped when `gzip` has a weight above 0 that
37///   is at least that of `identity`. A header value that is not visible
38///   ASCII is skipped.
39/// - **Some responses are never compressed**: one that already has a
40///   `Content-Encoding` or a `Content-Range`, one with status 206 (a
41///   `multipart/byteranges` body has none of its own), one with
42///   `Cache-Control: no-transform`, one of a route with
43///   [`no_compression`](crate::RouteDef::no_compression), one with a status
44///   that has no body (1xx, 204, 205, 304), a body of fewer than 32 bytes (by
45///   its exact size, or else its `Content-Length`; a body of unknown size
46///   counts as large), and the content types `image/*` (but `image/svg+xml`),
47///   `application/grpc*` (but `application/grpc-web*`) and
48///   `text/event-stream`, in any case.
49/// - **`HEAD` is `GET` without the body**: the router empties the body of a
50///   `HEAD` response and keeps its length, so for `HEAD` the length is what
51///   says whether the body is under 32 bytes (none: unknown, so large), and
52///   the response gets the headers of the compressed `GET` response (no
53///   `Content-Length`, a weak `ETag`, `Content-Encoding: gzip`) with no body.
54/// - **BREACH**: a compressed length gives away how much of a body repeats.
55///   With a secret (a CSRF token) and reflected input in one response, and
56///   cookies that a cross-site request carries, an attacker who sees lengths
57///   on the network recovers the secret request by request. Opt such a
58///   response out with `no_compression` or `no-transform`. Every compressor
59///   of the app reads the same rule ([`may_compress`]), the UI toolkit's
60///   brotli for pages included.
61/// - **`Vary: accept-encoding`** is added to every response that could be
62///   compressed, whatever the client accepts, unless a `Vary` value already
63///   contains `accept-encoding` (in any case). A 304 carries it as well,
64///   unless it has `no-transform`, a `Content-Encoding` or a route that opts
65///   out: it has the header fields of the 200 it stands in for, and what that
66///   one is, a cache has to be told.
67/// - **A compressed response** loses its `Content-Length` and
68///   `Accept-Ranges`, a strong `ETag` becomes a weak one, and it gets
69///   `Content-Encoding: gzip`. Its body is a gzip
70///   stream at level 6 that keeps streaming, in frames of at most 4 KiB:
71///   when the handler's body has nothing ready, what it sent so far is
72///   flushed to the client, and the body is read no faster than the
73///   client takes the frames. Its trailers follow the gzip stream, and its
74///   error ends the response with that error.
75///
76/// ```
77/// use navree_http::{AppRouter, CompressionLayer};
78/// use navree_http::routing::Router;
79///
80/// let app = AppRouter::new(Router::new()).layer(CompressionLayer::new());
81/// # let _ = app;
82/// ```
83#[derive(Clone, Copy, Debug, Default)]
84pub struct CompressionLayer {
85    _private: (),
86}
87
88impl CompressionLayer {
89    /// The layer.
90    pub fn new() -> Self {
91        Self::default()
92    }
93}
94
95impl<S> Layer<S> for CompressionLayer {
96    type Service = Compression<S>;
97
98    fn layer(&self, inner: S) -> Compression<S> {
99        Compression { inner }
100    }
101}
102
103/// The service [`CompressionLayer`] makes.
104#[derive(Clone, Copy, Debug)]
105pub struct Compression<S> {
106    inner: S,
107}
108
109impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for Compression<S>
110where
111    S: Service<Request<ReqBody>, Response = Response<ResBody>>,
112    ResBody: HttpBody<Data = Bytes> + Send + 'static,
113    ResBody::Error: Into<BoxError>,
114{
115    type Response = Response<Body>;
116    type Error = S::Error;
117    type Future = ResponseFuture<S::Future>;
118
119    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
120        self.inner.poll_ready(cx)
121    }
122
123    fn call(&mut self, request: Request<ReqBody>) -> Self::Future {
124        let gzip = accepts_gzip(request.headers());
125        let head = request.method() == Method::HEAD;
126        ResponseFuture {
127            future: self.inner.call(request),
128            gzip,
129            head,
130        }
131    }
132}
133
134pin_project! {
135    /// The response future of [`Compression`].
136    pub struct ResponseFuture<F> {
137        #[pin]
138        future: F,
139        gzip: bool,
140        head: bool,
141    }
142}
143
144impl<F, B, E> Future for ResponseFuture<F>
145where
146    F: Future<Output = Result<Response<B>, E>>,
147    B: HttpBody<Data = Bytes> + Send + 'static,
148    B::Error: Into<BoxError>,
149{
150    type Output = Result<Response<Body>, E>;
151
152    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
153        let this = self.project();
154        let response = match this.future.poll(cx) {
155            Poll::Ready(Ok(response)) => response,
156            Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
157            Poll::Pending => return Poll::Pending,
158        };
159        Poll::Ready(Ok(compress(response, *this.gzip, *this.head)))
160    }
161}
162
163/// `response`, gzipped when `gzip` (the client accepts it) and the
164/// response may be compressed. `head`: it answers a `HEAD` request, so its
165/// body is empty, and its `Content-Length` is that of the `GET` response.
166fn compress<B>(response: Response<B>, gzip: bool, head: bool) -> Response<Body>
167where
168    B: HttpBody<Data = Bytes> + Send + 'static,
169    B::Error: Into<BoxError>,
170{
171    let compressible = compressible(&response, head);
172    let varies = compressible || stands_in_for_a_varying_response(&response);
173    let (mut parts, body) = response.into_parts();
174    if varies && !varies_with_accept_encoding(&parts.headers) {
175        parts
176            .headers
177            .append(VARY, HeaderValue::from_static("accept-encoding"));
178    }
179    if !(compressible && gzip) {
180        return Response::from_parts(parts, Body::new(body));
181    }
182    parts.headers.remove(ACCEPT_RANGES);
183    parts.headers.remove(CONTENT_LENGTH);
184    weaken_etag(&mut parts.headers);
185    parts
186        .headers
187        .insert(CONTENT_ENCODING, HeaderValue::from_static("gzip"));
188    if head {
189        return Response::from_parts(parts, Body::new(body));
190    }
191    Response::from_parts(parts, Body::new(GzipBody::new(body)))
192}
193
194/// A strong `ETag` promises the very bytes, which the gzip variant doesn't
195/// have: it stays as a weak one. A client's `If-None-Match` still matches it.
196fn weaken_etag(headers: &mut HeaderMap) {
197    let weak = headers.get(ETAG).and_then(|etag| {
198        let etag = etag.as_bytes();
199        let strong = etag.starts_with(b"\"");
200        strong.then(|| HeaderValue::from_bytes(&[b"W/", etag].concat()).ok())?
201    });
202    if let Some(weak) = weak {
203        headers.insert(ETAG, weak);
204    }
205}
206
207/// Whether `response` may be compressed at all, by this layer or by another
208/// compressor of the app (the UI toolkit's brotli for pages and ops): not
209/// when its route opted out with
210/// [`no_compression`](crate::RouteDef::no_compression), and not when it has
211/// `Cache-Control: no-transform` (in any case). `http.compression = false`
212/// turns every compressor off as well; that is the app's setting
213/// ([`HttpOptions::compression`](crate::HttpOptions::compression)), not the
214/// response's, so it is not read here.
215///
216/// ```
217/// use http::header::CACHE_CONTROL;
218/// use navree_http::may_compress;
219///
220/// let page = http::Response::new(());
221/// assert!(may_compress(&page));
222/// let kept = http::Response::builder()
223///     .header(CACHE_CONTROL, "private, no-transform")
224///     .body(())
225///     .unwrap();
226/// assert!(!may_compress(&kept));
227/// ```
228pub fn may_compress<B>(response: &Response<B>) -> bool {
229    !opted_out(response) && !no_transform(response.headers())
230}
231
232/// Whether the response was opted out of compression by its route.
233fn opted_out<B>(response: &Response<B>) -> bool {
234    response
235        .extensions()
236        .get::<Arc<RouteMeta>>()
237        .is_some_and(|route| route.no_compression)
238}
239
240/// Whether the response is a 304 that stands in for a 200 that would have
241/// `Vary: accept-encoding`: unless the route opted out of compression, or the
242/// response says it is not transformed or already encoded.
243fn stands_in_for_a_varying_response<B>(response: &Response<B>) -> bool {
244    let headers = response.headers();
245    response.status() == StatusCode::NOT_MODIFIED
246        && !opted_out(response)
247        && !headers.contains_key(CONTENT_ENCODING)
248        && !no_transform(headers)
249}
250
251/// Whether the response may be compressed, whatever the client accepts. For
252/// a `HEAD` response the body is already gone, and `Content-Length` is what
253/// the `GET` response's body measures.
254fn compressible<B: HttpBody>(response: &Response<B>, head: bool) -> bool {
255    let headers = response.headers();
256    if !may_compress(response)
257        || !has_a_body(response.status())
258        // The parts of a `multipart/byteranges` body say which ranges they are.
259        || response.status() == StatusCode::PARTIAL_CONTENT
260        || headers.contains_key(CONTENT_ENCODING)
261        || headers.contains_key(CONTENT_RANGE)
262    {
263        return false;
264    }
265    let length = || {
266        headers
267            .get(CONTENT_LENGTH)
268            .and_then(|value| value.to_str().ok())
269            .and_then(|value| value.parse::<u64>().ok())
270    };
271    let size = if head {
272        length()
273    } else {
274        response.body().size_hint().exact().or_else(length)
275    };
276    if size.is_some_and(|size| size < MIN_SIZE) {
277        return false;
278    }
279    let content_type = headers
280        .get(CONTENT_TYPE)
281        .map(HeaderValue::as_bytes)
282        .unwrap_or_default();
283    // Media types are the same in any case.
284    let is = |prefix: &str| {
285        content_type
286            .get(..prefix.len())
287            .is_some_and(|start| start.eq_ignore_ascii_case(prefix.as_bytes()))
288    };
289    let excluded = |prefix: &str, except: Option<&str>| is(prefix) && !except.is_some_and(is);
290    !(excluded("application/grpc", Some("application/grpc-web"))
291        || excluded("image/", Some("image/svg+xml"))
292        || excluded("text/event-stream", None))
293}
294
295/// Whether a response with `status` can have a body at all. hyper sends none
296/// for these, but would send the headers of one.
297fn has_a_body(status: StatusCode) -> bool {
298    !(status.is_informational()
299        || matches!(
300            status,
301            StatusCode::NO_CONTENT | StatusCode::RESET_CONTENT | StatusCode::NOT_MODIFIED
302        ))
303}
304
305/// Whether a `Cache-Control` value of `headers` has the `no-transform`
306/// directive, in any case.
307fn no_transform(headers: &HeaderMap) -> bool {
308    headers
309        .get_all(CACHE_CONTROL)
310        .iter()
311        .flat_map(|value| value.as_bytes().split(|byte| *byte == b','))
312        .any(|directive| directive.trim_ascii().eq_ignore_ascii_case(b"no-transform"))
313}
314
315/// Whether a `Vary` value of `headers` contains `accept-encoding`, in any
316/// case, anywhere in it.
317fn varies_with_accept_encoding(headers: &HeaderMap) -> bool {
318    const NAME: &[u8] = b"accept-encoding";
319    headers.get_all(VARY).iter().any(|value| {
320        value
321            .as_bytes()
322            .windows(NAME.len())
323            .any(|window| window.eq_ignore_ascii_case(NAME))
324    })
325}
326
327/// A coding the layer reads in `Accept-Encoding`.
328#[derive(Clone, Copy, PartialEq)]
329enum Coding {
330    Identity,
331    Gzip,
332}
333
334/// Whether the client's `Accept-Encoding` prefers gzip (see
335/// [`CompressionLayer`]).
336pub(crate) fn accepts_gzip(headers: &HeaderMap) -> bool {
337    let mut gzip = 0;
338    let mut identity = 0;
339    let items = headers
340        .get_all(ACCEPT_ENCODING)
341        .iter()
342        .filter_map(|value| value.to_str().ok())
343        .flat_map(|value| value.split(','));
344    for item in items {
345        let (name, weight) = match item.split_once(';') {
346            Some((name, weight)) => (name, weight_of(weight.trim())),
347            None => (item, Some(1000)),
348        };
349        let coding = match name.trim() {
350            name if name.eq_ignore_ascii_case("gzip") || name.eq_ignore_ascii_case("x-gzip") => {
351                Coding::Gzip
352            }
353            name if name.eq_ignore_ascii_case("identity") => Coding::Identity,
354            _ => continue,
355        };
356        let Some(weight) = weight else { continue };
357        let best = match coding {
358            Coding::Gzip => &mut gzip,
359            Coding::Identity => &mut identity,
360        };
361        *best = (*best).max(weight);
362    }
363    // A weight of 0 refuses the coding; gzip wins a tie.
364    gzip > 0 && gzip >= identity
365}
366
367/// A `q=` weight in thousandths: `q=` (any case) then `0` or `1`, then
368/// optionally `.` and up to three digits, at most `1`.
369fn weight_of(text: &str) -> Option<u16> {
370    let rest = text
371        .strip_prefix("q=")
372        .or_else(|| text.strip_prefix("Q="))?;
373    let mut chars = rest.chars();
374    let mut weight = match chars.next()? {
375        '0' => 0,
376        '1' => 1000,
377        _ => return None,
378    };
379    match chars.next() {
380        None => return Some(weight),
381        Some('.') => {}
382        Some(_) => return None,
383    }
384    let mut factor = 100;
385    for char in chars {
386        let digit = char.to_digit(10)?;
387        if factor == 0 {
388            return None;
389        }
390        weight += factor * digit as u16;
391        factor /= 10;
392    }
393    (weight <= 1000).then_some(weight)
394}
395
396#[cfg(test)]
397mod tests;