From c7883e0eb4757d070bc64b0a7b38642952ff819f Mon Sep 17 00:00:00 2001 From: Erik Wegner Date: Tue, 17 Dec 2024 21:21:51 +0100 Subject: [PATCH] Detect multiple boundary values --- src/error.rs | 7 ++++++- src/lib.rs | 27 ++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/error.rs b/src/error.rs index 4f3b47b..f369f37 100644 --- a/src/error.rs +++ b/src/error.rs @@ -51,6 +51,9 @@ pub enum Error { /// No boundary found in `Content-Type` header. NoBoundary, + /// More than one boundary found in `Content-Type` header. + MultipleBoundaries, + /// Failed to decode the field data as `JSON` in /// [`field.json()`](crate::Field::json) method. #[cfg(feature = "json")] @@ -96,6 +99,7 @@ impl Display for Error { Error::LockFailure => write!(f, "failed to lock multipart state"), Error::NoMultipart => write!(f, "Content-Type is not multipart/form-data"), Error::NoBoundary => write!(f, "multipart boundary not found in Content-Type"), + Error::MultipleBoundaries => write!(f, "multipart boundary found multiple times in Content-Type"), #[cfg(feature = "json")] Error::DecodeJson(_) => write!(f, "failed to decode field data as JSON"), } @@ -120,7 +124,8 @@ impl std::error::Error for Error { | Error::StreamSizeExceeded { .. } | Error::LockFailure | Error::NoMultipart - | Error::NoBoundary => None, + | Error::NoBoundary + | Error::MultipleBoundaries => None, } } } diff --git a/src/lib.rs b/src/lib.rs index 3a1e04e..27efcb8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -175,9 +175,21 @@ pub fn parse_boundary>(content_type: T) -> Result { return Err(Error::NoMultipart); } - m.get_param(mime::BOUNDARY) - .map(|name| name.as_str().to_owned()) - .ok_or(Error::NoBoundary) + let mut count = 0; + let mut boundary: Option = None; + for param in m.params() { + if param.0 == mime::BOUNDARY { + count += 1; + if count == 1 { + boundary = Some(param.1.as_str().to_owned()); + continue; + } + if count > 1 { + return Err(Error::MultipleBoundaries); + } + } + } + boundary.ok_or(Error::NoBoundary) } #[cfg(test)] @@ -192,6 +204,15 @@ mod tests { let content_type = "multipart/form-data; boundary=------ABCDEFG"; assert_eq!(parse_boundary(content_type), Ok("------ABCDEFG".to_owned())); + let content_type = "multipart/form-data; boundary=firstboundary; boundary=secondaryboundary"; + let boundary = parse_boundary(content_type); + assert!( + boundary.is_err(), + "expected error for invalid boundary, boundary set to {}", + boundary.unwrap() + ); + assert_eq!(Error::MultipleBoundaries, boundary.unwrap_err()); + let content_type = "boundary=------ABCDEFG"; assert!(parse_boundary(content_type).is_err());