Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 5 · Worked example · 25 min · revision 3

Receiving Uploads Safely

Safely handle file uploads in backend services by enforcing size limits at reverse proxy and application layers, sniffing MIME types via magic bytes, and generating collision-free storage keys.

Contentsand lesson path

What you will learn

  • Accept multipart uploads with size limits, streaming them instead of loading whole files into memory, and validate type from file content rather than the client's filename or header.

01. Context: the attack surface of file uploads

Accepting binary files from unauthenticated or untrusted users is one of the highest-risk operations a backend API can perform. When a client sends a multipart/form-data payload containing an image or document, several dangerous attack vectors threaten your systems:

  • Denial of service through unbounded payloads: Without strict streaming size limits, an attacker can stream a multi-gigabyte payload into an upload endpoint. If the framework buffers the whole body in RAM, the worker can run out of memory and be killed by the kernel's out-of-memory (OOM) killer. If it spools the body to a temporary file instead, an attacker can fill that disk. And in asyncio or Node.js, parsing a huge body in one go also blocks the event loop for every other request.
  • MIME confusion and polyglot files: Attackers rename malicious executable payloads (e.g., PHP webshells, Windows .exe files, or SVG scripts) to innocent extensions like avatar.jpg. If the server trusts the user-supplied filename or Content-Type HTTP header, it may store and subsequently execute or serve executable code to other users. Historically, naive blacklists blocking .php were easily defeated by attackers submitting .php5, .phtml, .phar, or mixed-case .pHp extensions.
  • Cross-site scripting (XSS) through SVG images: Scalable Vector Graphics (.svg) files are XML documents. When rendered directly inline by a web browser, embedded <script> tags or onload attributes execute JavaScript within the domain's security origin, resulting in session hijacking and credential theft.
  • Directory traversal through crafted filenames: If a service writes uploaded files using raw filenames like ../../etc/cron.d/malware or ../../../var/www/html/shell.php, the application risks overwriting critical operating system files or application source code.
  • Decompression bombs (zip bombs): When endpoints accept compressed archive formats (such as ZIP, GZIP, or TAR) to unpack user datasets, malicious archives containing nested high-compression ratios (e.g. 42 kilobytes expanding to 4.5 petabytes) can exhaust disk space and CPU within seconds.

A secure upload pipeline requires defence in depth: early size enforcement at the reverse proxy, a byte count on the request body before it is parsed, magic-byte MIME sniffing, filename detachment, and safe download header configuration.

02. Worked example: building a hardened FastAPI upload endpoint

Let us walk through the four essential layers of a hardened file ingestion service:

  • Layer 1, size limit at the reverse proxy: Configure Nginx or Envoy to terminate oversized connections before the byte stream reaches Python worker processes. In Nginx, client_max_body_size 10M; makes the proxy answer with status 413 (RFC 9110 calls it Content Too Large; nginx's page still says Request Entity Too Large) as soon as a declared Content-Length is over the limit, or once the body it reads passes it. Oversized uploads then stop at the edge and never use your workers' bandwidth or memory.
  • Layer 2, body limit in the application: Even with reverse proxy guards, application code must guard against rogue requests or internal bypasses. Know what UploadFile does first: before your handler runs, Starlette has already received the whole multipart body and written each file part to a temporary file (the first 1 MB in RAM, the rest on disk), with no size cap of its own. Counting bytes inside the handler therefore limits nothing; it only measures after the fact, while an attacker can fill the temp disk. The limit has to sit before parsing: BodySizeLimit below is a small ASGI middleware that rejects a declared Content-Length over the limit before reading a byte, and counts the bytes of a chunked body as they arrive, aborting with 413 past the limit.
  • Layer 3, magic-byte MIME sniffing: We extract the initial 512 bytes of the payload and evaluate its signature (magic numbers) using binary inspection. We verify that the actual bytes correspond strictly to an approved allowlist (image/jpeg, image/png, application/pdf). Checking magic bytes catches a file whose name lies, such as a shell script renamed to .png. It does not catch polyglots: files with a real JPEG or PDF header followed by HTML or script. Re-encode images (as the post-processing lesson does) and serve uploads with X-Content-Type-Options: nosniff and Content-Disposition: attachment, or from a separate sandbox domain.
  • Layer 4, key isolation and header hardening: Discard the user-provided filename completely. Generate an unpredictable UUIDv4 or ULID key for storage in object storage, and record the sanitized original name solely in the metadata database.

Register the middleware on the app with app.add_middleware(BodySizeLimit, max_bytes=MAX_BODY_BYTES) and include the router. The code below was run under uvicorn 0.54.0 with FastAPI 0.163.1, Starlette 1.10.0 and python-multipart 0.0.34: a small PNG returns 201, an HTML file named .png returns 415, and a 25 MB upload returns 413 without the handler running, both with a Content-Length header and as a chunked body (the chunked one is stopped after about 11 MB has been read). After the checks, inspect_upload rewinds the file with seek(0), so the bytes it read for sniffing are not lost when the file is sent to storage. Note that this still lands the file in a temporary file on your API server first. To stream bytes straight to object storage without that, either parse request.stream() yourself with a streaming multipart parser (python-multipart has one) and pipe validated chunks into an S3 multipart upload, or let clients upload directly with presigned URLs, as the next lesson does.

Python · app/uploads.py (body size limit, magic bytes, random key)
import uuid
from fastapi import APIRouter, File, HTTPException, UploadFile, status

router = APIRouter(prefix="/files", tags=["uploads"])

# Strict byte limit: 10 Megabytes
MAX_FILE_BYTES = 10 * 1024 * 1024
# Whole request body: the file plus a little multipart framing
MAX_BODY_BYTES = MAX_FILE_BYTES + 64 * 1024

# Magic byte signatures for authorized MIME types
MAGIC_SIGNATURES: dict[str, tuple[bytes, ...]] = {
    "image/jpeg": (b"\xff\xd8\xff",),
    "image/png": (b"\x89PNG\r\n\x1a\n",),
    "application/pdf": (b"%PDF-",),
}


class BodySizeLimit:
    """Pure ASGI middleware: refuses a body over max_bytes while it arrives."""

    def __init__(self, app, max_bytes: int):
        self.app, self.max_bytes = app, max_bytes

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            return await self.app(scope, receive, send)
        declared = dict(scope["headers"]).get(b"content-length")
        if declared is not None and int(declared) > self.max_bytes:
            # Refused before a single body byte is read
            return await self._too_large(send)
        received = 0

        async def counting_receive():
            nonlocal received
            message = await receive()
            received += len(message.get("body", b""))
            if received > self.max_bytes:  # chunked bodies have no length
                raise HTTPException(status.HTTP_413_CONTENT_TOO_LARGE,
                                    "Request body too large")
            return message

        await self.app(scope, counting_receive, send)

    async def _too_large(self, send):
        await send({"type": "http.response.start", "status": 413,
                    "headers": [(b"content-type", b"application/json"),
                                (b"connection", b"close")]})
        await send({"type": "http.response.body",
                    "body": b'{"detail":"Request body too large"}'})


def sniff_mime_type(header_bytes: bytes) -> str | None:
    for mime, signatures in MAGIC_SIGNATURES.items():
        for sig in signatures:
            if header_bytes.startswith(sig):
                return mime
    return None


async def inspect_upload(file: UploadFile) -> tuple[str, str, int]:
    # When this runs, Starlette has already received the whole file part and
    # spooled it to a temporary file (1 MB in RAM, the rest on disk).
    # BodySizeLimit is what kept that file from growing past the limit.
    size = file.size or 0
    if size == 0:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "Uploaded file is empty")
    if size > MAX_FILE_BYTES:
        raise HTTPException(status.HTTP_413_CONTENT_TOO_LARGE, "File too large")
    detected_mime = sniff_mime_type(await file.read(512))
    if not detected_mime:
        raise HTTPException(
            status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
            detail="File content signature does not match allowed types",
        )
    await file.seek(0)  # rewind, so the upload below sends the whole file
    # Discard client filename; generate random storage key
    extension = detected_mime.split("/")[-1]
    storage_key = f"uploads/{uuid.uuid4().hex}.{extension}"
    return storage_key, detected_mime, size


