Skip to main content

Security and hardening · Intermediate · 22 min

Validate file uploads before you store or serve them

By Padding · Updated 18 Nov 2026
python:3.15-slim (Debian) · Python 3.15.2 · FastAPI 0.165.0 · Pillow 13.0.0 · pytest 9.2.0

You will take a FastAPI image upload route that trusts everything the browser sends, prove its flaws with pytest, and rebuild it with size limits, type checks from the file's own bytes, Pillow re-encoding, random storage names and safe download headers.

On this page

An upload form is the one place where a stranger gets to put a file on your server. Everything that arrives with the file is chosen by the sender: the name, the extension, the Content-Type header and the bytes themselves. A route that trusts any of those can be made to write outside its folder, store a web page that runs script on your domain, fill your disk, or keep the GPS position from a user's photo and hand it to everyone who downloads it.

In this tutorial you work on a small FastAPI app that accepts profile and listing photos. You first write it the quick way and a set of pytest tests that state the rules a safe upload route must follow. The tests fail and name each flaw. Then you rebuild the route in layers: a size limit at the proxy and in the app, a type check that reads the file's first bytes, a Pillow re-encode that drops metadata and anything hidden in the image, random storage names in a folder the web server never serves, and download headers that stop the browser guessing. Every check uses harmless data on your own machine.

The pattern applies to other frameworks as well. The browser half of uploads, with drag and drop and progress, is in upload files with drag and drop and a progress bar.

Step 1 · Create the project

Make a throwaway project folder and add the packages. fastapi[standard] brings python-multipart, which FastAPI needs to read form uploads, and httpx, which its test client uses. Pillow reads and rewrites images. pytest is a development dependency, so it never ships with the app:

Bash
mkdir -p ~/uploads-demo/tests
cd ~/uploads-demo
uv init --no-package
uv add "fastapi[standard]>=0.165,<0.166" "pillow>=13.0,<13.1"
uv add --dev "pytest>=9.2,<9.3"
cat >> pyproject.toml <<'TOML'

