Content-Disposition Filename Parser
Extract a safe basename from Content-Disposition headers, honoring RFC 5987 encoding and rejecting traversal segments.
Code
import re
from pathlib import PurePosixPath
from urllib.parse import unquote
NAME_STAR = re.compile(r"filename\*\s*=\s*([^;]+)", re.IGNORECASE)
NAME = re.compile(r'filename\s*=\s*(?:"([^"]*)"|([^;]+))', re.IGNORECASE)
def safe_basename(value: str) -> str | None:
candidate = PurePosixPath(value.replace("\\", "/")).name.strip()
if candidate in {"", ".", ".."} or "\x00" in candidate:
return None
return candidate
def attachment_filename(header: str) -> str | None:
match = NAME_STAR.search(header)
if match:
value = match.group(1).strip().strip('"')
charset, _, remainder = value.partition("'")
_, _, encoded = remainder.partition("'")
try:
decoded = unquote(
encoded or remainder,
encoding=charset or "utf-8",
errors="strict",
)
except (LookupError, UnicodeDecodeError):
decoded = unquote(encoded or remainder)
return safe_basename(decoded)
match = NAME.search(header)
if not match:
return None
value = match.group(1) if match.group(1) is not None else match.group(2)
return safe_basename(unquote(value.strip()))
def main() -> None:
headers = [
'attachment; filename="report final.pdf"',
"attachment; filename=../../etc/passwd",
"attachment; filename*=UTF-8''%E5%B9%B4%E6%8A%A5.pdf",
'attachment; filename=".."',
]
for header in headers:
print(attachment_filename(header))
if __name__ == "__main__":
main()How it works
Content-Disposition Filename Parser keeps everything in the functions safe_basename, attachment_filename and main.
The one repetition in this snippet is the loop for header in headers. The import line is the dependency contract: PurePosixPath, unquote come from urllib and nothing else.
Points of care
- Dependency check:
urllib— not built-in, must be present in the project.
Applying it
Entry signature: def safe_basename(value: str) -> str | None
The entry point wires attachment_filename together — run it once and the whole demo flows.
Statements that matter
def safe_basename(value: str) -> str | None:
candidate = PurePosixPath(value.replace("\\", "/")).name.strip()
if candidate in {"", ".", ".."} or "\x00" in candidate:
return None
return candidate
def main() -> None:
headers = [
'attachment; filename="report final.pdf"',
"attachment; filename=../../etc/passwd",
"attachment; filename*=UTF-8''%E5%B9%B4%E6%8A%A5.pdf",
'attachment; filename=".."',
]
for header in headers:
print(attachment_filename(header))
except (LookupError, UnicodeDecodeError):
decoded = unquote(encoded or remainder)
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
FAQ
- Do I need to install anything before running this?
- Yes: `urllib` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.