product-os-proxy 0.0.19

Product OS : Proxy builds on the work of hudsucker, taking it to the next level with a man-in-the-middle proxy server that can tunnel traffic through a VPN utilising Product OS : VPN.
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
434
435
436
437
438
439
440
441
442
443
444
445
//! HTTP content encoding/decoding support.
//!
//! This module provides functions for decoding compressed HTTP request and response
//! bodies. It supports the following encoding types:
//!
//! - **gzip** / **x-gzip** - GNU zip compression
//! - **deflate** - zlib compression
//! - **br** - Brotli compression
//! - **zstd** - Zstandard compression
//! - **identity** - No compression (pass-through)
//!
//! The decoder handles multiple `Content-Encoding` headers and nested encodings,
//! decoding them in the correct order (outermost encoding first).
//!
//! # Feature Flag
//!
//! This module is only available when the `decoder` feature is enabled.
//!
//! # Examples
//!
//! ```ignore
//! use product_os_proxy::mitm::{decode_request, decode_response};
//!
//! // Decode a gzip-compressed request
//! let decoded_req = decode_request(request)?;
//!
//! // Decode a compressed response
//! let decoded_res = decode_response(response)?;
//! ```

use async_compression::tokio::bufread::{BrotliDecoder, GzipDecoder, ZlibDecoder, ZstdDecoder};
use hyper::{
    body::{Body as HttpBody, Bytes},
    header::{HeaderMap, HeaderValue, CONTENT_ENCODING, CONTENT_LENGTH},
    Request, Response,
};
use product_os_http_body::{BodyBytes as Body, BodyBytes, BodyError as Error};
use std::{
    io,
    pin::Pin,
    task::{ready, Context, Poll},
};
use tokio::io::{AsyncBufRead, AsyncRead, BufReader};
use tokio_util::io::{ReaderStream, StreamReader};

/// Adapter that converts an HTTP body into a `Stream` of `io::Result<Bytes>`.
///
/// This is used internally to bridge between the HTTP body abstraction and
/// the tokio IO ecosystem needed for decompression.
struct IoStream<T>(T);

impl<T: HttpBody<Data = Bytes, Error = Error> + Unpin> futures_util::Stream for IoStream<T> {
    type Item = Result<Bytes, io::Error>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        loop {
            return match ready!(Pin::new(&mut self.0).poll_frame(cx)) {
                Some(Ok(frame)) => match frame.into_data() {
                    Ok(buf) => Poll::Ready(Some(Ok(buf))),
                    Err(_) => continue,
                },
                Some(Err(Error::Io(err))) => Poll::Ready(Some(Err(err))),
                Some(Err(err)) => Poll::Ready(Some(Err(io::Error::other(err)))),
                None => Poll::Ready(None),
            };
        }
    }
}

/// Creates a decoder for the given encoding type.
///
/// # Arguments
///
/// * `encoding` - The encoding type as bytes (e.g., `b"gzip"`, `b"br"`)
/// * `reader` - The input reader to decode from
///
/// # Errors
///
/// Returns `Error::Decode` if the encoding type is not supported.
fn decode(
    encoding: &[u8],
    reader: impl AsyncBufRead + Send + Sync + Unpin + 'static,
) -> Result<Box<dyn AsyncRead + Send + Sync + Unpin>, Error> {
    Ok(match encoding {
        b"gzip" | b"x-gzip" => Box::new(GzipDecoder::new(reader)),
        b"deflate" => Box::new(ZlibDecoder::new(reader)),
        b"br" => Box::new(BrotliDecoder::new(reader)),
        b"zstd" => Box::new(ZstdDecoder::new(reader)),
        _ => Err(Error::Decode)?,
    })
}

/// Internal enum representing either a raw body or a decoder chain.
enum Decoder<T> {
    /// Raw HTTP body (no decoding applied yet)
    Body(T),
    /// Decoded stream with one or more decoders applied
    Decoder(Box<dyn AsyncRead + Send + Sync + Unpin>),
}

impl Decoder<Body> {
    /// Apply an encoding layer to this decoder.
    ///
    /// Identity encoding is treated as a no-op. For other encodings,
    /// the appropriate decompression decoder is applied.
    pub fn decode(self, encoding: &[u8]) -> Result<Self, Error> {
        if encoding == b"identity" {
            return Ok(self);
        }

        Ok(Self::Decoder(match self {
            Self::Body(body) => decode(encoding, StreamReader::new(IoStream(body))),
            Self::Decoder(decoder) => decode(encoding, BufReader::new(decoder)),
        }?))
    }
}

impl From<Decoder<Body>> for Body {
    fn from(decoder: Decoder<Body>) -> Body {
        match decoder {
            Decoder::Body(body) => body,
            Decoder::Decoder(decoder) => BodyBytes::from_stream(ReaderStream::new(decoder)),
        }
    }
}

