rocket_community/data/
limits.rs

1use crate::request::{FromRequest, Outcome, Request};
2use serde::{Deserialize, Serialize};
3
4use crate::data::ByteUnit;
5use crate::http::uncased::Uncased;
6
7/// Mapping from (hierarchical) data types to size limits.
8///
9/// A `Limits` structure contains a mapping from a given hierarchical data type
10/// ("form", "data-form", "ext/pdf", and so on) to the maximum size in bytes
11/// that should be accepted by Rocket for said data type. For instance, if the
12/// limit for "form" is set to `256`, only 256 bytes from an incoming non-data
13/// form (that is, url-encoded) will be accepted.
14///
15/// To help in preventing DoS attacks, all incoming data reads must capped by a
16/// limit. As such, all data guards impose a limit. The _name_ of the limit is
17/// dictated by the data guard or type itself. For instance, [`Form`] imposes
18/// the `form` limit for value-based forms and `data-form` limit for data-based
19/// forms.
20///
21/// If a limit is exceeded, a guard will typically fail. The [`Capped`] type
22/// allows retrieving some data types even when the limit is exceeded.
23///
24/// [`Capped`]: crate::data::Capped
25/// [`Form`]: crate::form::Form
26///
27/// # Hierarchy
28///
29/// Data limits are hierarchical. The `/` (forward slash) character delimits the
30/// levels, or layers, of a given limit. To obtain a limit value for a given
31/// name, layers are peeled from right to left until a match is found, if any.
32/// For example, fetching the limit named `pet/dog/bingo` will return the first
33/// of `pet/dog/bingo`, `pet/dog` or `pet`:
34///
35/// ```rust
36/// # extern crate rocket_community as rocket;
37/// use rocket::data::{Limits, ToByteUnit};
38///
39/// let limits = Limits::default()
40///     .limit("pet", 64.kibibytes())
41///     .limit("pet/dog", 128.kibibytes())
42///     .limit("pet/dog/bingo", 96.kibibytes());
43///
44/// assert_eq!(limits.get("pet/dog/bingo"), Some(96.kibibytes()));
45/// assert_eq!(limits.get("pet/dog/ralph"), Some(128.kibibytes()));
46/// assert_eq!(limits.get("pet/cat/bingo"), Some(64.kibibytes()));
47///
48/// assert_eq!(limits.get("pet/dog/bingo/hat"), Some(96.kibibytes()));
49/// ```
50///
51/// # Built-in Limits
52///
53/// The following table details recognized built-in limits used by Rocket.
54///
55/// | Limit Name        | Default | Type         | Description                           |
56/// |-------------------|---------|--------------|---------------------------------------|
57/// | `form`            | 32KiB   | [`Form`]     | entire non-data-based form            |
58/// | `data-form`       | 2MiB    | [`Form`]     | entire data-based form                |
59/// | `file`            | 1MiB    | [`TempFile`] | [`TempFile`] data guard or form field |
60/// | `file/$ext`       | _N/A_   | [`TempFile`] | file form field with extension `$ext` |
61/// | `string`          | 8KiB    | [`String`]   | data guard or form field              |
62/// | `string`          | 8KiB    | [`&str`]     | data guard or form field              |
63/// | `bytes`           | 8KiB    | [`Vec<u8>`]  | data guard                            |
64/// | `bytes`           | 8KiB    | [`&[u8]`]    | data guard or form field              |
65/// | `json`            | 1MiB    | [`Json`]     | JSON data and form payloads           |
66/// | `msgpack`         | 1MiB    | [`MsgPack`]  | MessagePack data and form payloads    |
67///
68/// [`TempFile`]: crate::fs::TempFile
69/// [`Json`]: crate::serde::json::Json
70/// [`MsgPack`]: crate::serde::msgpack::MsgPack
71///
72/// # Usage
73///
74/// A `Limits` structure is created following the builder pattern:
75///
76/// ```rust
77/// # extern crate rocket_community as rocket;
78/// use rocket::data::{Limits, ToByteUnit};
79///
80/// // Set a limit of 64KiB for forms, 3MiB for PDFs, and 1MiB for JSON.
81/// let limits = Limits::default()
82///     .limit("form", 64.kibibytes())
83///     .limit("file/pdf", 3.mebibytes())
84///     .limit("json", 2.mebibytes());
85/// ```
86///
87/// The [`Limits::default()`](#impl-Default) method populates the `Limits`
88/// structure with default limits in the [table above](#built-in-limits). A
89/// configured limit can be retrieved via the `&Limits` request guard:
90///
91/// ```rust
92/// # #[macro_use] extern crate rocket_community as rocket;
93/// use std::io;
94///
95/// use rocket::data::{Data, Limits, ToByteUnit};
96///
97/// #[post("/echo", data = "<data>")]
98/// async fn echo(data: Data<'_>, limits: &Limits) -> io::Result<String> {
99///     let limit = limits.get("data").unwrap_or(1.mebibytes());
100///     Ok(data.open(limit).into_string().await?.value)
101/// }
102/// ```
103///
104/// ...or via the [`Request::limits()`] method:
105///
106/// ```
107/// # #[macro_use] extern crate rocket_community as rocket;
108/// use rocket::request::Request;
109/// use rocket::data::{self, Data, FromData};
110///
111/// # struct MyType;
112/// # type MyError = ();
113/// #[rocket::async_trait]
114/// impl<'r> FromData<'r> for MyType {
115///     type Error = MyError;
116///
117///     async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> data::Outcome<'r, Self> {
118///         let limit = req.limits().get("my-data-type");
119///         /* .. */
120///         # unimplemented!()
121///     }
122/// }
123/// ```
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(transparent)]
126pub struct Limits {
127    #[serde(deserialize_with = "Limits::deserialize")]
128    #[serde(serialize_with = "figment::util::vec_tuple_map::serialize")]
129    pub(crate) limits: Vec<(Uncased<'static>, ByteUnit)>,
130}
131
132impl Default for Limits {
133    fn default() -> Limits {
134        Limits::new()
135            .limit("form", Limits::FORM)
136            .limit("data-form", Limits::DATA_FORM)
137            .limit("file", Limits::FILE)
138            .limit("string", Limits::STRING)
139            .limit("bytes", Limits::BYTES)
140            .limit("json", Limits::JSON)
141            .limit("msgpack", Limits::MESSAGE_PACK)
142    }
143}
144
145impl Limits {
146    /// Default limit for value-based forms.
147    pub const FORM: ByteUnit = ByteUnit::Kibibyte(32);
148
149    /// Default limit for data-based forms.
150    pub const DATA_FORM: ByteUnit = ByteUnit::Mebibyte(2);
151
152    /// Default limit for temporary files.
153    pub const FILE: ByteUnit = ByteUnit::Mebibyte(1);
154
155    /// Default limit for strings.
156    pub const STRING: ByteUnit = ByteUnit::Kibibyte(8);
157
158    /// Default limit for bytes.
159    pub const BYTES: ByteUnit = ByteUnit::Kibibyte(8);
160
161    /// Default limit for JSON payloads.
162    pub const JSON: ByteUnit = ByteUnit::Mebibyte(1);
163
164    /// Default limit for MessagePack payloads.
165    pub const MESSAGE_PACK: ByteUnit = ByteUnit::Mebibyte(1);
166
167    /// Construct a new `Limits` structure with no limits set.
168    ///
169    /// # Example
170    ///
171    /// ```rust
172    /// # extern crate rocket_community as rocket;
173    /// use rocket::data::{Limits, ToByteUnit};
174    ///
175    /// let limits = Limits::default();
176    /// assert_eq!(limits.get("form"), Some(32.kibibytes()));
177    ///
178    /// let limits = Limits::new();
179    /// assert_eq!(limits.get("form"), None);
180    /// ```
181    #[inline]
182    pub fn new() -> Self {
183        Limits { limits: vec![] }
184    }
185
186    /// Adds or replaces a limit in `self`, consuming `self` and returning a new
187    /// `Limits` structure with the added or replaced limit.
188    ///
189    /// # Example
190    ///
191    /// ```rust
192    /// # extern crate rocket_community as rocket;
193    /// use rocket::data::{Limits, ToByteUnit};
194    ///
195    /// let limits = Limits::default();
196    /// assert_eq!(limits.get("form"), Some(32.kibibytes()));
197    /// assert_eq!(limits.get("json"), Some(1.mebibytes()));
198    /// assert_eq!(limits.get("cat"), None);
199    ///
200    /// let limits = limits.limit("cat", 1.mebibytes());
201    /// assert_eq!(limits.get("form"), Some(32.kibibytes()));
202    /// assert_eq!(limits.get("cat"), Some(1.mebibytes()));
203    ///
204    /// let limits = limits.limit("json", 64.mebibytes());
205    /// assert_eq!(limits.get("json"), Some(64.mebibytes()));
206    /// ```
207    pub fn limit<S: Into<Uncased<'static>>>(mut self, name: S, limit: ByteUnit) -> Self {
208        let name = name.into();
209        match self.limits.binary_search_by(|(k, _)| k.cmp(&name)) {
210            Ok(i) => self.limits[i].1 = limit,
211            Err(i) => self.limits.insert(i, (name, limit)),
212        }
213
214        self
215    }
216
217    /// Returns the limit named `name`, proceeding hierarchically from right
218    /// to left until one is found, or returning `None` if none is found.
219    ///
220    /// # Example
221    ///
222    /// ```rust
223    /// # extern crate rocket_community as rocket;
224    /// use rocket::data::{Limits, ToByteUnit};
225    ///
226    /// let limits = Limits::default()
227    ///     .limit("json", 2.mebibytes())
228    ///     .limit("file/jpeg", 4.mebibytes())
229    ///     .limit("file/jpeg/special", 8.mebibytes());
230    ///
231    /// assert_eq!(limits.get("form"), Some(32.kibibytes()));
232    /// assert_eq!(limits.get("json"), Some(2.mebibytes()));
233    /// assert_eq!(limits.get("data-form"), Some(Limits::DATA_FORM));
234    ///
235    /// assert_eq!(limits.get("file"), Some(1.mebibytes()));
236    /// assert_eq!(limits.get("file/png"), Some(1.mebibytes()));
237    /// assert_eq!(limits.get("file/jpeg"), Some(4.mebibytes()));
238    /// assert_eq!(limits.get("file/jpeg/inner"), Some(4.mebibytes()));
239    /// assert_eq!(limits.get("file/jpeg/special"), Some(8.mebibytes()));
240    ///
241    /// assert!(limits.get("cats").is_none());
242    /// ```
243    pub fn get<S: AsRef<str>>(&self, name: S) -> Option<ByteUnit> {
244        let mut name = name.as_ref();
245        let mut indices = name.rmatch_indices('/');
246        loop {
247            let exact_limit = self
248                .limits
249                .binary_search_by(|(k, _)| k.as_uncased_str().cmp(name.into()))
250                .map(|i| self.limits[i].1);
251
252            if let Ok(exact) = exact_limit {
253                return Some(exact);
254            }
255
256            let (i, _) = indices.next()?;
257            name = &name[..i];
258        }
259    }
260
261    /// Returns the limit for the name created by joining the strings in
262    /// `layers` with `/` as a separator, then proceeding like
263    /// [`Limits::get()`], hierarchically from right to left until one is found,
264    /// or returning `None` if none is found.
265    ///
266    /// This methods exists to allow finding hierarchical limits without
267    /// constructing a string to call `get()` with but otherwise returns the
268    /// same results.
269    ///
270    /// # Example
271    ///
272    /// ```rust
273    /// # extern crate rocket_community as rocket;
274    /// use rocket::data::{Limits, ToByteUnit};
275    ///
276    /// let limits = Limits::default()
277    ///     .limit("json", 2.mebibytes())
278    ///     .limit("file/jpeg", 4.mebibytes())
279    ///     .limit("file/jpeg/special", 8.mebibytes());
280    ///
281    /// assert_eq!(limits.find(["json"]), Some(2.mebibytes()));
282    /// assert_eq!(limits.find(["json", "person"]), Some(2.mebibytes()));
283    ///
284    /// assert_eq!(limits.find(["file"]), Some(1.mebibytes()));
285    /// assert_eq!(limits.find(["file", "png"]), Some(1.mebibytes()));
286    /// assert_eq!(limits.find(["file", "jpeg"]), Some(4.mebibytes()));
287    /// assert_eq!(limits.find(["file", "jpeg", "inner"]), Some(4.mebibytes()));
288    /// assert_eq!(limits.find(["file", "jpeg", "special"]), Some(8.mebibytes()));
289    ///
290    /// # let s: &[&str] = &[]; assert_eq!(limits.find(s), None);
291    /// ```
292    pub fn find<S: AsRef<str>, L: AsRef<[S]>>(&self, layers: L) -> Option<ByteUnit> {
293        let layers = layers.as_ref();
294        for j in (1..=layers.len()).rev() {
295            let layers = &layers[..j];
296            let opt = self
297                .limits
298                .binary_search_by(|(k, _)| {
299                    let k_layers = k.as_str().split('/');
300                    k_layers.cmp(layers.iter().map(|s| s.as_ref()))
301                })
302                .map(|i| self.limits[i].1);
303
304            if let Ok(byte_unit) = opt {
305                return Some(byte_unit);
306            }
307        }
308
309        None
310    }
311
312    /// Deserialize a `Limits` vector from a map. Ensures that the resulting
313    /// vector is properly sorted for futures lookups via binary search.
314    fn deserialize<'de, D>(de: D) -> Result<Vec<(Uncased<'static>, ByteUnit)>, D::Error>
315    where
316        D: serde::Deserializer<'de>,
317    {
318        let mut limits = figment::util::vec_tuple_map::deserialize(de)?;
319        limits.sort();
320        Ok(limits)
321    }
322}
323
324#[crate::async_trait]
325impl<'r> FromRequest<'r> for &'r Limits {
326    type Error = std::convert::Infallible;
327
328    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
329        Outcome::Success(req.limits())
330    }
331}