Struct rocket::data::Limits[][src]

pub struct Limits { /* fields omitted */ }
Expand description

Mapping from (hierarchical) data types to size limits.

A Limits structure contains a mapping from a given hierarchical data type (“form”, “data-form”, “ext/pdf”, and so on) to the maximum size in bytes that should be accepted by Rocket for said data type. For instance, if the limit for “form” is set to 256, only 256 bytes from an incoming non-data form (that is, url-encoded) will be accepted.

To help in preventing DoS attacks, all incoming data reads must capped by a limit. As such, all data guards impose a limit. The name of the limit is dictated by the data guard or type itself. For instance, Form imposes the form limit for value-based forms and data-form limit for data-based forms.

If a limit is exceeded, a guard will typically fail. The Capped type allows retrieving some data types even when the limit is exceeded.

Hierarchy

Data limits are hierarchical. The / (forward slash) character delimits the levels, or layers, of a given limit. To obtain a limit value for a given name, layers are peeled from right to left until a match is found, if any. For example, fetching the limit named pet/dog/bingo will return the first of pet/dog/bingo, pet/dog or pet:

use rocket::data::{Limits, ToByteUnit};

let limits = Limits::default()
    .limit("pet", 64.kibibytes())
    .limit("pet/dog", 128.kibibytes())
    .limit("pet/dog/bingo", 96.kibibytes());

assert_eq!(limits.get("pet/dog/bingo"), Some(96.kibibytes()));
assert_eq!(limits.get("pet/dog/ralph"), Some(128.kibibytes()));
assert_eq!(limits.get("pet/cat/bingo"), Some(64.kibibytes()));

assert_eq!(limits.get("pet/dog/bingo/hat"), Some(96.kibibytes()));

Built-in Limits

The following table details recognized built-in limits used by Rocket.

Limit NameDefaultTypeDescription
form32KiBFormentire non-data-based form
data-form2MiBFormentire data-based form
file1MiBTempFileTempFile data guard or form field
file/$extN/ATempFilefile form field with extension $ext
string8KiBStringdata guard or data form field
bytes8KiBVec<u8>data guard
json1MiBJsonJSON data and form payloads
msgpack1MiBMsgPackMessagePack data and form payloads

Usage

A Limits structure is created following the builder pattern:

use rocket::data::{Limits, ToByteUnit};

// Set a limit of 64KiB for forms, 3MiB for PDFs, and 1MiB for JSON.
let limits = Limits::default()
    .limit("form", 64.kibibytes())
    .limit("file/pdf", 3.mebibytes())
    .limit("json", 2.mebibytes());

The Limits::default() method populates the Limits structure with default limits in the table above. A configured limit can be retrieved via the &Limits request guard:

use std::io;

use rocket::data::{Data, Limits, ToByteUnit};

#[post("/echo", data = "<data>")]
async fn echo(data: Data<'_>, limits: &Limits) -> io::Result<String> {
    let limit = limits.get("data").unwrap_or(1.mebibytes());
    Ok(data.open(limit).into_string().await?.value)
}

…or via the Request::limits() method:

use rocket::request::Request;
use rocket::data::{self, Data, FromData};

#[rocket::async_trait]
impl<'r> FromData<'r> for MyType {
    type Error = MyError;

    async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> data::Outcome<'r, Self> {
        let limit = req.limits().get("my-data-type");
        /* .. */
    }
}

Implementations

impl Limits[src]

pub const FORM: ByteUnit[src]

Default limit for value-based forms.

pub const DATA_FORM: ByteUnit[src]

Default limit for data-based forms.

pub const FILE: ByteUnit[src]

Default limit for temporary files.

pub const STRING: ByteUnit[src]

Default limit for strings.

pub const BYTES: ByteUnit[src]

Default limit for bytes.

pub const JSON: ByteUnit[src]

Default limit for JSON payloads.

pub const MESSAGE_PACK: ByteUnit[src]

Default limit for MessagePack payloads.

pub fn new() -> Self[src]

Construct a new Limits structure with no limits set.

Example

use rocket::data::{Limits, ToByteUnit};

let limits = Limits::default();
assert_eq!(limits.get("form"), Some(32.kibibytes()));

let limits = Limits::new();
assert_eq!(limits.get("form"), None);

pub fn limit<S: Into<Uncased<'static>>>(self, name: S, limit: ByteUnit) -> Self[src]

Adds or replaces a limit in self, consuming self and returning a new Limits structure with the added or replaced limit.

Example

use rocket::data::{Limits, ToByteUnit};

let limits = Limits::default();
assert_eq!(limits.get("form"), Some(32.kibibytes()));
assert_eq!(limits.get("json"), Some(1.mebibytes()));
assert_eq!(limits.get("cat"), None);

let limits = limits.limit("cat", 1.mebibytes());
assert_eq!(limits.get("form"), Some(32.kibibytes()));
assert_eq!(limits.get("cat"), Some(1.mebibytes()));

let limits = limits.limit("json", 64.mebibytes());
assert_eq!(limits.get("json"), Some(64.mebibytes()));

pub fn get<S: AsRef<str>>(&self, name: S) -> Option<ByteUnit>[src]

Returns the limit named name, proceeding hierarchically from right to left until one is found, or returning None if none is found.

Example

use rocket::data::{Limits, ToByteUnit};

let limits = Limits::default()
    .limit("json", 2.mebibytes())
    .limit("file/jpeg", 4.mebibytes())
    .limit("file/jpeg/special", 8.mebibytes());

