refactor(middleware): polish the ContentLengthLimiter implementation

This commit is contained in:
Orhun Parmaksız 2023-06-05 23:02:10 +03:00
parent 1670a71cdd
commit 19cb7cccb7
No known key found for this signature in database
GPG Key ID: F83424824B3E4B90
2 changed files with 11 additions and 15 deletions

View File

@ -19,16 +19,8 @@ pub struct ContentLengthLimiter {
impl ContentLengthLimiter {
/// Contructs a new instance.
pub fn new(limit: u128) -> Self {
Self { max_bytes: limit }
}
}
impl Default for ContentLengthLimiter {
fn default() -> Self {
Self {
max_bytes: 10 * 1024 * 1024,
}
pub fn new(max_bytes: u128) -> Self {
Self { max_bytes }
}
}
@ -46,7 +38,7 @@ where
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(ContentLengthLimiterMiddleware {
service: Rc::new(service),
limit: self.max_bytes,
max_bytes: self.max_bytes,
}))
}
}
@ -55,7 +47,7 @@ where
#[derive(Debug)]
pub struct ContentLengthLimiterMiddleware<S> {
service: Rc<S>,
limit: u128,
max_bytes: u128,
}
impl<S, B> Service<ServiceRequest> for ContentLengthLimiterMiddleware<S>
@ -76,8 +68,7 @@ where
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<u128>().ok())
{
if content_length > self.limit {
log::warn!("{} > {}", content_length, self.limit);
if content_length > self.max_bytes {
log::warn!("Upload rejected due to exceeded limit.");
return Box::pin(async move {
// drain the body due to https://github.com/actix/actix-web/issues/2695

View File

@ -313,6 +313,11 @@ mod tests {
header::CONTENT_TYPE,
header::HeaderValue::from_static("multipart/mixed; boundary=\"multipart_bound\""),
))
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_str(&data.bytes().len().to_string())
.expect("cannot create header value"),
))
.set_payload(multipart_data)
}
@ -454,7 +459,7 @@ mod tests {
App::new()
.app_data(Data::new(RwLock::new(Config::default())))
.app_data(Data::new(Client::default()))
.wrap(ContentLengthLimiter::new(30000))
.wrap(ContentLengthLimiter::new(1))
.configure(configure_routes),
)
.await;