deps_core/cache/body.rs
1//! Capped response-body reading and the per-request body-size limit.
2
3use crate::endpoint_contact::BodyNote;
4use crate::error::{DepsError, Result};
5use crate::redact::RedactedUrl;
6use bytes::{Bytes, BytesMut};
7use reqwest::Response;
8
9/// Maximum decompressed response body size accepted from a single request.
10///
11/// `reqwest`'s `gzip` feature strips `Content-Length`/`Content-Encoding` after
12/// decoding a response, so a header-based pre-check cannot bound body size
13/// (`response.content_length()` is `None` for every decoded response). This
14/// cap is instead enforced by counting bytes as the body streams in, aborting
15/// as soon as the running total would exceed the limit.
16pub(super) const MAX_RESPONSE_BYTES: usize = 32 * 1024 * 1024;
17
18/// Ceiling every [`BodyLimit`] is clamped to at construction, so no caller can weaken
19/// the size guard [`read_body_capped`] enforces past this value.
20///
21/// 128 MiB comfortably covers the largest known caller (`deps-pypi`'s PyPI
22/// Simple API full index, ~43 MB decompressed today, capped at 96 MiB for organic
23/// growth) while still bounding the pathological case.
24pub(super) const ABSOLUTE_MAX_RESPONSE_BYTES: usize = 128 * 1024 * 1024;
25
26/// Upper bound on a single response body, clamped at construction so no caller can
27/// weaken the guard `read_body_capped` enforces past `ABSOLUTE_MAX_RESPONSE_BYTES`.
28///
29/// Every cache method that previously read `MAX_RESPONSE_BYTES` directly now takes
30/// this newtype instead (defaulting to it via [`Self::DEFAULT`]), so a caller that
31/// legitimately needs a larger cap — e.g. a full-index fetch that bypasses the entry
32/// cache entirely, like [`HttpCache::get_transport_only_with_headers_limited`](crate::cache::HttpCache::get_transport_only_with_headers_limited) — can
33/// request one without touching the shared constant every other registry client
34/// relies on.
35///
36/// # Examples
37///
38/// ```
39/// use deps_core::cache::BodyLimit;
40///
41/// let default_limit = BodyLimit::DEFAULT;
42/// let clamped = BodyLimit::new(usize::MAX);
43/// assert_ne!(clamped, default_limit);
44/// ```
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct BodyLimit(usize);
47
48impl BodyLimit {
49 /// The default limit (`MAX_RESPONSE_BYTES`), used by every cache method that
50 /// does not take an explicit [`BodyLimit`].
51 pub const DEFAULT: Self = Self(MAX_RESPONSE_BYTES);
52
53 /// Creates a limit of `bytes`, clamped down to `ABSOLUTE_MAX_RESPONSE_BYTES` if
54 /// `bytes` exceeds it.
55 #[must_use]
56 pub const fn new(bytes: usize) -> Self {
57 if bytes > ABSOLUTE_MAX_RESPONSE_BYTES {
58 Self(ABSOLUTE_MAX_RESPONSE_BYTES)
59 } else {
60 Self(bytes)
61 }
62 }
63
64 /// The clamped byte value this limit enforces.
65 #[must_use]
66 pub const fn bytes(self) -> usize {
67 self.0
68 }
69}
70
71/// Reads a response body incrementally, aborting once it exceeds `limit`.
72///
73/// Chunked reading (via [`Response::chunk`]) is required because the
74/// decompressed body size is not known upfront: `gzip` decoding strips
75/// `Content-Length`, so the only reliable guard against an oversized or
76/// maliciously amplified (decompression-bomb) response is counting bytes
77/// as they arrive and bailing before the whole body is buffered.
78///
79/// Every chunk is reported to `note`, so a body that stalls after its headers reads as slow
80/// breaker evidence while one that keeps arriving does not; `note` is finished once the body is
81/// complete and abandoned on any error.
82pub(super) async fn read_body_capped(
83 url: &str,
84 mut response: Response,
85 limit: BodyLimit,
86 note: BodyNote,
87) -> Result<Bytes> {
88 let mut body = BytesMut::new();
89 let limit = limit.bytes();
90
91 while let Some(chunk) = response
92 .chunk()
93 .await
94 .map_err(|e| DepsError::RegistryError {
95 package: RedactedUrl::new(url),
96 source: e.into(),
97 })?
98 {
99 if body.len() + chunk.len() > limit {
100 return Err(DepsError::ResponseTooLarge {
101 url: RedactedUrl::new(url),
102 limit,
103 });
104 }
105 note.progressed();
106 body.extend_from_slice(&chunk);
107 }
108
109 note.finished();
110 Ok(body.freeze())
111}