Recipe 8.4 · Python
Validating Uploaded Files
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
A user uploads a file, and the code checks that the name ends in .pdf. That check says nothing about the content. A renamed executable passes, and so does a 2 GB file that fills the disk. The original file name is then used to save the file, which brings its own trouble: names with ..\, reserved device names, or a name that overwrites another user's upload.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
The extension is the only check, the size limit is whatever the web server allows, and the client-supplied name decides where the bytes land on disk, inside the web root.
Requirements: Python 3.12+. Install: pip install fastapi
"""Upload handler that trusts the extension and client file name
Source: ImproveCode, Chapter 8, Recipe 8.4 "Validating Uploaded Files"
Section: The way it's often written
Book page: 173 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
The Web Forms FileUpload control becomes a FastAPI UploadFile; Server.MapPath a fixed folder.
"""
import os
import shutil
from fastapi import UploadFile
UPLOADS = "uploads/"
def btn_upload_click(fu: UploadFile) -> None:
ext = os.path.splitext(fu.filename or "")[1].lower()
if ext == ".pdf" or ext == ".jpg" or ext == ".xls":
with open(UPLOADS + (fu.filename or ""), "wb") as out:
shutil.copyfileobj(fu.file, out)
The improved recipe
The validator below checks four things: the extension is on an allow-list, the size is within a limit, the first bytes match the file type's signature, and the stored name is generated by the server. It works on a Stream and a name, so it has no dependency on ASP.NET Core and is easy to test.
A usage snippet for an ASP.NET Core minimal API endpoint, not a complete program:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Upload validator checking extension, size and magic-byte signatures
Source: ImproveCode, Chapter 8, Recipe 8.4 "Validating Uploaded Files"
Section: The improved recipe
Book page: 174-176 -- original C# listing
Converted from C# to Python.
Works on a binary file-like object (io.BufferedIOBase); the async read runs via
asyncio.to_thread. uuid4().hex replaces Guid "N".
"""
import asyncio
import os
import uuid
from collections.abc import Iterable
from dataclasses import dataclass
from typing import BinaryIO
@dataclass(frozen=True)
class UploadCheck:
is_valid: bool
error: str | None
stored_file_name: str | None
@staticmethod
def fail(error: str) -> "UploadCheck":
return UploadCheck(False, error, None)
class UploadValidator:
_TEXT_SAMPLE_BYTES = 8192
# Leading "magic" bytes per extension. Empty means text.
_SIGNATURES: dict[str, list[bytes]] = {
".pdf": [bytes([0x25, 0x50, 0x44, 0x46, 0x2D])],
".png": [bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])],
".jpg": [bytes([0xFF, 0xD8, 0xFF])],
".jpeg": [bytes([0xFF, 0xD8, 0xFF])],
".xlsx": [bytes([0x50, 0x4B, 0x03, 0x04])],
".docx": [bytes([0x50, 0x4B, 0x03, 0x04])],
".csv": [],
".txt": [],
}
def __init__(self, max_bytes: int, allowed_extensions: Iterable[str]) -> None:
if max_bytes <= 0:
raise ValueError("max_bytes must be greater than zero.")
if allowed_extensions is None:
raise TypeError("allowed_extensions must not be None.")
self._max_bytes = max_bytes
self._allowed = {e.lower() for e in allowed_extensions}
unknown = [e for e in self._allowed if e not in self._SIGNATURES]
if unknown:
raise ValueError("No signature known for: " + ", ".join(unknown))
async def validate_async(self, client_file_name: str | None,
content: BinaryIO) -> UploadCheck:
if content is None:
raise TypeError("content must not be None.")
ext = os.path.splitext(client_file_name or "")[1]
if len(ext) == 0 or ext.lower() not in self._allowed:
return UploadCheck.fail("This file type is not allowed.")
seekable = content.seekable()
length = _stream_length(content) if seekable else None
if length is not None and length > self._max_bytes:
return UploadCheck.fail("The file is too large.")
if length is not None and length == 0:
return UploadCheck.fail("The file is empty.")
sample = await asyncio.to_thread(_read_at_least, content,
self._TEXT_SAMPLE_BYTES)
if seekable:
content.seek(0)
if not self._matches_type(ext, sample):
return UploadCheck.fail("The file content does not match its type.")
stored = f"{uuid.uuid4().hex}{ext.lower()}"
return UploadCheck(True, None, stored)
@classmethod
def _matches_type(cls, ext: str, head: bytes) -> bool:
signatures = cls._SIGNATURES[ext.lower()]
if not signatures:
# Text: non-empty, and no NUL bytes in the sample.
return len(head) > 0 and b"\x00" not in head
return any(head.startswith(sig) for sig in signatures)
def _stream_length(stream: BinaryIO) -> int:
pos = stream.tell()
end = stream.seek(0, os.SEEK_END)
stream.seek(pos)
return end
def _read_at_least(stream: BinaryIO, size: int) -> bytes:
buf = bytearray()
while len(buf) < size:
chunk = stream.read(size - len(buf))
if not chunk:
break
buf.extend(chunk)
return bytes(buf)
Requirements: Python 3.12+. Install: pip install fastapi
"""Upload endpoint that validates the file before saving
Source: ImproveCode, Chapter 8, Recipe 8.4 "Validating Uploaded Files"
Section: The improved recipe
Book page: 176 -- original C# listing
Converted from C# to Python.
ASP.NET Core minimal API (MapPost, IFormFile, Results) becomes a FastAPI route
with UploadFile and Depends; FastAPI has no antiforgery middleware to disable.
"""
from fastapi import Depends, FastAPI, HTTPException, UploadFile
from p174_r8_4_upload_validator_magic_bytes import UploadValidator
app = FastAPI()
_validator = UploadValidator(10 * 1024 * 1024, [".pdf", ".png", ".jpg"])
def get_upload_validator() -> UploadValidator:
return _validator
@app.post("/documents")
async def upload_document(
file: UploadFile,
validator: UploadValidator = Depends(get_upload_validator)) -> str | None:
stream = file.file
try:
check = await validator.validate_async(file.filename, stream)
if not check.is_valid:
raise HTTPException(status_code=400, detail=check.error)
# Save under check.stored_file_name (see Recipe 10.1).
return check.stored_file_name
finally:
await file.close()
How it works
The extension check is an allow-list, never a deny-list. The constructor refuses any extension it has no signature for, so nobody can add .exe to configuration and have it pass silently.
The size check uses Stream.Length when the stream can seek, which is true for IFormFile.OpenReadStream(). Keep the server-side request limit as well (FormOptions.MultipartBodyLengthLimit and Kestrel's MaxRequestBodySize), because by the time your code runs, the body has been buffered.
The signature check reads up to 8 KB with ReadAtLeastAsync, which, unlike a single ReadAsync, keeps reading until it has the bytes or reaches the end. Binary types must start with their known magic bytes: %PDF- for PDF, the eight-byte PNG header, FF D8 FF for JPEG, and PK plus two bytes for the zip container that .xlsx and .docx use. Text types must not contain a zero byte in the sample, which rejects most binaries renamed to .csv.
The stored name is a new GUID plus the lowercased extension. The client's file name is kept only as display data, stored in your database next to the GUID. That single decision removes a whole class of overwrite and traversal bugs.
Variations and pitfalls
- Signatures are a filter, not a guarantee. Every
.xlsxstarts withPK, and so does every zip file. If you go on to open the file, use a library that fails cleanly on malformed input (Recipe 11.3 covers importing Excel safely), and scan uploads with your antivirus product when the risk warrants it. - Store outside the web root. Save uploads to a folder or blob container the web server does not serve directly, and stream them back through an endpoint that sets
Content-Disposition: attachment. - Path checks belong with path code. If you must combine a user-influenced name with a folder, use the safe path recipe in Chapter 10, Recipe 10.1, which rejects traversal outright.
- Images can carry surprises. If you display user images, consider re-encoding them with an image library. That strips metadata, including GPS coordinates from phone photos.
- Don't trust
ContentType. The browser sets it from the extension. It is a hint for display, not evidence.