style: apply rustfmt formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+207
-212
@@ -1,212 +1,207 @@
|
|||||||
//! MIME type detection using magic bytes (infer) + extension fallback (mime_guess).
|
//! MIME type detection using magic bytes (infer) + extension fallback (mime_guess).
|
||||||
//!
|
//!
|
||||||
//! Priority order:
|
//! Priority order:
|
||||||
//! 1. If the claimed Content-Type is specific (not `application/octet-stream`), trust it.
|
//! 1. If the claimed Content-Type is specific (not `application/octet-stream`), trust it.
|
||||||
//! 2. Read first bytes of the file and detect via magic bytes (`infer` crate).
|
//! 2. Read first bytes of the file and detect via magic bytes (`infer` crate).
|
||||||
//! 3. Fall back to extension-based detection (`mime_guess`).
|
//! 3. Fall back to extension-based detection (`mime_guess`).
|
||||||
//! 4. If nothing matches, return the original claimed type.
|
//! 4. If nothing matches, return the original claimed type.
|
||||||
//!
|
//!
|
||||||
//! Performance: < 1µs for the `infer` check (reads only header bytes, no allocation).
|
//! Performance: < 1µs for the `infer` check (reads only header bytes, no allocation).
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use tokio::io::AsyncReadExt;
|
use tokio::io::AsyncReadExt;
|
||||||
|
|
||||||
/// Maximum bytes to read for magic-byte detection.
|
/// Maximum bytes to read for magic-byte detection.
|
||||||
const MAGIC_BYTES_LEN: usize = 8192;
|
const MAGIC_BYTES_LEN: usize = 8192;
|
||||||
|
|
||||||
/// Extract the filename component from a `/`-separated path.
|
/// Extract the filename component from a `/`-separated path.
|
||||||
pub fn filename_from_path(path: &str) -> &str {
|
pub fn filename_from_path(path: &str) -> &str {
|
||||||
path.rsplit('/').next().unwrap_or(path)
|
path.rsplit('/').next().unwrap_or(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Refine a claimed MIME type using magic bytes and filename extension.
|
/// Refine a claimed MIME type using magic bytes and filename extension.
|
||||||
///
|
///
|
||||||
/// This is a synchronous function — the caller should already have the first
|
/// This is a synchronous function — the caller should already have the first
|
||||||
/// bytes of the file available (or call the async wrapper below).
|
/// bytes of the file available (or call the async wrapper below).
|
||||||
///
|
///
|
||||||
/// # Arguments
|
/// # Arguments
|
||||||
/// * `buf` — first bytes of the file (at least 8192 for best results)
|
/// * `buf` — first bytes of the file (at least 8192 for best results)
|
||||||
/// * `filename` — original filename (used for extension fallback)
|
/// * `filename` — original filename (used for extension fallback)
|
||||||
/// * `claimed` — the Content-Type sent by the client
|
/// * `claimed` — the Content-Type sent by the client
|
||||||
pub fn refine_content_type(buf: &[u8], filename: &str, claimed: &str) -> String {
|
pub fn refine_content_type(buf: &[u8], filename: &str, claimed: &str) -> String {
|
||||||
// If the client sent a specific type (not generic), trust it
|
// If the client sent a specific type (not generic), trust it
|
||||||
if !claimed.is_empty()
|
if !claimed.is_empty()
|
||||||
&& claimed != "application/octet-stream"
|
&& claimed != "application/octet-stream"
|
||||||
&& claimed != "binary/octet-stream"
|
&& claimed != "binary/octet-stream"
|
||||||
{
|
{
|
||||||
return claimed.to_string();
|
return claimed.to_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. Try magic bytes detection
|
// 1. Try magic bytes detection
|
||||||
if let Some(kind) = infer::get(buf) {
|
if let Some(kind) = infer::get(buf) {
|
||||||
return kind.mime_type().to_string();
|
return kind.mime_type().to_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Try extension-based detection
|
// 2. Try extension-based detection
|
||||||
let guess = mime_guess::from_path(filename);
|
let guess = mime_guess::from_path(filename);
|
||||||
if let Some(mime) = guess.first() {
|
if let Some(mime) = guess.first() {
|
||||||
return mime.to_string();
|
return mime.to_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Fall back to claimed type
|
// 3. Fall back to claimed type
|
||||||
claimed.to_string()
|
claimed.to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Async helper: reads the first bytes of a file on disk and refines the MIME type.
|
/// Async helper: reads the first bytes of a file on disk and refines the MIME type.
|
||||||
///
|
///
|
||||||
/// Designed for the upload path where the file has been spooled to a temp path.
|
/// Designed for the upload path where the file has been spooled to a temp path.
|
||||||
pub async fn refine_content_type_from_file(
|
pub async fn refine_content_type_from_file(
|
||||||
temp_path: &Path,
|
temp_path: &Path,
|
||||||
filename: &str,
|
filename: &str,
|
||||||
claimed: &str,
|
claimed: &str,
|
||||||
) -> String {
|
) -> String {
|
||||||
// Fast path: if the client gave us a specific type, trust it
|
// Fast path: if the client gave us a specific type, trust it
|
||||||
if !claimed.is_empty()
|
if !claimed.is_empty()
|
||||||
&& claimed != "application/octet-stream"
|
&& claimed != "application/octet-stream"
|
||||||
&& claimed != "binary/octet-stream"
|
&& claimed != "binary/octet-stream"
|
||||||
{
|
{
|
||||||
return claimed.to_string();
|
return claimed.to_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read only the first bytes needed for magic detection (not the whole file).
|
// Read only the first bytes needed for magic detection (not the whole file).
|
||||||
match tokio::fs::File::open(temp_path).await {
|
match tokio::fs::File::open(temp_path).await {
|
||||||
Ok(mut file) => {
|
Ok(mut file) => {
|
||||||
let mut buf = vec![0u8; MAGIC_BYTES_LEN];
|
let mut buf = vec![0u8; MAGIC_BYTES_LEN];
|
||||||
let n = file.read(&mut buf).await.unwrap_or(0);
|
let n = file.read(&mut buf).await.unwrap_or(0);
|
||||||
refine_content_type(&buf[..n], filename, claimed)
|
refine_content_type(&buf[..n], filename, claimed)
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!(
|
tracing::warn!(
|
||||||
"MIME detection: failed to read {} for magic bytes: {}",
|
"MIME detection: failed to read {} for magic bytes: {}",
|
||||||
temp_path.display(),
|
temp_path.display(),
|
||||||
e
|
e
|
||||||
);
|
);
|
||||||
// Fall back to extension
|
// Fall back to extension
|
||||||
let guess = mime_guess::from_path(filename);
|
let guess = mime_guess::from_path(filename);
|
||||||
if let Some(mime) = guess.first() {
|
if let Some(mime) = guess.first() {
|
||||||
return mime.to_string();
|
return mime.to_string();
|
||||||
}
|
}
|
||||||
claimed.to_string()
|
claimed.to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
// ── refine_content_type (sync) ──────────────────────────────
|
// ── refine_content_type (sync) ──────────────────────────────
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn specific_claimed_type_is_trusted() {
|
fn specific_claimed_type_is_trusted() {
|
||||||
let result = refine_content_type(b"garbage", "file.txt", "image/png");
|
let result = refine_content_type(b"garbage", "file.txt", "image/png");
|
||||||
assert_eq!(result, "image/png");
|
assert_eq!(result, "image/png");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn octet_stream_triggers_magic_detection_png() {
|
fn octet_stream_triggers_magic_detection_png() {
|
||||||
// PNG magic bytes
|
// PNG magic bytes
|
||||||
let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR";
|
let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR";
|
||||||
let result = refine_content_type(png, "noext", "application/octet-stream");
|
let result = refine_content_type(png, "noext", "application/octet-stream");
|
||||||
assert_eq!(result, "image/png");
|
assert_eq!(result, "image/png");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn octet_stream_triggers_magic_detection_jpeg() {
|
fn octet_stream_triggers_magic_detection_jpeg() {
|
||||||
let jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF";
|
let jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF";
|
||||||
let result = refine_content_type(jpeg, "noext", "application/octet-stream");
|
let result = refine_content_type(jpeg, "noext", "application/octet-stream");
|
||||||
assert_eq!(result, "image/jpeg");
|
assert_eq!(result, "image/jpeg");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn binary_octet_stream_also_triggers_detection() {
|
fn binary_octet_stream_also_triggers_detection() {
|
||||||
let jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF";
|
let jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF";
|
||||||
let result = refine_content_type(jpeg, "noext", "binary/octet-stream");
|
let result = refine_content_type(jpeg, "noext", "binary/octet-stream");
|
||||||
assert_eq!(result, "image/jpeg");
|
assert_eq!(result, "image/jpeg");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn extension_fallback_when_no_magic_match() {
|
fn extension_fallback_when_no_magic_match() {
|
||||||
let result = refine_content_type(b"plain text", "style.css", "application/octet-stream");
|
let result = refine_content_type(b"plain text", "style.css", "application/octet-stream");
|
||||||
assert_eq!(result, "text/css");
|
assert_eq!(result, "text/css");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn falls_back_to_claimed_when_nothing_matches() {
|
fn falls_back_to_claimed_when_nothing_matches() {
|
||||||
let result =
|
let result = refine_content_type(b"unknown stuff", "noext", "application/octet-stream");
|
||||||
refine_content_type(b"unknown stuff", "noext", "application/octet-stream");
|
assert_eq!(result, "application/octet-stream");
|
||||||
assert_eq!(result, "application/octet-stream");
|
}
|
||||||
}
|
|
||||||
|
#[test]
|
||||||
#[test]
|
fn empty_claimed_triggers_detection() {
|
||||||
fn empty_claimed_triggers_detection() {
|
let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR";
|
||||||
let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR";
|
let result = refine_content_type(png, "photo.png", "");
|
||||||
let result = refine_content_type(png, "photo.png", "");
|
assert_eq!(result, "image/png");
|
||||||
assert_eq!(result, "image/png");
|
}
|
||||||
}
|
|
||||||
|
// ── refine_content_type_from_file (async) ───────────────────
|
||||||
// ── refine_content_type_from_file (async) ───────────────────
|
|
||||||
|
#[tokio::test]
|
||||||
#[tokio::test]
|
async fn from_file_detects_png() {
|
||||||
async fn from_file_detects_png() {
|
let mut tmp = tempfile::NamedTempFile::new().unwrap();
|
||||||
let mut tmp = tempfile::NamedTempFile::new().unwrap();
|
let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR";
|
||||||
let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR";
|
tmp.write_all(png).unwrap();
|
||||||
tmp.write_all(png).unwrap();
|
tmp.flush().unwrap();
|
||||||
tmp.flush().unwrap();
|
|
||||||
|
let result =
|
||||||
let result =
|
refine_content_type_from_file(tmp.path(), "photo", "application/octet-stream").await;
|
||||||
refine_content_type_from_file(tmp.path(), "photo", "application/octet-stream").await;
|
assert_eq!(result, "image/png");
|
||||||
assert_eq!(result, "image/png");
|
}
|
||||||
}
|
|
||||||
|
#[tokio::test]
|
||||||
#[tokio::test]
|
async fn from_file_falls_back_to_extension() {
|
||||||
async fn from_file_falls_back_to_extension() {
|
let mut tmp = tempfile::NamedTempFile::new().unwrap();
|
||||||
let mut tmp = tempfile::NamedTempFile::new().unwrap();
|
tmp.write_all(b"not magic").unwrap();
|
||||||
tmp.write_all(b"not magic").unwrap();
|
tmp.flush().unwrap();
|
||||||
tmp.flush().unwrap();
|
|
||||||
|
let result =
|
||||||
let result =
|
refine_content_type_from_file(tmp.path(), "doc.css", "application/octet-stream").await;
|
||||||
refine_content_type_from_file(tmp.path(), "doc.css", "application/octet-stream").await;
|
assert_eq!(result, "text/css");
|
||||||
assert_eq!(result, "text/css");
|
}
|
||||||
}
|
|
||||||
|
#[tokio::test]
|
||||||
#[tokio::test]
|
async fn from_file_trusts_specific_claimed() {
|
||||||
async fn from_file_trusts_specific_claimed() {
|
let result =
|
||||||
let result = refine_content_type_from_file(
|
refine_content_type_from_file(Path::new("/nonexistent"), "file", "image/webp").await;
|
||||||
Path::new("/nonexistent"),
|
assert_eq!(result, "image/webp");
|
||||||
"file",
|
}
|
||||||
"image/webp",
|
|
||||||
)
|
#[tokio::test]
|
||||||
.await;
|
async fn from_file_missing_file_falls_back_to_extension() {
|
||||||
assert_eq!(result, "image/webp");
|
let result = refine_content_type_from_file(
|
||||||
}
|
Path::new("/nonexistent/file"),
|
||||||
|
"photo.jpg",
|
||||||
#[tokio::test]
|
"application/octet-stream",
|
||||||
async fn from_file_missing_file_falls_back_to_extension() {
|
)
|
||||||
let result = refine_content_type_from_file(
|
.await;
|
||||||
Path::new("/nonexistent/file"),
|
assert_eq!(result, "image/jpeg");
|
||||||
"photo.jpg",
|
}
|
||||||
"application/octet-stream",
|
|
||||||
)
|
// ── filename_from_path ──────────────────────────────────────
|
||||||
.await;
|
|
||||||
assert_eq!(result, "image/jpeg");
|
#[test]
|
||||||
}
|
fn extracts_filename_from_deep_path() {
|
||||||
|
assert_eq!(filename_from_path("a/b/c/photo.jpg"), "photo.jpg");
|
||||||
// ── filename_from_path ──────────────────────────────────────
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn extracts_filename_from_deep_path() {
|
fn returns_input_when_no_slash() {
|
||||||
assert_eq!(filename_from_path("a/b/c/photo.jpg"), "photo.jpg");
|
assert_eq!(filename_from_path("photo.jpg"), "photo.jpg");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn returns_input_when_no_slash() {
|
fn handles_trailing_slash() {
|
||||||
assert_eq!(filename_from_path("photo.jpg"), "photo.jpg");
|
assert_eq!(filename_from_path("a/b/"), "");
|
||||||
}
|
}
|
||||||
|
}
|
||||||
#[test]
|
|
||||||
fn handles_trailing_slash() {
|
|
||||||
assert_eq!(filename_from_path("a/b/"), "");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user