Practical technical guides

Download Filenames From User Input: Build Content-Disposition Safely

Measured in Chrome 158 and Python 3.13: header splitting, filename versus filename*, double extensions and a tested header builder.

By Sandeep Belgavi · Published 2026-12-05

Flow from Reject control characters, to Sanitize one display name, to Send filename and filename*.
Original conceptual diagram by Sandeep Belgavi.

A download name is untrusted input in a header

The help desk at Belgavi's Book Store lets customers attach files to a case, and agents download them later. The download endpoint names the file after what the customer uploaded: Content-Disposition: attachment; filename="<original name>". That single line puts customer-controlled text into an HTTP response header, and then into a browser that turns it into a path on an agent's disk.

Three things can go wrong. The header can be split, because a name containing a carriage return and line feed ends the header and starts a new one. The name can be misread, because quoting, non-ASCII characters and the two filename parameters each have rules that servers and browsers apply differently. And the saved file can be different from what the agent expects: a double extension, a hidden dot file or a name that is reserved on Windows.

The fix is not a cleverer escaping function. It is to treat the download name as a display value derived from stored metadata, build the header in one small, tested function and never let raw input reach the header writer.

What the specifications say

RFC 6266 defines the Content-Disposition response header: a disposition type, inline or attachment, and parameters. The filename parameter is a token or a quoted string. RFC 6266 also allows filename*, whose value uses the RFC 8187 encoding: a charset, an empty language tag and percent-encoded bytes, for example filename*=UTF-8''G%C3%A9etha%20return.pdf. When both are present, recipients that understand filename* are told to prefer it. That gives one well-defined way to carry any Unicode name, plus an ASCII fallback for older clients.

RFC 6266 also says recipients should not trust the name: they should strip path information, avoid special device names and not let the server pick a location. RFC 9110 sets the boundary for the header itself: a field value cannot contain CR, LF or NUL, and a recipient that sees them must reject the message or replace them.

Measured: what Chrome saves

I served eighteen synthetic responses to headless Chrome 158.0.8127.107 through Playwright 1.65.2 on Windows 11 and recorded the suggested download filename for each header. The suggested name is what Chrome proposes before the operating system and the download settings apply further limits. The probe script and its JSON output are in the companion example.

Header valueSuggested filename
filename="CASE-4107-return.pdf"CASE-4107-return.pdf
filename="return.pdf"; filename*=UTF-8''G%C3%A9etha%20return.pdfGéetha return.pdf
filename="Géetha return.pdf" (raw UTF-8)Géetha return.pdf
filename="G%C3%A9etha.pdf" (no star)Géetha.pdf
filename="../../etc/report.pdf"_.._etc_report.pdf
filename="..\..\Windows\report.pdf"Windowsreport.pdf
filename="Jenya\"s list.pdf"Jenya_s list.pdf
filename="invoice.pdf.exe"invoice.pdf.exe
filename=".bashrc"bashrc
filename="CON.txt"_CON.txt
filename="report.pdf. "report.pdf__

Chrome is defensive. It removed path components, prefixed a reserved device name, dropped a leading dot and replaced characters that Windows does not allow. Two results deserve attention. First, Chrome percent-decoded a plain filename value, which RFC 6266 does not ask for; another client may show G%C3%A9etha.pdf. Second, the backslashes appear to have been treated as quoted-string escapes before path handling ran, so the name lost its separators rather than having them replaced. A server cannot rely on any of this: the double extension passed through unchanged, and other clients, download managers and server-side consumers of the same header behave differently.

Measured: what the server writes

On the server side I tested three Python 3.13.5 standard library paths with a name containing CR LF.

  • http.server.BaseHTTPRequestHandler.send_header wrote the value verbatim, so the response contained a second header line, Set-Cookie: session=forged.
  • wsgiref.headers.Headers.add_header escaped the embedded quote but also passed CR LF through.
  • http.client rejected the same value with ValueError: Invalid header value, but that check runs on the client side, which does not protect a server.

Frameworks and servers often add their own checks, but whether yours does is a property of the version you run, so test it. A second mismatch showed up in parsing: Python's email package, given a header with both parameters, returned return.pdf from get_filename(), while Chrome showed the filename* value. Any server code that parses these headers, for example in multipart uploads, can disagree with the browser about which name a file has.

A header builder that cannot be confused

The builder below takes the stored display name, derives a safe ASCII fallback and an RFC 8187 value, and refuses control characters instead of trying to repair them.

