-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement IntoResponse
for MultipartError
#1861
Merged
Merged
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,9 +12,10 @@ use axum::{ | |
use futures_util::stream::Stream; | ||
use http::{ | ||
header::{HeaderMap, CONTENT_TYPE}, | ||
Request, | ||
Request, StatusCode, | ||
}; | ||
use std::{ | ||
error::Error, | ||
fmt, | ||
pin::Pin, | ||
task::{Context, Poll}, | ||
|
@@ -246,6 +247,58 @@ impl MultipartError { | |
fn from_multer(multer: multer::Error) -> Self { | ||
Self { source: multer } | ||
} | ||
|
||
/// Get the response body text used for this rejection. | ||
pub fn body_text(&self) -> String { | ||
self.source.to_string() | ||
} | ||
|
||
/// Get the status code used for this rejection. | ||
pub fn status(&self) -> http::StatusCode { | ||
status_code_from_multer_error(&self.source) | ||
} | ||
} | ||
|
||
fn status_code_from_multer_error(err: &multer::Error) -> StatusCode { | ||
match err { | ||
multer::Error::UnknownField { .. } | ||
| multer::Error::IncompleteFieldData { .. } | ||
| multer::Error::IncompleteHeaders | ||
| multer::Error::ReadHeaderFailed(..) | ||
| multer::Error::DecodeHeaderName { .. } | ||
| multer::Error::DecodeContentType(..) | ||
| multer::Error::NoBoundary | ||
| multer::Error::DecodeHeaderValue { .. } | ||
| multer::Error::NoMultipart | ||
| multer::Error::IncompleteStream => StatusCode::BAD_REQUEST, | ||
multer::Error::FieldSizeExceeded { .. } | multer::Error::StreamSizeExceeded { .. } => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This kind of error will never thrown, because There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. But we still need an exhaustive match. |
||
StatusCode::PAYLOAD_TOO_LARGE | ||
} | ||
multer::Error::LockFailure => StatusCode::INTERNAL_SERVER_ERROR, | ||
multer::Error::StreamReadFailed(err) => { | ||
if let Some(err) = err.downcast_ref::<multer::Error>() { | ||
return status_code_from_multer_error(err); | ||
} | ||
davidpdrsn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if err | ||
.downcast_ref::<axum::Error>() | ||
.and_then(|err| err.source()) | ||
.and_then(|err| err.downcast_ref::<http_body::LengthLimitError>()) | ||
.is_some() | ||
{ | ||
return StatusCode::PAYLOAD_TOO_LARGE; | ||
} | ||
|
||
StatusCode::INTERNAL_SERVER_ERROR | ||
} | ||
_ => StatusCode::BAD_REQUEST, | ||
davidpdrsn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
impl IntoResponse for MultipartError { | ||
fn into_response(self) -> Response { | ||
(self.status(), self.body_text()).into_response() | ||
} | ||
} | ||
|
||
impl fmt::Display for MultipartError { | ||
|
@@ -357,7 +410,9 @@ impl std::error::Error for InvalidBoundary {} | |
mod tests { | ||
use super::*; | ||
use crate::test_helpers::*; | ||
use axum::{body::Body, response::IntoResponse, routing::post, Router}; | ||
use axum::{ | ||
body::Body, extract::DefaultBodyLimit, response::IntoResponse, routing::post, Router, | ||
}; | ||
|
||
#[tokio::test] | ||
async fn content_type_with_encoding() { | ||
|
@@ -395,4 +450,28 @@ mod tests { | |
async fn handler(_: Multipart) {} | ||
let _app: Router<(), http_body::Limited<Body>> = Router::new().route("/", post(handler)); | ||
} | ||
|
||
#[tokio::test] | ||
async fn body_too_large() { | ||
const BYTES: &[u8] = "<!doctype html><title>🦀</title>".as_bytes(); | ||
|
||
async fn handle(mut multipart: Multipart) -> Result<(), MultipartError> { | ||
while let Some(field) = multipart.next_field().await? { | ||
field.bytes().await?; | ||
} | ||
Ok(()) | ||
} | ||
|
||
let app = Router::new() | ||
.route("/", post(handle)) | ||
.layer(DefaultBodyLimit::max(BYTES.len() - 1)); | ||
|
||
let client = TestClient::new(app); | ||
|
||
let form = | ||
reqwest::multipart::Form::new().part("file", reqwest::multipart::Part::bytes(BYTES)); | ||
|
||
let res = client.post("/").multipart(form).send().await; | ||
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure if this
multer::Error::ReadHeaderFailed
is always thrown by the client side. How do you think? Is it OK to response as400
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Feels like if the headers cannot be parsed then that's a client issue. The inner error is
httparse::Error