#[derive(Debug)]
pub(crate) struct Multipart {
pub(crate) body: Vec<u8>,
pub(crate) content_type: String,
}
#[derive(Debug)]
pub(crate) struct FilePart<'a> {
pub(crate) field: &'a str,
pub(crate) file_name: &'a str,
pub(crate) content_type: &'a str,
pub(crate) bytes: &'a [u8],
}
pub(crate) fn encode_file(part: &FilePart<'_>) -> Multipart {
encode_file_with_fields(&[], part)
}
pub(crate) fn encode_file_with_fields(fields: &[(&str, &str)], part: &FilePart<'_>) -> Multipart {
let boundary = pick_boundary_for(part.bytes, fields);
let file_name = sanitize_file_name(part.file_name);
let mut body = Vec::with_capacity(part.bytes.len() + 256);
for (name, value) in fields {
body.extend_from_slice(b"--");
body.extend_from_slice(boundary.as_bytes());
body.extend_from_slice(b"\r\nContent-Disposition: form-data; name=\"");
body.extend_from_slice(name.as_bytes());
body.extend_from_slice(b"\"\r\n\r\n");
body.extend_from_slice(value.as_bytes());
body.extend_from_slice(b"\r\n");
}
body.extend_from_slice(b"--");
body.extend_from_slice(boundary.as_bytes());
body.extend_from_slice(b"\r\nContent-Disposition: form-data; name=\"");
body.extend_from_slice(part.field.as_bytes());
body.extend_from_slice(b"\"; filename=\"");
body.extend_from_slice(file_name.as_bytes());
body.extend_from_slice(b"\"\r\nContent-Type: ");
body.extend_from_slice(part.content_type.as_bytes());
body.extend_from_slice(b"\r\n\r\n");
body.extend_from_slice(part.bytes);
body.extend_from_slice(b"\r\n--");
body.extend_from_slice(boundary.as_bytes());
body.extend_from_slice(b"--\r\n");
Multipart {
body,
content_type: format!("multipart/form-data; boundary={boundary}"),
}
}
fn pick_boundary_for(payload: &[u8], fields: &[(&str, &str)]) -> String {
let mut boundary = pick_boundary(payload);
while fields
.iter()
.any(|(_, value)| contains(value.as_bytes(), boundary.as_bytes()))
|| contains(payload, boundary.as_bytes())
{
boundary.push('-');
}
boundary
}
fn pick_boundary(payload: &[u8]) -> String {
let mut boundary = String::from("delopayFormBoundary7MA4YWxkTrZu0gW");
while contains(payload, boundary.as_bytes()) {
boundary.push('-');
}
boundary
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
if needle.is_empty() || haystack.len() < needle.len() {
return false;
}
haystack.windows(needle.len()).any(|w| w == needle)
}
fn sanitize_file_name(name: &str) -> String {
let cleaned: String = name
.chars()
.filter(|c| !matches!(c, '"' | '\\' | '\r' | '\n' | '/'))
.collect();
if cleaned.is_empty() {
"upload".to_string()
} else {
cleaned
}
}
#[cfg(test)]
mod tests {
use super::*;
fn encoded(bytes: &[u8], file_name: &str) -> Multipart {
encode_file(&FilePart {
field: "file",
file_name,
content_type: "image/png",
bytes,
})
}
#[test]
fn body_wraps_the_payload_in_matching_boundaries() {
let out = encoded(b"PNGDATA", "logo.png");
let text = String::from_utf8(out.body.clone()).unwrap();
let boundary = out
.content_type
.strip_prefix("multipart/form-data; boundary=")
.expect("content type advertises the boundary");
assert!(text.starts_with(&format!("--{boundary}\r\n")));
assert!(text.ends_with(&format!("\r\n--{boundary}--\r\n")));
assert!(
text.contains("Content-Disposition: form-data; name=\"file\"; filename=\"logo.png\"")
);
assert!(text.contains("Content-Type: image/png\r\n\r\nPNGDATA\r\n"));
}
#[test]
fn boundary_is_extended_until_it_does_not_occur_in_the_payload() {
let hostile = b"before--delopayFormBoundary7MA4YWxkTrZu0gW--after".to_vec();
let out = encoded(&hostile, "logo.png");
let boundary = out
.content_type
.strip_prefix("multipart/form-data; boundary=")
.unwrap();
assert!(
boundary.ends_with('-'),
"boundary should have been extended, got {boundary}"
);
assert!(!contains(&hostile, boundary.as_bytes()));
let count = out
.body
.windows(boundary.len())
.filter(|w| *w == boundary.as_bytes())
.count();
assert_eq!(count, 2);
}
#[test]
fn file_name_cannot_inject_headers_or_paths() {
let out = encoded(b"x", "ev\"il\r\nX-Injected: 1/../logo.png");
let text = String::from_utf8(out.body).unwrap();
assert!(!text.contains("X-Injected: 1\r\n"));
assert!(text.contains("filename=\"evilX-Injected: 1..logo.png\""));
}
#[test]
fn empty_file_name_falls_back_rather_than_emitting_an_empty_filename() {
let out = encoded(b"x", "///");
let text = String::from_utf8(out.body).unwrap();
assert!(text.contains("filename=\"upload\""));
}
#[test]
fn text_fields_come_before_the_file_part() {
let out = encode_file_with_fields(
&[("client_upload_id", "upl_12345678")],
&FilePart {
field: "file",
file_name: "receipt.pdf",
content_type: "application/pdf",
bytes: b"%PDF",
},
);
let text = String::from_utf8(out.body).unwrap();
let boundary = out
.content_type
.strip_prefix("multipart/form-data; boundary=")
.unwrap();
let field = format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"client_upload_id\"\r\n\r\nupl_12345678\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"receipt.pdf\""
);
assert!(text.starts_with(&field), "unexpected body: {text}");
assert!(text.ends_with(&format!("\r\n%PDF\r\n--{boundary}--\r\n")));
}
#[test]
fn boundary_is_extended_until_it_does_not_occur_in_a_field_value() {
let hostile = "x--delopayFormBoundary7MA4YWxkTrZu0gW--y";
let out = encode_file_with_fields(
&[("client_upload_id", hostile)],
&FilePart {
field: "file",
file_name: "a.txt",
content_type: "text/plain",
bytes: b"clean",
},
);
let boundary = out
.content_type
.strip_prefix("multipart/form-data; boundary=")
.unwrap();
assert!(!contains(hostile.as_bytes(), boundary.as_bytes()));
let count = out
.body
.windows(boundary.len())
.filter(|w| *w == boundary.as_bytes())
.count();
assert_eq!(count, 3);
}
#[test]
fn binary_payloads_survive_byte_for_byte() {
let bytes: Vec<u8> = (0u8..=255).collect();
let out = encoded(&bytes, "logo.png");
let marker = b"\r\n\r\n";
let start = out
.body
.windows(marker.len())
.position(|w| w == marker)
.unwrap()
+ marker.len();
assert_eq!(&out.body[start..start + bytes.len()], &bytes[..]);
}
}