[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
TOML

The last command appends a pytest section so the tests can import the app's modules from the project folder.

Check it worked

Bash
uv run python -c "import fastapi, PIL, pytest; print(fastapi.__version__, PIL.__version__, pytest.__version__)"

The output is 0.165.0 13.0.0 9.2.0, or later patch releases of the same lines.

Step 2 · Write the quick version and the tests that catch it

Here is the route as it is often first written. It checks that the Content-Type header starts with image/, saves the file under the name the browser sent, in a folder that is also served as static files:

Bash
cat > main.py <<'PY'
from pathlib import Path

from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.staticfiles import StaticFiles


def create_app(data_dir: Path, max_bytes: int = 5_000_000) -> FastAPI:
    # max_bytes is configured, but nothing enforces it yet.
    uploads = Path(data_dir) / "public" / "uploads"
    uploads.mkdir(parents=True, exist_ok=True)
    app = FastAPI()

    @app.post("/uploads", status_code=201)
    def upload(file: UploadFile = File()):
        if not (file.content_type or "").startswith("image/"):
            raise HTTPException(415, "images only")
        (uploads / file.filename).write_bytes(file.file.read())
        return {"id": file.filename, "url": f"/files/{file.filename}"}

    app.mount("/files", StaticFiles(directory=uploads), name="files")
    return app


app = create_app(Path("data"))
PY

Each problem in that code is a rule the tests below state. Every test builds its files in memory, with Pillow for the real images, and runs against a fresh app in a temporary folder, so nothing touches your own files:

Bash
cat > tests/test_uploads.py <<'PY'
import io

import pytest
from fastapi.testclient import TestClient
from PIL import Image

from main import create_app

LIMIT = 1_000_000


@pytest.fixture
def data_dir(tmp_path):
    return tmp_path


@pytest.fixture
def client(data_dir):
    return TestClient(create_app(data_dir, max_bytes=LIMIT))


def image_bytes(fmt, **save_options):
    buf = io.BytesIO()
    Image.new("RGB", (64, 48), (40, 120, 200)).save(buf, fmt, **save_options)
    return buf.getvalue()


def upload(client, name, data, content_type):
    return client.post("/uploads", files={"file": (name, data, content_type)})


def stored_names(data_dir):
    return [p.name for p in data_dir.rglob("*") if p.is_file()]


def test_a_real_png_is_stored_and_served(client):
    r = upload(client, "cat.png", image_bytes("PNG"), "image/png")
    assert r.status_code == 201
    got = client.get(r.json()["url"])
    assert got.status_code == 200
    assert got.headers["content-type"] == "image/png"
    assert Image.open(io.BytesIO(got.content)).size == (64, 48)


def test_the_type_comes_from_the_bytes(client):
    r = upload(client, "cat.png", image_bytes("JPEG"), "image/png")
    assert r.status_code == 201
    got = client.get(r.json()["url"])
    assert got.headers["content-type"] == "image/jpeg"


def test_text_disguised_as_png_is_refused(client):
    page = b"<html><script>document.title='marker-42'</script></html>"
    r = upload(client, "cat.png", page, "image/png")
    assert r.status_code == 415


def test_svg_with_script_is_refused(client):
    svg = b'<svg xmlns="http://www.w3.org/2000/svg"><script>document.title="marker-42"</script></svg>'
    r = upload(client, "logo.svg", svg, "image/svg+xml")
    assert r.status_code == 415


def test_a_broken_image_is_refused(client):
    r = upload(client, "cat.png", b"\x89PNG\r\n\x1a\n" + b"junk" * 100, "image/png")
    assert r.status_code == 415


def test_an_oversized_upload_is_refused(client):
    r = upload(client, "big.png", b"\x89PNG\r\n\x1a\n" + b"\0" * LIMIT, "image/png")
    assert r.status_code == 413


def test_metadata_is_removed(client):
    exif = Image.Exif()
    exif[0x010F] = "marker-camera"  # the EXIF Make tag
    photo = image_bytes("JPEG", exif=exif)
    assert b"marker-camera" in photo
    r = upload(client, "photo.jpg", photo, "image/jpeg")
    assert r.status_code == 201
    assert b"marker-camera" not in client.get(r.json()["url"]).content


def test_a_path_in_the_name_stays_inside_storage(client, data_dir):
    upload(client, "../escaped.png", image_bytes("PNG"), "image/png")
    assert "escaped.png" not in stored_names(data_dir)


def test_the_stored_name_is_not_the_uploaded_name(client, data_dir):
    r = upload(client, "holiday-lagos.png", image_bytes("PNG"), "image/png")
    assert r.status_code == 201
    assert "holiday" not in r.json()["id"]
    assert not any("holiday" in name for name in stored_names(data_dir))


def test_downloads_carry_safe_headers(client):
    r = upload(client, "cat.png", image_bytes("PNG"), "image/png")
    got = client.get(r.json()["url"])
    assert got.headers.get("x-content-type-options") == "nosniff"
    assert got.headers.get("content-disposition", "").startswith("attachment")
PY

The markers (marker-42, marker-camera) are plain strings. If one survives into a stored or served file, a test fails and says which rule broke. Run the tests:

Bash
uv run pytest -q

Check it worked

The run fails, which is what you want here: the last line reads 9 failed, 1 passed. Only test_a_real_png_is_stored_and_served passes, because the happy path works, and that is why routes like this get through review. The failures list each flaw: a text file and an SVG with a script were accepted because their headers said image/, the JPEG named cat.png was served as image/png, the oversized file was kept, the camera tag came back on download, ../escaped.png was stored under the sender's own name, path and all, and the downloads have no nosniff or attachment header.

Step 3 · Limit the size at the proxy and in the app

Limit size twice. The proxy refuses a big body before your app spends memory, disk or time on it. The app enforces its own limit too, because a request can arrive by another route, and because a chunked request has no Content-Length to check in advance.

In Nginx, client_max_body_size sets the largest body it accepts; the default is 1m. Set it a little above your app limit, so the app sends its own clearer error for files just over the line, in the location block that forwards to the app:

Nginx
location /uploads {
    client_max_body_size 6m;
    proxy_pass http://127.0.0.1:8000;
}

Nginx answers 413 Request Entity Too Large above that. If your users are on slow or prepaid mobile data, as many are across Africa, also tell them the limit in the form before they pick a file, so nobody spends data uploading 12 MB only to be refused.

In the app, read the upload in chunks and stop as soon as it passes the limit. Put that in its own module:

Bash
cat > limits.py <<'PY'
CHUNK = 64 * 1024


class TooLarge(Exception):
    pass


def read_limited(fileobj, max_bytes: int) -> bytes:
    """Read at most max_bytes from fileobj, or raise TooLarge."""
    chunks, total = [], 0
    while chunk := fileobj.read(CHUNK):
        total += len(chunk)
        if total > max_bytes:
            raise TooLarge(f"more than {max_bytes} bytes")
        chunks.append(chunk)
    return b"".join(chunks)
PY

By the time your route runs, FastAPI's form parser has already received the whole body and spooled it to a temporary file, so this limit protects what you keep and process, not the network. That is why the proxy limit matters, and why the final app also refuses a declared Content-Length that is far too big before the form is parsed.

Check it worked

Bash
uv run python -c "
import io
from limits import TooLarge, read_limited
print(len(read_limited(io.BytesIO(b'x' * 100), 100)))
try:
    read_limited(io.BytesIO(b'x' * 101), 100)
except TooLarge as err:
    print('refused:', err)
"

The output is 100, then refused: more than 100 bytes.

Step 4 · Check the real type from the first bytes

The extension and Content-Type are labels the sender writes. The bytes are what the file is. Most image formats start with a fixed signature, sometimes called magic bytes: PNG begins with the eight bytes 89 50 4E 47 0D 0A 1A 0A, JPEG with FF D8 FF, and WebP with RIFF, four bytes of length, then WEBP.

Allow a short list of formats you actually need and refuse everything else. Leave SVG off the list. An SVG is an XML document, not a grid of pixels: it can hold <script> and event handlers, and if it is opened straight from your domain the script runs with your site's cookies and origin. If you must accept SVG logos, convert them to PNG on the server, or serve them only from a separate domain that holds no sessions.

Bash
cat > sniff.py <<'PY'
SIGNATURES = {
    "png": lambda head: head.startswith(b"\x89PNG\r\n\x1a\n"),
    "jpeg": lambda head: head.startswith(b"\xff\xd8\xff"),
    "webp": lambda head: head[:4] == b"RIFF" and head[8:12] == b"WEBP",
}


def sniff_type(head: bytes) -> str | None:
    """Return 'png', 'jpeg' or 'webp' from a file's first bytes, or None."""
    for kind, matches in SIGNATURES.items():
        if matches(head):
            return kind
    return None
PY

A signature match is a first filter, not proof. A file can start with a PNG signature and contain anything after it, which is what the broken-image test sends. The next step closes that gap by asking Pillow to decode the whole image.

Check it worked

Bash
uv run python -c "
from sniff import sniff_type
print(sniff_type(b'\x89PNG\r\n\x1a\n' + b'rest'))
print(sniff_type(b'RIFF\x24\x00\x00\x00WEBPVP8 '))
print(sniff_type(b'<svg xmlns=\"http://www.w3.org/2000/svg\">'))
"

The output is png, webp and None.

Step 5 · Re-encode images with Pillow

Decoding the image and saving a new one from its pixels does three jobs at once. It proves the file is a complete, readable image. It drops everything that is not pixels: EXIF data with the camera, time and GPS position, comments, colour profiles and any bytes tacked on the end. And it lets you cap the size, which saves storage and saves data for everyone who views the image later.

Bash
cat > images.py <<'PY'
import io

from PIL import Image, ImageOps

# Pillow refuses images far above this as possible decompression bombs.
Image.MAX_IMAGE_PIXELS = 40_000_000

PIL_FORMATS = {"png": "PNG", "jpeg": "JPEG", "webp": "WEBP"}


class BadImage(Exception):
    pass


def reencode(data: bytes, kind: str, max_side: int = 2048) -> bytes:
    """Decode data as the given kind and return a fresh image with no metadata."""
    fmt = PIL_FORMATS[kind]
    try:
        with Image.open(io.BytesIO(data), formats=[fmt]) as img:
            if img.width * img.height > Image.MAX_IMAGE_PIXELS:
                raise BadImage("too many pixels")
            img = ImageOps.exif_transpose(img)
            mode = "RGB" if kind == "jpeg" or "A" not in img.getbands() else "RGBA"
            pixels = img.convert(mode)
            clean = Image.frombytes(mode, pixels.size, pixels.tobytes())
    except (OSError, ValueError, Image.DecompressionBombError) as err:
        raise BadImage(str(err)) from err

    clean.thumbnail((max_side, max_side))
    out = io.BytesIO()
    options = {"quality": 85} if kind in ("jpeg", "webp") else {"optimize": True}
    clean.save(out, fmt, **options)
    return out.getvalue()
PY

The details that matter:

  • formats=[fmt] tells Pillow to try only the format the signature named, so a file cannot be sniffed as one format and decoded as another.
  • Image.open reads only the header, so the pixel count check runs before the image is decoded. A small file can declare an enormous canvas, and decoding it would eat your memory.
  • ImageOps.exif_transpose turns the pixels the way the camera's orientation tag said, before the tag is thrown away, so portrait photos stay upright.
  • Image.frombytes builds a new image from raw pixels alone. It carries none of the original's metadata, colour profile or text chunks, whatever a save option would otherwise copy across.
  • thumbnail only ever shrinks, and keeps the aspect ratio. A 4000 by 3000 photo from a phone becomes 2048 by 1536, a fraction of the bytes for a visitor on a low-end Android phone or a prepaid bundle.

Check it worked

Bash
uv run python -c "
import io
from PIL import Image
from images import BadImage, reencode
exif = Image.Exif(); exif[0x010F] = 'marker-camera'
buf = io.BytesIO(); Image.new('RGB', (4000, 3000), 'white').save(buf, 'JPEG', exif=exif)
clean = reencode(buf.getvalue(), 'jpeg')
print(b'marker-camera' in buf.getvalue(), b'marker-camera' in clean)
print(Image.open(io.BytesIO(clean)).size)
try:
    reencode(b'\x89PNG\r\n\x1a\n' + b'junk' * 100, 'png')
except BadImage:
    print('broken image refused')
"

The output is True False (the marker was in the original and is gone from the copy), then (2048, 1536), then broken image refused.

Step 6 · Store under random names and serve with safe headers

Now rebuild main.py from the three modules. Overwrite the quick version; it has done its job. The new route:

  • refuses a declared body far over the limit before the form is parsed, then reads the file with read_limited;
  • takes the type from sniff_type and the clean bytes from reencode, ignoring the sender's extension and Content-Type;
  • stores the result as <random id>.bin in data/store, a folder that is never mounted as static files, with the type and a display name in a small JSON file beside it;
  • serves files only through a route that checks the ID's shape, sets the type it recorded, and adds headers that stop the browser treating the file as anything else.
Bash
cat > main.py <<'PY'
import json
import re
import secrets
from pathlib import Path

from fastapi import FastAPI, File, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, JSONResponse

from images import BadImage, reencode
from limits import TooLarge, read_limited
from sniff import sniff_type

ID_PATTERN = re.compile(r"[A-Za-z0-9_-]{22}")
MEDIA_TYPES = {"png": "image/png", "jpeg": "image/jpeg", "webp": "image/webp"}
EXTENSIONS = {"png": "png", "jpeg": "jpg", "webp": "webp"}
SAFE_HEADERS = {
    "X-Content-Type-Options": "nosniff",
    "Content-Security-Policy": "default-src 'none'; sandbox",
    "Cache-Control": "private, max-age=3600",
}


def display_name(sent: str | None, kind: str) -> str:
    """A name for the download box only. It never becomes a path."""
    base = (sent or "").replace("\\", "/").rsplit("/", 1)[-1]
    stem = "".join(ch for ch in base.rsplit(".", 1)[0] if ch.isprintable())[:80].strip()
    return f"{stem or 'upload'}.{EXTENSIONS[kind]}"


def create_app(data_dir: Path, max_bytes: int = 5_000_000) -> FastAPI:
    store = Path(data_dir) / "store"
    store.mkdir(parents=True, exist_ok=True)
    app = FastAPI()

    @app.middleware("http")
    async def refuse_big_bodies(request: Request, call_next):
        declared = request.headers.get("content-length", "")
        if request.url.path == "/uploads" and declared.isdigit() and int(declared) > max_bytes + 65_536:
            return JSONResponse({"detail": "file too large"}, status_code=413)
        return await call_next(request)

    @app.post("/uploads", status_code=201)
    def upload(file: UploadFile = File()):
        try:
            data = read_limited(file.file, max_bytes)
        except TooLarge:
            raise HTTPException(413, "file too large")
        kind = sniff_type(data[:16])
        if kind is None:
            raise HTTPException(415, "send a PNG, JPEG or WebP image")
        try:
            clean = reencode(data, kind)
        except BadImage:
            raise HTTPException(415, "that image could not be read")

        file_id = secrets.token_urlsafe(16)
        with open(store / f"{file_id}.bin", "xb") as out:
            out.write(clean)
        meta = {"kind": kind, "name": display_name(file.filename, kind)}
        (store / f"{file_id}.json").write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
        return {"id": file_id, "url": f"/files/{file_id}"}

    @app.get("/files/{file_id}")
    def download(file_id: str):
        meta_path = store / f"{file_id}.json"
        if not ID_PATTERN.fullmatch(file_id) or not meta_path.is_file():
            raise HTTPException(404, "not found")
        meta = json.loads(meta_path.read_text(encoding="utf-8"))
        return FileResponse(
            store / f"{file_id}.bin",
            media_type=MEDIA_TYPES[meta["kind"]],
            filename=meta["name"],
            content_disposition_type="attachment",
            headers=SAFE_HEADERS,
        )

    return app


app = create_app(Path("data"))
PY

Why each piece is there:

  • Random IDs. secrets.token_urlsafe(16) gives 22 characters from 128 random bits. They cannot be guessed, so one user cannot walk through everyone's files by counting, and they contain nothing the sender chose. Opening with "xb" fails rather than overwriting if an ID ever repeated.
  • The original name is data. It goes into the JSON file, cut down to its last segment and printable characters, with the real extension. Names in Yoruba, Amharic, Arabic or Hindi stay readable: FileResponse sends non-ASCII names in the filename* form of Content-Disposition, which browsers decode correctly.
  • Outside the web root. Nothing under data/store is reachable except through /files/{id}, which checks the ID's exact shape first. In production keep the folder outside the app's code and static folders, or use a private object storage bucket that only your app can read, and serve from it through this route or short-lived signed links.
  • The headers. X-Content-Type-Options: nosniff stops the browser second-guessing the type. Content-Disposition: attachment makes a direct visit download the file instead of rendering it; <img> tags ignore that header, so images still show on your pages. The sandbox policy blocks scripts and forms if a file ever is rendered.

Run the same tests again:

Bash
uv run pytest -q

Check it worked

The run ends with 10 passed. The tests did not change; the route did. To see a rule bite, delete the line clean = reencode(data, kind) together with its try and except, set clean = data instead, and run again: test_metadata_is_removed and test_a_broken_image_is_refused fail. Put the code back before you go on.

Step 7 · Scan files where your policy requires it

Re-encoding removes anything hidden in an image, so a virus scan adds little for an images-only route. Scanning matters when you accept documents (PDF, Office files, archives) that you store as they arrive, or when a contract or regulator asks for it. ClamAV is the common open-source choice on Ubuntu. Its daemon keeps the signature database loaded, and the freshclam service updates it:

Bash
sudo apt install clamav-daemon

Call it from Python with an argument list, never a shell string. --fdpass passes the open file to the daemon, so the daemon does not need read access to your storage folder. clamdscan exits with 0 for no match, 1 when it finds a match, and 2 for an error:

Python
import subprocess


def scan_is_clean(path: str) -> bool:
    result = subprocess.run(
        ["clamdscan", "--no-summary", "--fdpass", path],
        capture_output=True,
        timeout=60,
    )
    if result.returncode == 0:
        return True
    if result.returncode == 1:
        return False
    raise RuntimeError("virus scan failed: " + result.stdout.decode(errors="replace"))

Scan the file in a quarantine folder before you move it into storage, and treat an error as a refusal, not a pass. A scanner only knows signatures it has already seen; it is one layer on top of the checks above, never a replacement for them.

Check it worked

On a server with ClamAV installed, systemctl status clamav-daemon shows the service as active (running), and clamdscan --fdpass on a file you know is harmless prints OK and exits 0. ClamAV's documentation describes the EICAR test file, a harmless string every scanner reports as a test virus, which you can use to check that the return False branch fires.

Step 8 · Clean up

Remove the demo project. Python and uv stay installed:

Bash
cd ~
rm -rf ~/uploads-demo

Check it worked

ls ~/uploads-demo prints No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.