@router.post("", status_code=201)
async def upload_file(file: UploadFile = File(...)):
    key, mime, size = await inspect_upload(file)
    # Stream the temp file to object storage in parts, never read() it whole:
    # s3.upload_fileobj(file.file, BUCKET, key, ExtraArgs={"ContentType": mime})
    return {"key": key, "content_type": mime, "size": size}

03. Check your understanding

Practice check · 3 questions

File upload security validation check

Three questions evaluating file validation mechanics, storage key generation, and HTTP header safety.

Q1. A handler takes `file: UploadFile` and counts bytes while reading 64 KB chunks. A client posts 2 GB. When does the counting code first run?
Q2. Why does the server generate a random UUID for the storage key instead of using the client's filename?
Q3. What does `X-Content-Type-Options: nosniff` change when the browser loads an uploaded file?
Practice only: not graded, not saved, not evidence.

04. Apply it

Implement these defensive file handling controls in your API endpoints:

  • Reverse proxy limit: Set client_max_body_size 10M; in your Nginx reverse proxy configuration to reject multi-gigabyte denial-of-service attempts at the front door, and keep the BodySizeLimit middleware as the second layer. Ensure proxy buffer settings do not write temporary disk spools that fill server root partitions.
  • Magic-byte detection: Use libraries like python-magic or direct binary slicing to verify the initial 512 bytes of uploaded files against strict file format specifications. Never permit executable extensions or script formats (.sh, .exe, .php, .py, .svg, .html) in user-facing media uploads.
  • Clean filenames and isolate storage keys: Always sanitize client filenames before storing them in database columns. Strip dangerous path traversal symbols (../, /, \), non-printable ASCII control characters, and leading dots. Generate random UUIDv4 or ULID storage keys so object storage paths bear no resemblance to client filenames.
  • Safe download headers: Ensure endpoints serving uploaded assets include Content-Disposition: attachment; filename="sanitized.png" and X-Content-Type-Options: nosniff. When serving files intended for inline rendering, host them on a separate registrable domain (e.g. example-usercontent.com, not a subdomain of your app) and send Content-Security-Policy: sandbox on them. A subdomain such as user-content.example.com is not isolated: it is same-site with example.com, receives cookies scoped to .example.com, and script on it can set cookies for the parent domain (cookie tossing).
  • Check the defences with curl: Execute automated integration tests using curl to verify rejection behaviour:
    • Send a 15MB dummy file to confirm HTTP 413 Content Too Large is returned, from the proxy or from BodySizeLimit, before the handler runs.
    • Send a text file disguised as test.png with curl -F "[email protected];filename=test.png;type=image/png" and verify HTTP 415 Unsupported Media Type.
    • Send a legitimate JPEG image and verify HTTP 201 Created with a generated UUID storage key.

In the next lesson, we will explore presigned URLs, enabling clients to upload directly to S3/MinIO without routing heavy file bytes through your API server.

05. Review prompt

Outline the defence-in-depth layers required to process file uploads safely in high-concurrency backend services. Explain why client-provided Content-Type headers and file extensions cannot be trusted for authorization, how magic byte sniffing operates across the initial 512 bytes, why random UUID storage keys mitigate directory traversal and file collision attacks, and why serving media with nosniff headers from an isolated domain prevents cross-site scripting.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check