Engineering
The filename on an uploaded file is user input
The filename on an uploaded file is user input. Most of us treat it like metadata.
I was writing a simple file-download endpoint the other day, and the obvious version looked like this:
read the file → send it back → set the header to the original filename
It works. It passes tests. And it's a header-injection bug.
That filename was chosen by whoever uploaded the file. If it contains line breaks and lands in a response header unescaped, the uploader gets to write their own headers into your response.
Don't clean it. Don't use it.
The reflex fix is to sanitize it: strip newlines, escape quotes, trim the length. That works right up until someone finds the encoding you didn't think of.
The better fix is to stop using the string at all. Build the filename from data your server already trusts, such as an ID, a record from your database, or a file type you detected yourself. The original filename never gets near the header.
You can't mis-sanitize a string you never use.
This is the mindset shift I keep coming back to as a developer. Sanitizing asks "how do I clean this?" A better question is "do I need this at all?" Surprisingly often, the answer is no.
Where else does the original filename end up in your code? Logs, emails, admin panels, URLs? It's usually more places than you'd guess.