Don't sniff media type in save_file()

This commit is contained in:
silverpill 2023-01-06 01:14:01 +00:00
parent 5b3aa2a24b
commit 68e464c813
3 changed files with 22 additions and 12 deletions

View file

@ -12,7 +12,7 @@ use crate::http_signatures::create::{
create_http_signature,
HttpSignatureError,
};
use crate::utils::files::save_file;
use crate::utils::files::{save_file, sniff_media_type};
use crate::utils::urls::guess_protocol;
use crate::webfinger::types::JsonResourceDescriptor;
@ -118,8 +118,13 @@ pub async fn fetch_file(
if file_data.len() > FILE_MAX_SIZE as usize {
return Err(FetchError::OtherError("file is too large"));
};
let (file_name, media_type) = save_file(file_data.to_vec(), output_dir, None)?;
Ok((file_name, media_type))
let maybe_media_type = sniff_media_type(&file_data);
let file_name = save_file(
file_data.to_vec(),
output_dir,
maybe_media_type.as_deref(),
)?;
Ok((file_name, maybe_media_type))
}
pub async fn perform_webfinger_query(

View file

@ -40,11 +40,18 @@ pub fn save_b64_file(
if data.len() > UPLOAD_MAX_SIZE {
return Err(UploadError::TooLarge);
};
// Sniff media type if not provided
maybe_media_type = maybe_media_type.or(sniff_media_type(&data));
if maybe_media_type.as_deref() == Some("image/svg+xml") {
// Don't treat SVG files as images
maybe_media_type = None;
};
Ok(save_file(data, output_dir, maybe_media_type)?)
let file_name = save_file(
data,
output_dir,
maybe_media_type.as_deref(),
)?;
Ok((file_name, maybe_media_type))
}
pub fn save_validated_b64_file(
@ -61,7 +68,6 @@ pub fn save_validated_b64_file(
if !media_type.starts_with(media_type_prefix) {
return Err(UploadError::InvalidMediaType);
};
let (file_name, _) =
save_file(data, output_dir, Some(media_type.clone()))?;
let file_name = save_file(data, output_dir, Some(&media_type))?;
Ok((file_name, media_type))
}

View file

@ -43,17 +43,16 @@ pub fn set_file_permissions(file_path: &Path, mode: u32) -> Result<(), Error> {
Ok(())
}
/// Save validated file to specified directory
pub fn save_file(
data: Vec<u8>,
output_dir: &Path,
media_type: Option<String>,
) -> Result<(String, Option<String>), Error> {
// Sniff media type if not provided
let media_type = media_type.or(sniff_media_type(&data));
let file_name = get_file_name(&data, media_type.as_deref());
media_type: Option<&str>,
) -> Result<String, Error> {
let file_name = get_file_name(&data, media_type);
let file_path = output_dir.join(&file_name);
write_file(&data, &file_path)?;
Ok((file_name, media_type))
Ok(file_name)
}
pub fn get_file_url(instance_url: &str, file_name: &str) -> String {