File Upload Security in Rust Checking Type Size and Name
Treat every upload as hostile: limit the size, sniff the real content type, ignore the client filename, store outside the web root under generated names, scan where needed and serve with safe headers.

File uploads are where a web application accepts arbitrary bytes from strangers and writes them to disk. That combination has produced many serious vulnerabilities: remote code execution through uploaded scripts, stored XSS through HTML files, path traversal through crafted names, disk exhaustion through giant bodies. Rust removes memory corruption from the picture, not these logic bugs. This post walks through the controls with Axum. Versions: Rust 1.90 with edition 2024, Axum 0.8 (with the multipart feature), infer 0.16, uuid 1, Tokio 1.47.
1. Limit the size, early
use axum::{extract::DefaultBodyLimit, routing::post, Router};
use tower_http::limit::RequestBodyLimitLayer;
fn app() -> Router {
Router::new()
.route("/upload", post(upload))
.layer(DefaultBodyLimit::disable()) // Axum's 2 MB default would reject big files
.layer(RequestBodyLimitLayer::new(10 * 1024 * 1024)) // our own hard cap: 10 MB
}
async fn upload() {}Axum limits bodies to 2 MB by default for the buffering extractors; for uploads you raise it deliberately, to a number you chose, and add a layer so oversized requests are rejected at the edge. Set a reverse-proxy limit too (client_max_body_size in Nginx), and a request timeout so slow uploads do not hold connections forever (request limits and slow clients). Also count bytes yourself while streaming, since a chunked body can lie about its length.
2. Read the type from the bytes
const ALLOWED: &[(&str, &str)] = &[
("image/png", "png"),
("image/jpeg", "jpg"),
("application/pdf", "pdf"),
];
fn detect(bytes: &[u8]) -> Option<(&'static str, &'static str)> {
let kind = infer::get(bytes)?;
ALLOWED.iter().copied().find(|(mime, _)| *mime == kind.mime_type())
}
fn main() {
let png = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0];
println!("{:?}", detect(&png));
println!("{:?}", detect(b"<html><script>alert(1)</script>"));
}Some(("image/png", "png"))
NoneThe infer crate recognizes formats from their magic bytes. Use an allow-list of the formats you accept; everything else is rejected, including types it cannot identify. The extension you store is derived from the detected type, never from the client's name. Content sniffing is not proof of safety: a valid image can still carry metadata or an appended payload, and some formats (SVG, HTML, PDF) can contain active content, so for SVG either reject or sanitize.
3. Ignore the client's filename
use axum::extract::Multipart;
use std::path::PathBuf;
use tokio::{fs::File, io::AsyncWriteExt};
use uuid::Uuid;
async fn upload_handler(mut mp: Multipart) -> Result<String, (axum::http::StatusCode, &'static str)> {
use axum::http::StatusCode as S;
let mut field = mp.next_field().await.map_err(|_| (S::BAD_REQUEST, "bad form"))?.ok_or((S::BAD_REQUEST, "no file"))?;
// The client's name is untrusted display data at best; never part of a path.
let _original_name = field.file_name().map(str::to_owned);
let first = field.chunk().await.map_err(|_| (S::BAD_REQUEST, "read error"))?.ok_or((S::BAD_REQUEST, "empty"))?;
let (mime, ext) = detect(&first).ok_or((S::UNSUPPORTED_MEDIA_TYPE, "type not allowed"))?;
let id = Uuid::new_v4();
let path: PathBuf = PathBuf::from("/var/lib/app/uploads").join(format!("{id}.{ext}"));
let mut out = File::create_new(&path).await.map_err(|_| (S::INTERNAL_SERVER_ERROR, "storage"))?;
out.write_all(&first).await.map_err(|_| (S::INTERNAL_SERVER_ERROR, "storage"))?;
let mut written = first.len();
while let Some(chunk) = field.chunk().await.map_err(|_| (S::BAD_REQUEST, "read error"))? {
written += chunk.len();
if written > 10 * 1024 * 1024 {
let _ = tokio::fs::remove_file(&path).await;
return Err((S::PAYLOAD_TOO_LARGE, "file too large"));
}
out.write_all(&chunk).await.map_err(|_| (S::INTERNAL_SERVER_ERROR, "storage"))?;
}
Ok(format!("{id} ({mime})"))
}
fn detect(bytes: &[u8]) -> Option<(&'static str, &'static str)> {
let kind = infer::get(bytes)?;
Some(match kind.mime_type() {
"image/png" => ("image/png", "png"),
"image/jpeg" => ("image/jpeg", "jpg"),
_ => return None,
})
}A generated name ({uuid}.{ext}) rules out path traversal (../../etc/cron.d/x), reserved device names on Windows and collisions. File::create_new fails if the path already exists, so a race or repeated id cannot overwrite a file. The handler streams to disk and enforces the size limit while reading, deleting partial files on failure. Store the original filename in your database as metadata, sanitized for display, if users expect to see it (path traversal and safe joins).
4. Where files live and how they are served
- Not in a directory your web server executes or serves directly. Serve through an authorizing handler or object storage.
- Separate origin: serve user content from a different domain (for example
usercontent.example.net) so any active content cannot read your main site's cookies or storage. - Safe response headers: a fixed
Content-Typefrom your allow-list,Content-Disposition: attachmentunless it is a vetted image, andX-Content-Type-Options: nosniffso browsers do not guess a different type. - Access control: check that the requester may see the file; unguessable ids are not authorization.
5. Process the content
use image::{ImageFormat, ImageReader};
use std::io::Cursor;
fn reencode_image(bytes: &[u8]) -> Result<Vec<u8>, image::ImageError> {
let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format()?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(8000);
limits.max_image_height = Some(8000);
reader.limits(limits); // guard against decompression bombs
let img = reader.decode()?;
let mut out = Vec::new();
img.write_to(&mut Cursor::new(&mut out), ImageFormat::Png)?; // fresh file: metadata and trailing data are gone
Ok(out)
}Decoding and re-encoding an image produces a new file without EXIF location data, embedded scripts or appended bytes, and the dimension limits stop a small file that expands to gigapixels from exhausting memory (resource limits). Run decoding on a blocking thread pool. For documents and archives, consider antivirus scanning (ClamAV) in an isolated worker and never extract archives without limits on entry count, depth and expanded size (zip bombs and zip-slip paths).
6. Direct-to-storage uploads
With presigned URLs the browser uploads to object storage, and your server never sees the bytes: it signs a URL with a size cap and content type, then processes the stored object in a worker after the upload completes (presigned uploads, form and file uploads in Axum). The checks above still apply, run in the worker, before the file becomes visible to anyone.


