swadhinbiswas 📦 v2.0.8: security fixes, documentation, testing improvements · 7/28/2026
84307b8
407 lines · 13.7 KB
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
use std::io::Write;

use anyhow::Result;
use async_trait::async_trait;
use flate2::write::{DeflateEncoder, GzEncoder};
use flate2::Compression;
use http_body_util::combinators::UnsyncBoxBody;
use http_body_util::BodyExt;
use hyper::body::Bytes;
use hyper::{Request, Response};

use crate::ResponseBody;

// ---------------------------------------------------------------------------
// Compression algorithm
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Encoding {
    Gzip,
    Deflate,
    #[cfg(feature = "brotli-compression")]
    Brotli,
    #[cfg(feature = "zstd-compression")]
    Zstd,
    Identity,
}

impl Encoding {
    /// Parse the best encoding from the `Accept-Encoding` header.
    /// Respects RFC 7231 quality values (q=) and selects the highest-quality encoding.
    /// Falls back to preference order (br > zstd > gzip > deflate) when q= is absent (defaults to 1.0).
    pub fn from_accept_encoding(header_value: &str) -> Self {
        let lower = header_value.to_ascii_lowercase();
        let parts: Vec<&str> = lower.split(',').map(|s| s.trim()).collect();

        // Parse (encoding_name, quality) pairs
        let mut candidates: Vec<(&str, f64)> = Vec::new();
        for part in &parts {
            let mut encoding_name = "";
            let mut quality = 1.0f64;

            for (i, sub) in part.split(';').enumerate() {
                let sub = sub.trim();
                if i == 0 {
                    encoding_name = sub;
                } else if let Some((key, val)) = sub.split_once('=') {
                    if key.trim() == "q" {
                        quality = val.trim().parse::<f64>().unwrap_or(0.0);
                    }
                }
            }

            // q=0 means explicitly not acceptable
            if quality <= 0.0 {
                continue;
            }

            let name = encoding_name.split(';').next().unwrap_or("").trim();
            match name {
                "br" | "zstd" | "gzip" | "x-gzip" | "deflate" | "*" => {
                    candidates.push((name, quality));
                }
                _ => continue,
            }
        }

        if candidates.is_empty() {
            return Encoding::Identity;
        }

        // Sort by quality descending, then by preference order as tiebreaker
        let preference_order = |name: &str| -> u8 {
            match name {
                #[cfg(feature = "brotli-compression")]
                "br" => 0,
                #[cfg(feature = "zstd-compression")]
                "zstd" => 1,
                "gzip" | "x-gzip" => 2,
                "deflate" => 3,
                "*" => 4,
                _ => 5,
            }
        };

        candidates.sort_by(|a, b| {
            b.1.partial_cmp(&a.1)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| preference_order(a.0).cmp(&preference_order(b.0)))
        });

        match candidates[0].0 {
            #[cfg(feature = "brotli-compression")]
            "br" => Encoding::Brotli,
            #[cfg(feature = "zstd-compression")]
            "zstd" => Encoding::Zstd,
            "gzip" | "x-gzip" => Encoding::Gzip,
            "deflate" => Encoding::Deflate,
            "*" => {
                #[cfg(feature = "brotli-compression")]
                {
                    Encoding::Brotli
                }
                #[cfg(feature = "zstd-compression")]
                #[cfg(not(feature = "brotli-compression"))]
                {
                    Encoding::Zstd
                }
                #[cfg(not(feature = "brotli-compression"))]
                #[cfg(not(feature = "zstd-compression"))]
                {
                    Encoding::Gzip
                }
            }
            _ => Encoding::Identity,
        }
    }

    /// Returns the `Content-Encoding` header value for this encoding.
    pub fn as_header_value(&self) -> &'static str {
        match self {
            Encoding::Gzip => "gzip",
            Encoding::Deflate => "deflate",
            #[cfg(feature = "brotli-compression")]
            Encoding::Brotli => "br",
            #[cfg(feature = "zstd-compression")]
            Encoding::Zstd => "zstd",
            Encoding::Identity => "identity",
        }
    }

    /// Returns true if this encoding actually compresses data.
    pub fn is_compression(&self) -> bool {
        *self != Encoding::Identity
    }
}

// ---------------------------------------------------------------------------
// Compress bytes
// ---------------------------------------------------------------------------