assert_eq!(limits.get("form"), Some(32.kibibytes()));
assert_eq!(limits.get("json"), Some(2.mebibytes()));
assert_eq!(limits.get("data-form"), Some(Limits::DATA_FORM));

assert_eq!(limits.get("file"), Some(1.mebibytes()));
assert_eq!(limits.get("file/png"), Some(1.mebibytes()));
assert_eq!(limits.get("file/jpeg"), Some(4.mebibytes()));
assert_eq!(limits.get("file/jpeg/inner"), Some(4.mebibytes()));
assert_eq!(limits.get("file/jpeg/special"), Some(8.mebibytes()));

assert!(limits.get("cats").is_none());

pub fn find<S: AsRef<str>, L: AsRef<[S]>>(&self, layers: L) -> Option<ByteUnit>[src]

Returns the limit for the name created by joining the strings in layers with / as a separator, then proceeding like Limits::get(), hierarchically from right to left until one is found, or returning None if none is found.

This methods exists to allow finding hierarchical limits without constructing a string to call get() with but otherwise returns the same results.

Example

use rocket::data::{Limits, ToByteUnit};

let limits = Limits::default()
    .limit("json", 2.mebibytes())
    .limit("file/jpeg", 4.mebibytes())
    .limit("file/jpeg/special", 8.mebibytes());

assert_eq!(limits.find(["json"]), Some(2.mebibytes()));
assert_eq!(limits.find(["json", "person"]), Some(2.mebibytes()));

assert_eq!(limits.find(["file"]), Some(1.mebibytes()));
assert_eq!(limits.find(["file", "png"]), Some(1.mebibytes()));
assert_eq!(limits.find(["file", "jpeg"]), Some(4.mebibytes()));
assert_eq!(limits.find(["file", "jpeg", "inner"]), Some(4.mebibytes()));
assert_eq!(limits.find(["file", "jpeg", "special"]), Some(8.mebibytes()));

Trait Implementations

impl Clone for Limits[src]

fn clone(&self) -> Limits[src]

Returns a copy of the value. Read more

fn clone_from(&mut self, source: &Self)1.0.0[src]

Performs copy-assignment from source. Read more

impl Debug for Limits[src]

fn fmt(&self, f: &mut Formatter<'_>) -> Result[src]

Formats the value using the given formatter. Read more

impl Default for Limits[src]

fn default() -> Limits[src]

Returns the “default value” for a type. Read more

impl<'de> Deserialize<'de> for Limits[src]

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
    __D: Deserializer<'de>, 
[src]

Deserialize this value from the given Serde deserializer. Read more

impl Display for Limits[src]

fn fmt(&self, f: &mut Formatter<'_>) -> Result[src]

Formats the value using the given formatter. Read more

impl<'r> FromRequest<'r> for &'r Limits[src]

type Error = Infallible

The associated error to be returned if derivation fails.

fn from_request<'life0, 'async_trait>(
    req: &'r Request<'life0>
) -> Pin<Box<dyn Future<Output = Outcome<Self, Self::Error>> + Send + 'async_trait>> where
    'r: 'async_trait,
    'life0: 'async_trait,
    Self: 'async_trait, 
[src]

Derives an instance of Self from the incoming request metadata. Read more

impl PartialEq<Limits> for Limits[src]

fn eq(&self, other: &Limits) -> bool[src]

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &Limits) -> bool[src]

This method tests for !=.

impl Serialize for Limits[src]

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where
    __S: Serializer
[src]

Serialize this value into the given Serde serializer. Read more

impl Eq for Limits[src]

impl StructuralEq for Limits[src]

impl StructuralPartialEq for Limits[src]

Auto Trait Implementations

impl RefUnwindSafe for Limits

impl Send for Limits

impl Sync for Limits

impl Unpin for Limits

impl UnwindSafe for Limits

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

pub fn type_id(&self) -> TypeId[src]

Gets the TypeId of self. Read more

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

impl<Q, K> Equivalent<K> for Q where
    K: Borrow<Q> + ?Sized,
    Q: Eq + ?Sized
[src]

pub fn equivalent(&self, key: &K) -> bool[src]

Compare self to key and return true if they are equal.

impl<T> From<T> for T[src]

pub fn from(t: T) -> T[src]

Performs the conversion.

impl<T> Instrument for T[src]

fn instrument(self, span: Span) -> Instrumented<Self>[src]

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

fn in_current_span(self) -> Instrumented<Self>[src]

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

pub fn into(self) -> U[src]

Performs the conversion.

impl<T> IntoCollection<T> for T

pub fn into_collection<A>(self) -> SmallVec<A> where
    A: Array<Item = T>, 

Converts self into a collection.

pub fn mapped<U, F, A>(self, f: F) -> SmallVec<A> where
    F: FnMut(T) -> U,
    A: Array<Item = U>, 

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

pub fn to_owned(&self) -> T[src]

Creates owned data from borrowed data, usually by cloning. Read more

pub fn clone_into(&self, target: &mut T)[src]

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

impl<T> ToString for T where
    T: Display + ?Sized
[src]

pub default fn to_string(&self) -> String[src]

Converts the given value to a String. Read more

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>[src]

Performs the conversion.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>[src]

Performs the conversion.

impl<V, T> VZip<V> for T where
    V: MultiLane<T>, 

pub fn vzip(self) -> V

impl<T> DeserializeOwned for T where
    T: for<'de> Deserialize<'de>, 
[src]