import re, unicodedata, urllib.parse

WINDOWS_RESERVED = {"CON", "PRN", "AUX", "NUL", *(f"COM{i}" for i in range(1, 10)), *(f"LPT{i}" for i in range(1, 10))}

def safe_name(name, max_len=120):
    name = unicodedata.normalize("NFC", name)
    if any(unicodedata.category(c) in ("Cc", "Cf") for c in name):
        raise ValueError("control or format character in filename")
    name = re.sub(r'[\\/:*?"<>|]', "_", name).strip(" .")
    stem, dot, ext = name.rpartition(".")
    if not dot:
        stem, ext = name, ""
    if stem.split(".")[0].upper() in WINDOWS_RESERVED:
        stem = "_" + stem
    stem = stem.replace(".", "_")  # one extension only
    return (stem[: max_len - len(ext) - 1] or "download") + (dot + ext if ext else "")

def content_disposition(display_name, disposition="attachment"):
    name = safe_name(display_name)
    ascii_name = name.encode("ascii", "replace").decode().replace("?", "_")
    star = urllib.parse.quote(name, safe="")
    return f'{disposition}; filename="{ascii_name}"; filename*=UTF-8\'\'{star}'

Rejecting a control character is a design choice. Since names are stored at upload time, the cleanest place to reject is the upload endpoint, with the header builder enforcing the same rule as a backstop. The builder also collapses inner dots, so invoice.pdf.exe becomes invoice_pdf.exe. The real extension stays visible, and the name no longer pretends to be a PDF.

A worked example

Tanishka uploads three files to case CASE-4107. The upload endpoint stores the bytes under a random object key and keeps the original name only as metadata. When Geetha downloads them from the agent console:

  1. Géetha return.pdf becomes filename="G_etha return.pdf"; filename*=UTF-8''G%C3%A9etha%20return.pdf. Chrome shows the accented name; an ASCII-only client gets a readable fallback.
  2. invoice.pdf.exe becomes invoice_pdf.exe. The executable extension is the one the operating system will use, and the console can warn before downloading it.
  3. report.pdf followed by CR LF and a Set-Cookie line is rejected at upload, so it never reaches the header. If an older record still holds it, the builder raises instead of emitting a split header, and the endpoint returns an error that is logged with the case identifier.

The companion example runs these names and other fixtures through the builder, asserts the output for each, and keeps both probe scripts with their recorded output.

Tradeoffs

Always sending both parameters costs a few bytes and gives every client a usable name. Sending only filename* is cleaner, but older or minimal clients will fall back to the URL path. Replacing characters loses information; storing the original name separately keeps it for display in the console while the header carries the safe version. Rejecting control characters may refuse an upload that some client produced innocently; in a help desk that is a better outcome than storing a name that can split a header later. Collapsing inner dots changes names such as v1.2.notes.txt, which some users will notice.

Failure modes

Header splitting. CR or LF in a value written by a server API that does not validate. The second line can set cookies or alter caching.

Two names for one file. filename and filename* disagree, and different consumers pick different ones. Always generate both from the same sanitized value.

Double extensions. invoice.pdf.exe passes through the browser unchanged.

Path components. Browsers strip them, but server-side tools that save attachments by name may not.

Encoding guesses. Raw UTF-8 or percent-escapes inside plain filename work in Chrome and can appear garbled elsewhere.

Using the name as a storage key. If the upload path writes to disk under the customer's name, the download header is the smaller problem.

When this is unnecessary

If the server chooses every name, such as CASE-4107-export.csv built from identifiers, a fixed template is enough and the builder is overkill. If files are only shown inline in the browser and never downloaded, omit the filename. If a storage service generates signed URLs and sets the header itself, test that service's encoding of the stored name instead of writing your own.

Verification

  • Unit tests on the builder with CR, LF, NUL, tab, quotes, backslashes, reserved names, trailing dots and spaces, double extensions and non-ASCII names.
  • A response test that writes the header through your actual server stack and asserts the raw bytes contain exactly one Content-Disposition line.
  • A browser test that downloads each fixture name and checks the suggested filename, rerun when the browser version changes.
  • A parsing test for any server code that reads these headers, with both parameters present.
  • A data check for stored names that the current rules would reject.

Primary references and authorship

Sources read December 5, 2026. Original explanations, measurements and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/content_disposition_builder. Views are my own and do not represent any employer, past or present.