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
// Copyright (c) 2016 Sergio Benitez
// Copyright (c) 2021 Cognite AS
//! Rocket extension to permit enums in application/x-www-form-urlencoded forms
//! This crate is a workaround for [https://github.com/SergioBenitez/Rocket/issues/1937](rocket#1937).
//!
//! It is derived from the included [serde_json](`rocket::serde::json`]) implementation in rocket.
//!
//! ```rust
//! # use rocket_enumform::UrlEncoded;
//! # use serde::Deserialize;
//! # use rocket::post;
//! #[derive(Debug, Deserialize)]
//! #[serde(tag = "type")]
//! enum Body {
//! #[serde(rename = "variant_one")]
//! VariantOne(VariantOne),
//! #[serde(rename = "variant_two")]
//! VariantTwo(VariantTwo),
//! }
//!
//! #[derive(Debug, Deserialize)]
//! struct VariantOne {
//! content_one: String
//! }
//!
//! #[derive(Debug, Deserialize)]
//! struct VariantTwo {
//! content_two: String
//! }
//!
//! #[post("/form", format = "form", data = "<data>")]
//! fn body(data: UrlEncoded<Body>) -> String { format!("{:?}", data) }
//! ```
//! ## status
//!
//! Works but not tested, nor have local testing affordances been added yet.
//!
// # Testing
//
// TODO; idea is use the underlying serde_urlencoded serializer and implement the glue
// needed as extension traits.
//
// ///The [`LocalRequest`] and [`LocalResponse`] types provide [`json()`] and
// ///[`into_json()`] methods to create a request with serialized JSON and
// ///deserialize a response as JSON, respectively.
//
// ///[`LocalRequest`]: crate::local::blocking::LocalRequest [`LocalResponse`]:
// ///crate::local::blocking::LocalResponse [`json()`]:
// ///crate::local::blocking::LocalRequest::json() [`into_json()`]:
// ///crate::local::blocking::LocalResponse::into_json()
use std::ops::{Deref, DerefMut};
use std::{error, fmt, io};
use rocket::data::{Data, FromData, Limits, Outcome};
use rocket::error_;
use rocket::form::prelude as form;
use rocket::http::uri::fmt::{Formatter as UriFormatter, FromUriParam, Query, UriDisplay};
use rocket::http::{ContentType, Status};
use rocket::request::{local_cache, Request};
use rocket::response::{self, content, Responder};
use serde::{Deserialize, Serialize};
/// The UrlEncoded guard: easily consume x-www-form-urlencoded requests.
///
/// ## Receiving
///
/// `UrlEncoded` is both a data guard and a form guard.
///
/// ### Data Guard
///
/// To deserialize request body data from x-www-form-urlencoded, add a `data`
/// route argument with a target type of `UrlEncoded<T>`, where `T` is some type
/// you'd like to parse. `T` must implement [`serde::Deserialize`]. See
/// [`serde_urlencoded`](serde_urlencoded) docs on the flatten-workaround for important hints about
/// more complex datatypes.
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// #
/// # type User = usize;
/// use rocket_enumform::UrlEncoded;
///
/// #[post("/user", format = "form", data = "<user>")]
/// fn new_user(user: UrlEncoded<User>) {
/// /* ... */
/// }
/// ```
///
/// You don't _need_ to use `format = "form"`, but it _may_ be what you
/// want. Using `format = urlencoded` means that any request that doesn't
/// specify "application/x-www-form-urlencoded" as its `Content-Type` header
/// value will not be routed to the handler.
///
/// ### Incoming Data Limits
///
/// The default size limit for incoming UrlEncoded data is the built in form
/// limit. Setting a limit protects your application from denial of service
/// (DoS) attacks and from resource exhaustion through high memory consumption.
/// The limit can be increased by setting the `limits.form` configuration
/// parameter. For instance, to increase the UrlEncoded limit to 5MiB for all
/// environments, you may add the following to your `Rocket.toml`:
///
/// ```toml
/// [global.limits]
/// form = 5242880
/// ```
#[repr(transparent)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UrlEncoded<T>(pub T);
/// Error returned by the [`UrlEncoded`] guard when deserialization fails.
#[derive(Debug)]
pub enum Error<'a> {
/// An I/O error occurred while reading the incoming request data.
Io(io::Error),
/// The client's data was received successfully but failed to parse as valid
/// UrlEncoded or as the requested type. The `&str` value in `.0` is the raw data
/// received from the user, while the `Error` in `.1` is the deserialization
/// error from `serde`.
Parse(&'a str, ::serde_urlencoded::de::Error),
}
impl<'a> fmt::Display for Error<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(err) => write!(f, "i/o error: {}", err),
Self::Parse(_, err) => write!(f, "parse error: {}", err),
}
}
}
impl<'a> error::Error for Error<'a> {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::Io(err) => Some(err),
Self::Parse(_, err) => Some(err),
}
}
}
impl<T> UrlEncoded<T> {
/// Consumes the UrlEncoded wrapper and returns the wrapped item.
///
/// # Example
/// ```rust
/// use rocket_enumform::UrlEncoded;
/// let string = "Hello".to_string();
/// let outer = UrlEncoded(string);
/// assert_eq!(outer.into_inner(), "Hello".to_string());
/// ```
#[inline(always)]
pub fn into_inner(self) -> T {
self.0
}
}
impl<'r, T: Deserialize<'r>> UrlEncoded<T> {
fn from_str(s: &'r str) -> Result<Self, Error<'r>> {
::serde_urlencoded::from_str(s)
.map(UrlEncoded)
.map_err(|e| Error::Parse(s, e))
}
async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> Result<Self, Error<'r>> {
let limit = req.limits().get("form").unwrap_or(Limits::FORM);
let string = match data.open(limit).into_string().await {
Ok(s) if s.is_complete() => s.into_inner(),
Ok(_) => {
let eof = io::ErrorKind::UnexpectedEof;
return Err(Error::Io(io::Error::new(eof, "data limit exceeded")));
}
Err(e) => return Err(Error::Io(e)),
};
Self::from_str(local_cache!(req, string))
}
}
#[rocket::async_trait]
impl<'r, T: Deserialize<'r>> FromData<'r> for UrlEncoded<T> {
type Error = Error<'r>;
async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r, Self> {
match Self::from_data(req, data).await {
Ok(value) => Outcome::Success(value),
Err(Error::Io(e)) if e.kind() == io::ErrorKind::UnexpectedEof => {
Outcome::Failure((Status::PayloadTooLarge, Error::Io(e)))
}
Err(Error::Parse(s, e)) => {
error_!("{:?}", e);
Outcome::Failure((Status::UnprocessableEntity, Error::Parse(s, e)))
}
Err(e) => Outcome::Failure((Status::BadRequest, e)),
}
}
}
/// Serializes the wrapped value into UrlEncoding. Returns a response with Content-Type
/// application/x-www-form-urlencode and a fixed-size body with the serialized value. If serialization
/// fails, an `Err` of `Status::InternalServerError` is returned.
impl<'r, T: Serialize> Responder<'r, 'static> for UrlEncoded<T> {
fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> {
let string = ::serde_urlencoded::to_string(&self.0).map_err(|e| {
error_!("UrlEncoding failed to serialize: {:?}", e);
Status::InternalServerError
})?;
content::Custom(ContentType::Form, string).respond_to(req)
}
}
impl<T: Serialize> UriDisplay<Query> for UrlEncoded<T> {
fn fmt(&self, f: &mut UriFormatter<'_, Query>) -> fmt::Result {
let string = ::serde_urlencoded::to_string(&self.0).map_err(|_| fmt::Error)?;
f.write_value(&string)
}
}
macro_rules! impl_from_uri_param_from_inner_type {
($($lt:lifetime)?, $T:ty) => (
impl<$($lt,)? T: Serialize> FromUriParam<Query, $T> for UrlEncoded<T> {
type Target = UrlEncoded<$T>;
#[inline(always)]
fn from_uri_param(param: $T) -> Self::Target {
UrlEncoded(param)
}
}
)
}
impl_from_uri_param_from_inner_type!(, T);
impl_from_uri_param_from_inner_type!('a, &'a T);
impl_from_uri_param_from_inner_type!('a, &'a mut T);
rocket::http::impl_from_uri_param_identity!([Query] (T: Serialize) UrlEncoded<T>);
impl<T> From<T> for UrlEncoded<T> {
fn from(value: T) -> Self {
UrlEncoded(value)
}
}
impl<T> Deref for UrlEncoded<T> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &T {
&self.0
}
}
impl<T> DerefMut for UrlEncoded<T> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl From<Error<'_>> for form::Error<'_> {
fn from(e: Error<'_>) -> Self {
match e {
Error::Io(e) => e.into(),
Error::Parse(_, e) => form::Error::custom(e),
}
}
}
#[rocket::async_trait]
impl<'v, T: Deserialize<'v> + Send> form::FromFormField<'v> for UrlEncoded<T> {
fn from_value(field: form::ValueField<'v>) -> Result<Self, form::Errors<'v>> {
Ok(Self::from_str(field.value)?)
}
async fn from_data(f: form::DataField<'v, '_>) -> Result<Self, form::Errors<'v>> {
Ok(Self::from_data(f.request, f.data).await?)
}
}
/// Deserialize an instance of type `T` from bytes of UrlEncoded text.
///
/// **_Always_ use [`UrlEncoded`] to deserialize UrlEncoded request data.**
///
/// # Example
///
/// ```
/// use rocket::serde::Deserialize;
///
/// #[derive(Debug, PartialEq, Deserialize)]
/// struct Data<'r> {
/// framework: &'r str,
/// stars: usize,
/// }
///
/// let bytes = br#"framework=Rocket&stars=5"#;
///
/// let data: Data = rocket_enumform::from_slice(bytes).unwrap();
/// assert_eq!(data, Data { framework: "Rocket", stars: 5, });
/// ```
///
/// # Errors
///
/// This conversion can fail if the structure of the input does not match the
/// structure expected by `T`, for example if `T` is a struct type but the input
/// contains something other than a UrlEncoded map. It can also fail if the structure
/// is correct but `T`'s implementation of `Deserialize` decides that something
/// is wrong with the data, for example required struct fields are missing from
/// the UrlEncoded map or some number is too big to fit in the expected primitive
/// type.
#[inline(always)]
pub fn from_slice<'a, T>(slice: &'a [u8]) -> Result<T, ::serde_urlencoded::de::Error>
where
T: Deserialize<'a>,
{
::serde_urlencoded::from_bytes(slice)
}
/// Deserialize an instance of type `T` from a string of UrlEncoded text.
///
/// **_Always_ use [`UrlEncoded`] to deserialize UrlEncoded request data.**
///
/// # Example
///
/// ```
/// use rocket::serde::Deserialize;
///
/// #[derive(Debug, PartialEq, Deserialize)]
/// struct Data<'r> {
/// framework: &'r str,
/// stars: usize,
/// }
///
/// let string = r#"framework=Rocket&stars=5"#;
///
/// let data: Data = rocket_enumform::from_str(string).unwrap();
/// assert_eq!(data, Data { framework: "Rocket", stars: 5 });
/// ```
///
/// # Errors
///
/// This conversion can fail if the structure of the input does not match the
/// structure expected by `T`, for example if `T` is a struct type but the input
/// contains something other than a UrlEncoded map. It can also fail if the structure
/// is correct but `T`'s implementation of `Deserialize` decides that something
/// is wrong with the data, for example required struct fields are missing from
/// the UrlEncoded map or some number is too big to fit in the expected primitive
/// type.
#[inline(always)]
pub fn from_str<'a, T>(string: &'a str) -> Result<T, ::serde_urlencoded::de::Error>
where
T: Deserialize<'a>,
{
::serde_urlencoded::from_str(string)
}