Coverage for app / util / http_headers.py: 100%
14 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""Response headers for files a person put into the platform.
3A stored document is the person's bytes, not ours: it is served so a browser
4neither runs it on our origin nor sniffs it into something it was not
5(``UNTRUSTED_CONTENT_HEADERS``), and its name — anything an upload carried —
6goes into ``Content-Disposition`` escaped (``content_disposition``). Every
7download used to write ``filename="{name}"`` as it came, so a quote ended the
8value early and a line break started a header of the name's choosing.
9"""
11from __future__ import annotations
13import re
14from typing import Literal
15from urllib.parse import quote
17#: Served with every stored document. An uploaded .html or .svg — or a
18#: website snapshot — rendered inline would run its scripts as the viewer;
19#: ``sandbox`` gives it an opaque origin with scripts off, and ``nosniff``
20#: stops a mislabelled file being promoted to something executable.
21UNTRUSTED_CONTENT_HEADERS = {
22 "Content-Security-Policy": "sandbox",
23 "X-Content-Type-Options": "nosniff",
24}
26#: What an ASCII fallback name may not hold: anything outside printable
27#: ASCII, quotes and backslashes (they end or escape the quoted value), and
28#: path separators.
29_NOT_FALLBACK_SAFE = re.compile(r'[^\x20-\x7e]|["\\/]')
30#: Control characters, which no form of the name may carry.
31_CONTROL = re.compile(r"[\x00-\x1f\x7f]")
34def content_disposition(
35 name: str, disposition: Literal["attachment", "inline"] = "attachment"
36) -> str:
37 """``Content-Disposition`` naming ``name`` (RFC 6266): an ASCII
38 ``filename`` every client reads, and the exact name, UTF-8 and
39 percent-encoded, as ``filename*`` for those that read it."""
40 cleaned = _CONTROL.sub("", name or "").replace("/", "_").replace("\\", "_").strip()
41 fallback = _NOT_FALLBACK_SAFE.sub("_", cleaned).strip(" .") or "download"
42 value = f'{disposition}; filename="{fallback}"'
43 if cleaned and cleaned != fallback:
44 value += f"; filename*=UTF-8''{quote(cleaned, safe='')}"
45 return value