AleannLab

Unsafe File Uploads: The File Picker Is Not a Security Check

AleannLab team3 min read

Everything the browser tells you about an uploaded file can be forged: its name, its extension, its MIME type, its size. The accept attribute on a file input only filters the picker. A safe upload flow checks the real content type and size on the server, generates its own file name, stores files outside your application, and serves them in a way that cannot run code in your users' browsers.

On this page
  1. What can go wrong
  2. Validate on the server
  3. Process images
  4. Store and serve safely
  5. Test it

Upload features built by AI tools usually work on the first try and have none of these checks. The demo was "upload an avatar", and the avatar uploaded.

What can go wrong

Scripts served from your domain. An .html or .svg file uploaded and then opened at yourapp.com/uploads/x.svg runs JavaScript in your origin. That is stored XSS without touching your code. SVG is the common trap, because it looks like an image and is accepted by image filters.

Executable files on your server. On a traditional server where uploads land inside the web root, an uploaded .php or .jsp can be run by requesting it. Less likely on serverless platforms, still common on a VPS.

Path traversal. A file named ../../app/config.js written with path.join(uploadDir, file.name) ends up outside the upload folder.

Disk and bill exhaustion. No size limit means someone uploads 5 GB files in a loop.

Malware distribution. Your storage becomes free hosting for files that get your domain flagged.

Overwrites and leaks. Using the original file name lets one user overwrite another's file, or guess it. See open storage buckets.

Validate on the server

TypeScript
import { fileTypeFromBuffer } from 'file-type';
import { randomUUID } from 'node:crypto';

const ALLOWED = new Map([
  ['image/png', 'png'],
  ['image/jpeg', 'jpg'],
  ['image/webp', 'webp'],
  ['application/pdf', 'pdf'],
]);
const MAX_BYTES = 10 * 1024 * 1024;

export async function POST(req: Request) {
  const session = await auth();
  if (!session) return Response.json({ error: 'Unauthorized' }, { status: 401 });

  const form = await req.formData();
  const file = form.get('file');
  if (!(file instanceof File)) return Response.json({ error: 'No file' }, { status: 400 });
  if (file.size > MAX_BYTES) return Response.json({ error: 'File too large' }, { status: 413 });

  const buffer = Buffer.from(await file.arrayBuffer());
  const detected = await fileTypeFromBuffer(buffer);          // reads the file's first bytes
  const ext = detected && ALLOWED.get(detected.mime);
  if (!ext) return Response.json({ error: 'File type not allowed' }, { status: 415 });

  const key = `${session.user.id}/${randomUUID()}.${ext}`;    // our name, not theirs
  await storage.put(key, buffer, { contentType: detected.mime });
  return Response.json({ key });
}

What this does:

  • Allowlist, not blocklist. Name the types you accept. Do not try to list the dangerous ones.
  • Content, not label. file.type and the extension come from the client. file-type inspects the bytes.
  • Generated name. The original name is kept, if at all, as a text field in your database for display.
  • Size checked before processing. Also set a body size limit at the platform or proxy level, so oversized requests are rejected before your code runs.

SVG cannot be detected by magic bytes and should not be on the list unless you sanitise it (DOMPurify can) or convert it to PNG.

Process images

Re-encoding an image with a library such as sharp strips embedded scripts, metadata (including GPS coordinates in photos) and most malformed-file tricks:

TypeScript
const safe = await sharp(buffer).rotate().resize({ width: 2000, withoutEnlargement: true }).webp().toBuffer();

Set a pixel limit as well. A tiny file can declare enormous dimensions and exhaust memory when decoded.

Store and serve safely

  • Object storage, not the app's disk. S3, R2, Supabase Storage. Private bucket for anything that is not meant to be public.
  • A separate domain for user content. usercontent-yourapp.com instead of yourapp.com/uploads. A script in an uploaded file then runs in an origin with no cookies and no access to your app.
  • Headers on download. Content-Disposition: attachment for anything that is not an image you re-encoded, and X-Content-Type-Options: nosniff so browsers do not guess a type.
  • Signed URLs with a short lifetime for private files.

If the browser uploads directly to storage with a presigned URL, set the conditions when you sign it: the key, the content type and a maximum length. Then validate the object after upload and delete it if it fails.

Test it

  1. Rename test.html to test.png and upload it. It should be rejected.
  2. Upload an SVG containing <script>alert(document.domain)</script> and open its URL.
  3. Upload a file larger than the limit, by curl, bypassing the form.
  4. Send a file name with ../ in it.
  5. Request another user's file by its URL while logged in as someone else.

File uploads are part of check 9 in our security checklist for vibe-coded apps. If you want your upload flow and storage reviewed and fixed, see our app rescue and security audit.

All articles →

Ready to discuss your project with us?

idea
*
*
*
I'm interested in...
Web Development
App Development
UX/UI Design
DevOps
Artificial Intelligence And Machine Learning
QA Testing
Mobile Development
Consultation
OutSource
Project budget (USD)
≤ $5K
$10K-$20K
$30K-$40K
$50K-$60K
>$100K
Upload file