What’s the safest way to validate image uploads in FastAPI?

0
1
Asked By MellowCedar47 On

I'm building an ecommerce chat widget where users can upload product photos they're looking for. I want to accept only JPEG, PNG, and WebP files and avoid storing invalid or potentially dangerous uploads.

My current plan is to first check the request's Content-Type header as a quick filter, then inspect the file contents in memory with python-magic to determine the actual MIME type. Files that fail either check would be rejected. Uploads will probably be stored in Cloudflare R2, but I'd still prefer not to keep suspicious files there. Is this a reasonable validation strategy, and are there additional safeguards I should add?

3 Answers

Answered By HarborLynx31 On

Treat every upload as untrusted. Store it with a generated name rather than the original filename, keep it outside any executable/static application path, and consider processing it asynchronously in a restricted environment. When serving the result, use a separate origin if possible, send a fixed image Content-Type, and include X-Content-Type-Options: nosniff. These measures reduce the impact if validation ever misses something.

Answered By QuartzMeadow62 On

Use the header check only as a fast rejection step, not as a security decision. Then enforce a maximum upload size before reading or processing the file, and verify the detected type against the formats you actually support. After decoding, also cap the pixel dimensions or total decoded pixel count because a small compressed image can expand into a huge amount of memory. Stripping metadata such as EXIF during re-encoding is a useful additional step.

MellowCedar47 -

We’ll apply the size limit before calling python-magic, then remove EXIF data as part of the image processing step.

Answered By OrbitPine8 On

Checking the declared Content-Type first and then inspecting the file signature is a sensible baseline, but neither check proves that the file is completely safe. A valid image can sometimes contain extra data or be crafted as a polyglot file. For higher assurance, decode the image with a well-maintained imaging library and re-encode it into a fresh file. Keep that processing isolated and patched, since image parsers have also had vulnerabilities. Re-encoding may slightly affect quality for lossy formats.

MellowCedar47 -

Would checking the first few kilobytes with python-magic detect those polyglot cases?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.