expression

File uploads: validate content, not just metadata

Validate the bytes against the actual format accepted by the application. This tiny policy accepts only nonempty UTF-8 ASCII alphanumeric text and spaces, at most eight bytes. It is intentionally not an image validator, malware scanner or general-purpose upload policy. In-memory standalone Cargo example. Expected stdout (not executed): true false false false Common mistake: Accepting all bytes because the filename ends in .txt.

Formal Syntax & Structure

rust syntaxrust
std::str::from_utf8(bytes)

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    fn accepts(bytes: &[u8]) -> bool {        !bytes.is_empty() && bytes.len() <= 8 && std::str::from_utf8(bytes).is_ok_and(|s| s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b' '))    }    for bytes in [b"Note 7".as_slice(), b"".as_slice(), b"123456789".as_slice(), b"\xff".as_slice()] {        println!("{}", accepts(bytes));    }}
Rust Reference