Skip to content

Commit

Permalink
Detect multiple boundary values
Browse files Browse the repository at this point in the history
  • Loading branch information
ErikWegner committed Dec 17, 2024
1 parent 09cc730 commit c7883e0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
7 changes: 6 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -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"),
}
Expand All @@ -120,7 +124,8 @@ impl std::error::Error for Error {
| Error::StreamSizeExceeded { .. }
| Error::LockFailure
| Error::NoMultipart
| Error::NoBoundary => None,
| Error::NoBoundary
| Error::MultipleBoundaries => None,
}
}
}
Expand Down
27 changes: 24 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,21 @@ pub fn parse_boundary<T: AsRef<str>>(content_type: T) -> Result<String> {
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<String> = 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)]
Expand All @@ -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());

Expand Down

0 comments on commit c7883e0

Please sign in to comment.