/// Extracts content encodings from headers in reverse order.
///
/// Multiple `Content-Encoding` headers and comma-separated values are supported.
/// The encodings are returned in reverse order because the outermost encoding
/// (listed last in the header) must be decoded first.
fn extract_encodings(headers: &HeaderMap<HeaderValue>) -> impl Iterator<Item = &[u8]> {
    headers
        .get_all(CONTENT_ENCODING)
        .iter()
        .rev()
        .flat_map(|val| {
            val.as_bytes().split(|&b| b == b',').rev().map(|v| {
                let start = v
                    .iter()
                    .position(|&b| b != b' ' && b != b'\t')
                    .unwrap_or(v.len());
                let end = v
                    .iter()
                    .rposition(|&b| b != b' ' && b != b'\t')
                    .map_or(start, |i| i + 1);
                &v[start..end]
            })
        })
}

/// Decodes a body using the specified encoding chain.
///
/// Each encoding in the iterator is applied as a decoding layer.
fn decode_body<'a>(
    encodings: impl IntoIterator<Item = &'a [u8]>,
    body: Body,
) -> Result<Body, Error> {
    let mut decoder = Decoder::Body(body);

    for encoding in encodings {
        decoder = decoder.decode(encoding)?;
    }

    Ok(decoder.into())
}

/// Decode the body of an HTTP request.
///
/// Removes the `Content-Encoding` and `Content-Length` headers and replaces the body
/// with the decoded content. If no `Content-Encoding` header is present, the request
/// is returned unchanged.
///
/// # Arguments
///
/// * `req` - The HTTP request to decode
///
/// # Returns
///
/// The request with decoded body, or the original request if no encoding was present.
///
/// # Errors
///
/// Returns an error if:
/// - The `Content-Encoding` header contains an unsupported encoding
/// - The decompression fails
///
/// # Examples
///
/// ```ignore
/// use product_os_proxy::mitm::decode_request;
///
/// let decoded = decode_request(compressed_request)?;
/// // Body is now decompressed, Content-Encoding header removed
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "decoder")))]
pub fn decode_request(mut req: Request<Body>) -> Result<Request<Body>, Error> {
    if !req.headers().contains_key(CONTENT_ENCODING) {
        return Ok(req);
    }

    if let Some(val) = req.headers_mut().remove(CONTENT_LENGTH) {
        if val == "0" {
            req.headers_mut().remove(CONTENT_ENCODING);
            return Ok(req);
        }
    }

    let (mut parts, body) = req.into_parts();

    let body = {
        let encodings = extract_encodings(&parts.headers);
        decode_body(encodings, body)?
    };

    parts.headers.remove(CONTENT_ENCODING);

    Ok(Request::from_parts(parts, body))
}

