From 639b7ce6163e8abd63f0833d4e17a2c978421e7b Mon Sep 17 00:00:00 2001 From: Bodo Junglas Date: Tue, 4 Dec 2018 13:06:16 +0100 Subject: [PATCH] Add limited raw payload --- src/parse_request.rs | 57 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 5 deletions(-) diff --git a/src/parse_request.rs b/src/parse_request.rs index 0186bed..dbaacdf 100644 --- a/src/parse_request.rs +++ b/src/parse_request.rs @@ -1,13 +1,22 @@ use super::AsyncBusinessResult; -use actix_web::dev::JsonBody; +use actix_web::dev::{JsonBody, MessageBody}; use actix_web::{FromRequest, HttpMessage, HttpRequest}; +use bytes::Bytes; use futures::{Future, IntoFuture}; use problem::Problem; use serde::de::DeserializeOwned; use std::fmt; use std::ops::Deref; -const JSON_REQUEST_LIMIT: usize = 1024 * 1024; +pub struct ValidatedJsonConfig { + limit: usize, +} + +impl Default for ValidatedJsonConfig { + fn default() -> Self { + ValidatedJsonConfig { limit: 1024 * 1024 } + } +} pub struct ValidatedJson(pub T); @@ -49,14 +58,14 @@ where T: DeserializeOwned + 'static, S: 'static, { - type Config = (); + type Config = ValidatedJsonConfig; type Result = Result, Problem>; #[inline] - fn from_request(req: &HttpRequest, _cfg: &Self::Config) -> Self::Result { + fn from_request(req: &HttpRequest, cfg: &Self::Config) -> Self::Result { Ok(Box::new( JsonBody::new(req) - .limit(JSON_REQUEST_LIMIT) + .limit(cfg.limit) .map_err(|error| Problem::bad_request().with_details(format!("Invalid json: {}", error))) .map(ValidatedJson), )) @@ -89,3 +98,41 @@ macro_rules! request_parameter { } }; } + +pub struct LimitedRawConfig { + limit: usize, +} + +impl Default for LimitedRawConfig { + fn default() -> Self { + LimitedRawConfig { limit: 1024 * 1024 } + } +} + +pub struct LimitedRaw(pub Bytes); + +impl Deref for LimitedRaw { + type Target = Bytes; + + fn deref(&self) -> &Bytes { + &self.0 + } +} + +impl FromRequest for LimitedRaw +where + S: 'static, +{ + type Config = LimitedRawConfig; + type Result = Result, Problem>; + + #[inline] + fn from_request(req: &HttpRequest, cfg: &Self::Config) -> Self::Result { + Ok(Box::new( + MessageBody::new(req) + .limit(cfg.limit) + .map_err(|error| Problem::bad_request().with_details(format!("Invalid body: {}", error))) + .map(LimitedRaw), + )) + } +}