askrobots / dbbasic-web
Public
A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.
Dan Quellhorst
Replace multipart parser with stdlib-only implementation
eb957a2
9 months, 2 weeks ago
History
static.py · 874 bytes · 26 lines
| 1 | """Static file serving""" |
| 2 | import mimetypes |
| 3 | from pathlib import Path |
| 4 | from .settings import PUBLIC_DIR |
| 5 | |
| 6 | |
| 7 | def serve_static(path: str): |
| 8 | """Serve a static file from the public directory""" |
| 9 | # Sanitize and resolve path |
| 10 | clean_path = path.strip("/") |
| 11 | if not clean_path: |
| 12 | return 404, [("content-type", "text/plain")], [b"Not Found"] |
| 13 | |
| 14 | candidate = (PUBLIC_DIR / clean_path).resolve() |
| 15 | |
| 16 | # Security: ensure we're still inside PUBLIC_DIR |
| 17 | if not str(candidate).startswith(str(PUBLIC_DIR)): |
| 18 | return 403, [("content-type", "text/plain")], [b"Forbidden"] |
| 19 | |
| 20 | if not candidate.exists() or not candidate.is_file(): |
| 21 | return 404, [("content-type", "text/plain")], [b"Not Found"] |
| 22 | |
| 23 | ctype, _ = mimetypes.guess_type(str(candidate)) |
| 24 | ctype = ctype or "application/octet-stream" |
| 25 | |
| 26 | return 200, [("content-type", ctype)], [candidate.read_bytes()] |