/// Decode the body of an HTTP response.
///
/// Removes the `Content-Encoding` and `Content-Length` headers and replaces the body
/// with the decoded content. If no `Content-Encoding` header is present, the response
/// is returned unchanged.
///
/// # Arguments
///
/// * `res` - The HTTP response to decode
///
/// # Returns
///
/// The response with decoded body, or the original response if no encoding was present.
///
/// # Errors
///
/// Returns an error if:
/// - The `Content-Encoding` header contains an unsupported encoding
/// - The decompression fails
///
/// # Examples
///
/// ```ignore
/// use product_os_proxy::mitm::decode_response;
///
/// let decoded = decode_response(compressed_response)?;
/// // Body is now decompressed, Content-Encoding header removed
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "decoder")))]
pub fn decode_response(mut res: Response<Body>) -> Result<Response<Body>, Error> {
    if !res.headers().contains_key(CONTENT_ENCODING) {
        return Ok(res);
    }

    if let Some(val) = res.headers_mut().remove(CONTENT_LENGTH) {
        if val == "0" {
            res.headers_mut().remove(CONTENT_ENCODING);
            return Ok(res);
        }
    }

    let (mut parts, body) = res.into_parts();

    let body = {
        let encodings = extract_encodings(&parts.headers);
        decode_body(encodings, body)?
    };

    parts.headers.remove(CONTENT_ENCODING);

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

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

    mod extract_encodings {
        use super::*;

        #[test]
        fn no_headers() {
            let headers = HeaderMap::new();

            assert_eq!(extract_encodings(&headers).count(), 0);
        }

        #[test]
        fn single_header_single_value() {
            let mut headers = HeaderMap::new();
            headers.append(CONTENT_ENCODING, HeaderValue::from_static("gzip"));

            assert_eq!(
                extract_encodings(&headers).collect::<Vec<_>>(),
                vec![b"gzip"]
            );
        }

        #[test]
        fn single_header_multiple_values() {
            let mut headers = HeaderMap::new();
            headers.append(CONTENT_ENCODING, HeaderValue::from_static("gzip, deflate"));

            assert_eq!(
                extract_encodings(&headers).collect::<Vec<_>>(),
                vec![&b"deflate"[..], &b"gzip"[..]]
            );
        }

        #[test]
        fn multiple_headers_single_value() {
            let mut headers = HeaderMap::new();
            headers.append(CONTENT_ENCODING, HeaderValue::from_static("gzip"));
            headers.append(CONTENT_ENCODING, HeaderValue::from_static("deflate"));

            assert_eq!(
                extract_encodings(&headers).collect::<Vec<_>>(),
                vec![&b"deflate"[..], &b"gzip"[..]]
            );
        }

        #[test]
        fn multiple_headers_multiple_values() {
            let mut headers = HeaderMap::new();
            headers.append(CONTENT_ENCODING, HeaderValue::from_static("gzip, deflate"));
            headers.append(CONTENT_ENCODING, HeaderValue::from_static("br, zstd"));

            assert_eq!(
                extract_encodings(&headers).collect::<Vec<_>>(),
                vec![&b"zstd"[..], &b"br"[..], &b"deflate"[..], &b"gzip"[..]]
            );
        }
    }

    async fn to_bytes<H: HttpBody>(body: H) -> Bytes
    where
        H::Error: std::fmt::Debug,
    {
        use http_body_util::BodyExt;
        body.collect().await.unwrap().to_bytes()
    }

    mod decode_body {
        use super::*;
        use async_compression::tokio::bufread::{BrotliEncoder, GzipEncoder};

        #[tokio::test]
        async fn no_encodings() {
            let content = "hello, world";
            let body = Body::from(content);

            assert_eq!(
                &to_bytes(decode_body(vec![], body).unwrap()).await[..],
                content.as_bytes()
            );
        }

        #[tokio::test]
        async fn identity_encoding() {
            let content = "hello, world";
            let body = Body::from(content);

            assert_eq!(
                &to_bytes(decode_body(vec![&b"identity"[..]], body).unwrap()).await[..],
                content.as_bytes()
            );
        }

        #[tokio::test]
        async fn single_encoding() {
            let content = b"hello, world";
            let encoder = GzipEncoder::new(&content[..]);
            let body = Body::from_stream(ReaderStream::new(encoder));

            assert_eq!(
                &to_bytes(decode_body(vec![&b"gzip"[..]], body).unwrap()).await[..],
                content
            );
        }

        #[tokio::test]
        async fn multiple_encodings() {
            let content = b"hello, world";
            let encoder = GzipEncoder::new(&content[..]);
            let encoder = BrotliEncoder::new(BufReader::new(encoder));
            let body = Body::from_stream(ReaderStream::new(encoder));

            assert_eq!(
                &to_bytes(decode_body(vec![&b"br"[..], &b"gzip"[..]], body).unwrap()).await[..],
                content
            );
        }

        #[test]
        fn invalid_encoding() {
            let body = Body::empty();

            assert!(decode_body(vec![&b"invalid"[..]], body).is_err());
        }
    }

    mod decode_request {
        use super::*;
        use async_compression::tokio::bufread::GzipEncoder;

        #[tokio::test]
        async fn decodes_request() {
            let content = b"hello, world";
            let encoder = GzipEncoder::new(&content[..]);
            let req = Request::builder()
                .header(CONTENT_LENGTH, 123)
                .header(CONTENT_ENCODING, "gzip")
                .body(Body::from_stream(ReaderStream::new(encoder)))
                .unwrap();

            let req = decode_request(req).unwrap();

            assert!(!req.headers().contains_key(CONTENT_LENGTH));
            assert!(!req.headers().contains_key(CONTENT_ENCODING));
            assert_eq!(&to_bytes(req.into_body()).await[..], content);
        }
    }

    mod decode_response {
        use super::*;
        use async_compression::tokio::bufread::GzipEncoder;

        #[tokio::test]
        async fn decodes_response() {
            let content = b"hello, world";
            let encoder = GzipEncoder::new(&content[..]);
            let res = Response::builder()
                .header(CONTENT_LENGTH, 123)
                .header(CONTENT_ENCODING, "gzip")
                .body(Body::from_stream(ReaderStream::new(encoder)))
                .unwrap();

            let res = decode_response(res).unwrap();

            assert!(!res.headers().contains_key(CONTENT_LENGTH));
            assert!(!res.headers().contains_key(CONTENT_ENCODING));
            assert_eq!(&to_bytes(res.into_body()).await[..], content);
        }
    }
}