Sanitize Uploaded Filenames

Turn untrusted filenames into safe basenames by stripping paths, blocking reserved names, normalizing Unicode, and limiting length.

PythonSecurity Boundaries

Code

pythonsnippet
86 lines
from __future__ import annotations

import re
import unicodedata

_INVALID = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
_WHITESPACE = re.compile(r"\s+")
_RESERVED = {
    "CON",
    "PRN",
    "AUX",
    "NUL",
    *(f"COM{index}" for index in range(1, 10)),
    *(f"LPT{index}" for index in range(1, 10)),
}


def safe_filename(
    name: str,
    *,
    max_length: int = 120,
    fallback: str = "file",
) -> str:
    if not isinstance(name, str):
        raise TypeError("name must be a string")
    if (
        not isinstance(max_length, int)
        or isinstance(max_length, bool)
        or not 8 <= max_length <= 255
    ):
        raise ValueError("max_length must be between 8 and 255")
    if not isinstance(fallback, str) or not fallback:
        raise ValueError("fallback must be a non-empty string")

    normalized = unicodedata.normalize("NFKC", name)
    normalized = normalized.replace("\\", "/").rsplit("/", 1)[-1]
    normalized = "".join(
        character
        for character in normalized
        if unicodedata.category(character)[0] != "C"
    )
    base = _INVALID.sub("_", normalized)
    base = _WHITESPACE.sub(" ", base).strip(" .")
    if not base:
        return fallback[:max_length]

    stem = base.split(".", 1)[0].strip().upper()
    if stem in _RESERVED:
        base = f"_{base}"

    if len(base) > max_length:
        head, dot, suffix = base.rpartition(".")
        candidate = (
            f".{suffix}"
            if dot
            and 0 < len(suffix) <= 16
            and suffix.isalnum()
            else ""
        )
        keep = max(1, max_length - len(candidate))
        base = f"{head[:keep].rstrip(' .')}{candidate}"

    return base or fallback[:max_length]


def main() -> None:
    samples = [
        "../../etc/passwd",
        "C:\\Windows\\System32\\cmd.exe",
        "CON.txt",
        "  ..hidden..  ",
        "résumé 2026.pdf",
        "a" * 200 + ".tar.gz",
        "report\x00final.pdf",
    ]
    for sample in samples:
        print(repr(sample), "->", safe_filename(sample))

    try:
        safe_filename("ok.txt", max_length=2)
    except ValueError as error:
        print(error)


if __name__ == "__main__":
    main()

How the snippet works

The working surface is the functions safe_filename and main — everything else is wiring.

The one repetition in this snippet is the loop for character in normalized. From __future__ it pulls annotations — the imports name exactly which library surface the snippet touches. The failure path is explicit — TypeError and ValueError is raised when the guard condition holds.

Watch out for

  • Dependency check: __future__ and unicodedata — not built-in, must be present in the project.
  • The guard not isinstance(name, str) short-circuits the flow with an early raise when its condition holds.

Applying it

Entry signature: def safe_filename( name: str, *, max_length: int = 120, fallback: str = "file", ) -> str

main is the driver: it invokes safe_filename before returning.

Statements that matter

except ValueError as error:
    print(error)
def safe_filename(
name: str,
*,
max_length: int = 120,
fallback: str = "file",
) -> str:

Interactive Tools for This Topic

FAQ

How does the snippet fail?
It throws `TypeError` and `ValueError` before any real work runs, via the guard `not isinstance(name, str)` — handle it at the call site or let it propagate deliberately.
Does this require external packages?
Yes — `__future__` and `unicodedata`. Add them to your project before running the snippet.