rocket/data/limits.rs
1use serde::{Serialize, Deserialize};
2use crate::request::{Request, FromRequest, Outcome};
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/// use rocket::data::{Limits, ToByteUnit};
37///
38/// let limits = Limits::default()
39/// .limit("pet", 64.kibibytes())
40/// .limit("pet/dog", 128.kibibytes())
41/// .limit("pet/dog/bingo", 96.kibibytes());
42///
43/// assert_eq!(limits.get("pet/dog/bingo"), Some(96.kibibytes()));
44/// assert_eq!(limits.get("pet/dog/ralph"), Some(128.kibibytes()));
45/// assert_eq!(limits.get("pet/cat/bingo"), Some(64.kibibytes()));
46///
47/// assert_eq!(limits.get("pet/dog/bingo/hat"), Some(96.kibibytes()));
48/// ```
49///
50/// # Built-in Limits
51///
52/// The following table details recognized built-in limits used by Rocket.
53///
54/// | Limit Name | Default | Type | Description |
55/// |-------------------|---------|--------------|---------------------------------------|
56/// | `form` | 32KiB | [`Form`] | entire non-data-based form |
57/// | `data-form` | 2MiB | [`Form`] | entire data-based form |
58/// | `file` | 1MiB | [`TempFile`] | [`TempFile`] data guard or form field |
59/// | `file/$ext` | _N/A_ | [`TempFile`] | file form field with extension `$ext` |
60/// | `string` | 8KiB | [`String`] | data guard or form field |
61/// | `string` | 8KiB | [`&str`] | data guard or form field |
62/// | `bytes` | 8KiB | [`Vec<u8>`] | data guard |
63/// | `bytes` | 8KiB | [`&[u8]`] | data guard or form field |
64/// | `json` | 1MiB | [`Json`] | JSON data and form payloads |
65/// | `xml` | 1MiB | [`Xml`] | XML 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/// [`Xml`]: crate::serde::xml::Xml
71/// [`MsgPack`]: crate::serde::msgpack::MsgPack
72///
73/// # Usage
74///
75/// A `Limits` structure is created following the builder pattern:
76///
77/// ```rust
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;
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;
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("xml", Limits::XML)
142 .limit("msgpack", Limits::MESSAGE_PACK)
143 }
144}
145
146impl Limits {
147 /// Default limit for value-based forms.
148 pub const FORM: ByteUnit = ByteUnit::Kibibyte(32);
149
150 /// Default limit for data-based forms.
151 pub const DATA_FORM: ByteUnit = ByteUnit::Mebibyte(2);
152
153 /// Default limit for temporary files.
154 pub const FILE: ByteUnit = ByteUnit::Mebibyte(1);
155
156 /// Default limit for strings.
157 pub const STRING: ByteUnit = ByteUnit::Kibibyte(8);
158
159 /// Default limit for bytes.
160 pub const BYTES: ByteUnit = ByteUnit::Kibibyte(8);
161
162 /// Default limit for JSON payloads.
163 pub const JSON: ByteUnit = ByteUnit::Mebibyte(1);
164
165 /// Default limit for XML payloads.
166 pub const XML: ByteUnit = ByteUnit::Mebibyte(1);
167
168 /// Default limit for MessagePack payloads.
169 pub const MESSAGE_PACK: ByteUnit = ByteUnit::Mebibyte(1);
170
171 /// Construct a new `Limits` structure with no limits set.
172 ///
173 /// # Example
174 ///
175 /// ```rust
176 /// use rocket::data::{Limits, ToByteUnit};
177 ///
178 /// let limits = Limits::default();
179 /// assert_eq!(limits.get("form"), Some(32.kibibytes()));
180 ///
181 /// let limits = Limits::new();
182 /// assert_eq!(limits.get("form"), None);
183 /// ```
184 #[inline]
185 pub fn new() -> Self {
186 Limits { limits: vec![] }
187 }
188
189 /// Adds or replaces a limit in `self`, consuming `self` and returning a new
190 /// `Limits` structure with the added or replaced limit.
191 ///
192 /// # Example
193 ///
194 /// ```rust
195 /// use rocket::data::{Limits, ToByteUnit};
196 ///
197 /// let limits = Limits::default();
198 /// assert_eq!(limits.get("form"), Some(32.kibibytes()));
199 /// assert_eq!(limits.get("json"), Some(1.mebibytes()));
200 /// assert_eq!(limits.get("cat"), None);
201 ///
202 /// let limits = limits.limit("cat", 1.mebibytes());
203 /// assert_eq!(limits.get("form"), Some(32.kibibytes()));
204 /// assert_eq!(limits.get("cat"), Some(1.mebibytes()));
205 ///
206 /// let limits = limits.limit("json", 64.mebibytes());
207 /// assert_eq!(limits.get("json"), Some(64.mebibytes()));
208 /// ```
209 pub fn limit<S: Into<Uncased<'static>>>(mut self, name: S, limit: ByteUnit) -> Self {
210 let name = name.into();
211 match self.limits.binary_search_by(|(k, _)| k.cmp(&name)) {
212 Ok(i) => self.limits[i].1 = limit,
213 Err(i) => self.limits.insert(i, (name, limit))
214 }
215
216 self
217 }
218
219 /// Returns the limit named `name`, proceeding hierarchically from right
220 /// to left until one is found, or returning `None` if none is found.
221 ///
222 /// # Example
223 ///
224 /// ```rust
225 /// use rocket::data::{Limits, ToByteUnit};
226 ///
227 /// let limits = Limits::default()
228 /// .limit("json", 2.mebibytes())
229 /// .limit("file/jpeg", 4.mebibytes())
230 /// .limit("file/jpeg/special", 8.mebibytes());
231 ///
232 /// assert_eq!(limits.get("form"), Some(32.kibibytes()));
233 /// assert_eq!(limits.get("json"), Some(2.mebibytes()));
234 /// assert_eq!(limits.get("data-form"), Some(Limits::DATA_FORM));
235 ///
236 /// assert_eq!(limits.get("file"), Some(1.mebibytes()));
237 /// assert_eq!(limits.get("file/png"), Some(1.mebibytes()));
238 /// assert_eq!(limits.get("file/jpeg"), Some(4.mebibytes()));
239 /// assert_eq!(limits.get("file/jpeg/inner"), Some(4.mebibytes()));
240 /// assert_eq!(limits.get("file/jpeg/special"), Some(8.mebibytes()));
241 ///
242 /// assert!(limits.get("cats").is_none());
243 /// ```
244 pub fn get<S: AsRef<str>>(&self, name: S) -> Option<ByteUnit> {
245 let mut name = name.as_ref();
246 let mut indices = name.rmatch_indices('/');
247 loop {
248 let exact_limit = self.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 /// use rocket::data::{Limits, ToByteUnit};
274 ///
275 /// let limits = Limits::default()
276 /// .limit("json", 2.mebibytes())
277 /// .limit("file/jpeg", 4.mebibytes())
278 /// .limit("file/jpeg/special", 8.mebibytes());
279 ///
280 /// assert_eq!(limits.find(["json"]), Some(2.mebibytes()));
281 /// assert_eq!(limits.find(["json", "person"]), Some(2.mebibytes()));
282 ///
283 /// assert_eq!(limits.find(["file"]), Some(1.mebibytes()));
284 /// assert_eq!(limits.find(["file", "png"]), Some(1.mebibytes()));
285 /// assert_eq!(limits.find(["file", "jpeg"]), Some(4.mebibytes()));
286 /// assert_eq!(limits.find(["file", "jpeg", "inner"]), Some(4.mebibytes()));
287 /// assert_eq!(limits.find(["file", "jpeg", "special"]), Some(8.mebibytes()));
288 ///
289 /// # let s: &[&str] = &[]; assert_eq!(limits.find(s), None);
290 /// ```
291 pub fn find<S: AsRef<str>, L: AsRef<[S]>>(&self, layers: L) -> Option<ByteUnit> {
292 let layers = layers.as_ref();
293 for j in (1..=layers.len()).rev() {
294 let layers = &layers[..j];
295 let opt = self.limits
296 .binary_search_by(|(k, _)| {
297 let k_layers = k.as_str().split('/');
298 k_layers.cmp(layers.iter().map(|s| s.as_ref()))
299 })
300 .map(|i| self.limits[i].1);
301
302 if let Ok(byte_unit) = opt {
303 return Some(byte_unit);
304 }
305 }
306
307 None
308 }
309
310 /// Deserialize a `Limits` vector from a map. Ensures that the resulting
311 /// vector is properly sorted for futures lookups via binary search.
312 fn deserialize<'de, D>(de: D) -> Result<Vec<(Uncased<'static>, ByteUnit)>, D::Error>
313 where D: serde::Deserializer<'de>
314 {
315 let mut limits = figment::util::vec_tuple_map::deserialize(de)?;
316 limits.sort();
317 Ok(limits)
318 }
319}
320
321#[crate::async_trait]
322impl<'r> FromRequest<'r> for &'r Limits {
323 type Error = std::convert::Infallible;
324
325 async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
326 Outcome::Success(req.limits())
327 }
328}