pub fn compress_bytes(data: &[u8], encoding: Encoding) -> Result<Vec<u8>> {
    match encoding {
        Encoding::Gzip => {
            let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
            encoder.write_all(data)?;
            Ok(encoder.finish()?)
        }
        Encoding::Deflate => {
            let mut encoder = DeflateEncoder::new(Vec::new(), Compression::fast());
            encoder.write_all(data)?;
            Ok(encoder.finish()?)
        }
        #[cfg(feature = "brotli-compression")]
        Encoding::Brotli => {
            let mut encoder = brotli::CompressorWriter::new(Vec::new(), 4096, 6, 22);
            std::io::Write::write_all(&mut encoder, data)?;
            Ok(encoder.into_inner())
        }
        #[cfg(feature = "zstd-compression")]
        Encoding::Zstd => {
            let mut output = Vec::new();
            zstd::stream::copy_encode(std::io::Cursor::new(data), &mut output, 3)?;
            Ok(output)
        }
        Encoding::Identity => Ok(data.to_vec()),
    }
}

// ---------------------------------------------------------------------------
// Compression middleware
// ---------------------------------------------------------------------------

/// Middleware that compresses response bodies based on the client's
/// `Accept-Encoding` header. Only compresses responses that are large
/// enough to benefit (> 1KB) and have compressible content types.
pub struct CompressionMiddleware {
    min_size: usize,
}

impl CompressionMiddleware {
    pub fn new() -> Self {
        Self { min_size: 1024 }
    }

    pub fn with_min_size(min_size: usize) -> Self {
        Self { min_size }
    }
}

impl Default for CompressionMiddleware {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl<B: Send + 'static> crate::middleware::Middleware<B> for CompressionMiddleware {
    async fn handle(
        &self,
        req: Request<B>,
        next: crate::middleware::Next<'_, B>,
    ) -> Result<Response<ResponseBody>> {
        // Determine client's accepted encoding
        let accept_encoding =
            req.headers().get("accept-encoding").and_then(|v| v.to_str().ok()).unwrap_or("");

        let encoding = Encoding::from_accept_encoding(accept_encoding);

        // If client doesn't support compression, just pass through
        if !encoding.is_compression() {
            return next.run(req).await;
        }

        let resp = next.run(req).await?;

        // Check if the response is worth compressing
        let content_type =
            resp.headers().get("content-type").and_then(|v| v.to_str().ok()).unwrap_or("");

        if !is_compressible_content_type(content_type) {
            return Ok(resp);
        }

        // Don't compress if already encoded
        if resp.headers().contains_key("content-encoding") {
            return Ok(resp);
        }

        // Decompose response into parts and body
        let (parts, body) = resp.into_parts();

        // Collect the response body
        let body_bytes = body.collect().await?.to_bytes();

        // Don't compress small responses
        if body_bytes.len() < self.min_size {
            let new_body = UnsyncBoxBody::new(
                http_body_util::Full::new(body_bytes)
                    .map_err(|e: std::convert::Infallible| -> anyhow::Error { match e {} }),
            );
            return Ok(Response::from_parts(parts, new_body));
        }

        // Compress
        let compressed = compress_bytes(&body_bytes, encoding)?;

        // Only use compression if it actually reduced size
        if compressed.len() >= body_bytes.len() {
            let new_body = UnsyncBoxBody::new(
                http_body_util::Full::new(body_bytes)
                    .map_err(|e: std::convert::Infallible| -> anyhow::Error { match e {} }),
            );
            return Ok(Response::from_parts(parts, new_body));
        }

        let mut parts = parts;
        parts.headers.insert(
            "content-encoding",
            encoding.as_header_value().parse().expect("valid content-encoding header"),
        );
        parts.headers.insert(
            "content-length",
            compressed.len().to_string().parse().expect("valid content-length header"),
        );
        // Add Vary header so caches know the response varies by Accept-Encoding
        parts.headers.insert("vary", "accept-encoding".parse().expect("valid vary header"));

        let new_body = UnsyncBoxBody::new(
            http_body_util::Full::new(Bytes::from(compressed))
                .map_err(|e: std::convert::Infallible| -> anyhow::Error { match e {} }),
        );

        Ok(Response::from_parts(parts, new_body))
    }
}

// ---------------------------------------------------------------------------
// Content type check
// ---------------------------------------------------------------------------

