Full answer
@app.get("/files/{file_path:path}") uses Starlette's path convertor, so /files/reports/2026/term1.pdf gives file_path = "reports/2026/term1.pdf". Without :path, the request would not match because the parameter stops at /.
The risk: code such as open(BASE / file_path) is dangerous. A request for /files/../../etc/passwd points outside BASE. Browsers and HTTP clients usually normalise literal .. segments before sending, but attackers use raw sockets or percent-encoded dots (%2e%2e/), which are decoded before they reach your function. Absolute paths are worse: Path("/srv/files") / "/etc/passwd" becomes /etc/passwd, because joining with an absolute path replaces the base.
Safe pattern:
BASE = Path("/srv/files").resolve()
target = (BASE / file_path).resolve()
if not target.is_relative_to(BASE) or not target.is_file():
raise HTTPException(404)
return FileResponse(target)resolve() collapses .. and follows symlinks, so the containment check sees the real location. Return 404 rather than 403 so attackers learn nothing about which files exist.
Other defences: serve user content from object storage with signed URLs; use StaticFiles for static directories (it normalises and rejects traversal); keep uploads outside the code tree with generated names, never user-supplied filenames; run the process with minimal filesystem permissions; and set an allow-list of extensions.
Also note that FastAPI route order matters: a catch-all /{file_path:path} declared early will swallow other routes, so declare specific routes first.
import tempfile
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
from fastapi.testclient import TestClient
BASE = Path(tempfile.mkdtemp()).resolve()
(BASE / "reports").mkdir()
(BASE / "reports" / "term1.txt").write_text("term 1 report")
SECRET = BASE.parent / "outside-secret.txt"
SECRET.write_text("not for clients")
app = FastAPI()
@app.get("/unsafe/{file_path:path}")
def unsafe(file_path: str):
return FileResponse(BASE / file_path)
@app.get("/files/{file_path:path}")
def safe(file_path: str):
target = (BASE / file_path).resolve()
if not target.is_relative_to(BASE) or not target.is_file():
raise HTTPException(status_code=404, detail="Not found")
return FileResponse(target)
c = TestClient(app)
print(c.get("/files/reports/term1.txt").text)
print(c.get(f"/unsafe/%2e%2e/{SECRET.name}").text) # encoded dots: the traversal succeeds, this is the bug
print(c.get(f"/files/%2e%2e/{SECRET.name}").status_code)
print(c.get("/files//etc/passwd").status_code, c.get("/files/missing.txt").status_code)
print(Path("/srv/files") / "/etc/passwd")
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The snippet creates a temporary directory and a file outside it to demonstrate traversal. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): term 1 report not for clients 404 404 404 /etc/passwd
Key points
- {name:path} matches slashes
- Never join user input to a base directory without checking
- resolve() then is_relative_to(BASE) blocks traversal
- Absolute paths replace the base when joined
- Declare catch-all routes last
Common mistakes
- Joining user input to a directory and opening the result
- Checking for '..' with string tests instead of resolving the path
- Trusting user-supplied filenames for uploads
- Returning 403 and revealing which paths exist
- Declaring a catch-all path route before specific routes
Follow-ups
- How does StaticFiles protect against traversal?
- How would you serve private files with expiring links?
- Why do symlinks matter in the check?
Tips
- Show the :path convertor
- Explain traversal with an example
- Show resolve plus is_relative_to