fn is_compressible_content_type(ct: &str) -> bool {
    // Text-based and common compressible types
    ct.starts_with("text/")
        || ct.contains("json")
        || ct.contains("javascript")
        || ct.contains("xml")
        || ct.contains("svg")
        || ct.contains("html")
        || ct.contains("css")
        || ct.contains("wasm")
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_encoding_from_gzip() {
        assert_eq!(Encoding::from_accept_encoding("gzip, deflate"), Encoding::Gzip);
    }

    #[test]
    fn test_encoding_from_deflate() {
        assert_eq!(Encoding::from_accept_encoding("deflate"), Encoding::Deflate);
    }

    #[test]
    fn test_encoding_from_identity() {
        assert_eq!(Encoding::from_accept_encoding("identity"), Encoding::Identity);
    }

    #[test]
    fn test_encoding_from_wildcard() {
        assert_eq!(Encoding::from_accept_encoding("*"), Encoding::Gzip);
    }

    #[test]
    fn test_encoding_preference_order() {
        // When quality values are equal (both default to 1.0), preference order applies:
        // br > zstd > gzip > deflate. So "deflate, gzip" returns Gzip (higher preference).
        assert_eq!(Encoding::from_accept_encoding("deflate, gzip"), Encoding::Gzip);
    }

    #[test]
    fn test_encoding_quality_values_respected() {
        // RFC 7231: quality values should be respected
        // deflate;q=1.0, gzip;q=0.5 -> deflate wins (higher quality)
        assert_eq!(Encoding::from_accept_encoding("deflate;q=1.0, gzip;q=0.5"), Encoding::Deflate);
        // gzip;q=1.0, deflate;q=0.5 -> gzip wins (higher quality)
        assert_eq!(Encoding::from_accept_encoding("gzip;q=1.0, deflate;q=0.5"), Encoding::Gzip);
    }

    #[test]
    fn test_encoding_quality_zero_rejects() {
        // q=0 means explicitly not acceptable
        assert_eq!(Encoding::from_accept_encoding("gzip;q=0, deflate;q=1.0"), Encoding::Deflate);
        // All q=0 -> Identity
        assert_eq!(Encoding::from_accept_encoding("gzip;q=0, deflate;q=0"), Encoding::Identity);
    }

    #[test]
    fn test_encoding_quality_default_is_one() {
        // When no q= is specified, default is 1.0
        // So "gzip, deflate;q=0.5" -> gzip wins (1.0 > 0.5)
        assert_eq!(Encoding::from_accept_encoding("gzip, deflate;q=0.5"), Encoding::Gzip);
    }

    #[test]
    fn test_encoding_gzip_preferred_over_deflate_in_header() {
        // When gzip appears before deflate, gzip wins
        assert_eq!(Encoding::from_accept_encoding("gzip, deflate"), Encoding::Gzip);
    }

    #[test]
    fn test_compress_gzip() {
        let data = b"hello world hello world hello world";
        let compressed = compress_bytes(data, Encoding::Gzip).unwrap();
        // Gzip adds overhead for small data, but still works
        assert!(!compressed.is_empty());
    }

    #[test]
    fn test_compress_deflate() {
        let data = b"hello world hello world hello world";
        let compressed = compress_bytes(data, Encoding::Deflate).unwrap();
        assert!(!compressed.is_empty());
    }

    #[test]
    fn test_compress_identity() {
        let data = b"hello world";
        let result = compress_bytes(data, Encoding::Identity).unwrap();
        assert_eq!(result, data);
    }

    #[test]
    fn test_compressible_content_type() {
        assert!(is_compressible_content_type("text/html"));
        assert!(is_compressible_content_type("application/json"));
        assert!(is_compressible_content_type("application/javascript"));
        assert!(is_compressible_content_type("image/svg+xml"));
        assert!(!is_compressible_content_type("image/png"));
        assert!(!is_compressible_content_type("image/jpeg"));
        assert!(!is_compressible_content_type("application/octet-stream"));
    }

    #[test]
    fn test_encoding_as_header_value() {
        assert_eq!(Encoding::Gzip.as_header_value(), "gzip");
        assert_eq!(Encoding::Deflate.as_header_value(), "deflate");
        assert_eq!(Encoding::Identity.as_header_value(), "identity");
    }

    #[test]
    fn test_is_compression() {
        assert!(Encoding::Gzip.is_compression());
        assert!(Encoding::Deflate.is_compression());
        assert!(!Encoding::Identity.is_compression());
    }
}