Static Server
Static File Serving Middleware
Section titled “Static File Serving Middleware”WSGI-compatible middleware for serving static files with full caching support.
Features
Section titled “Features”- Path traversal protection — Rejects
../sequences and absolute paths - ETag + If-None-Match — 304 Not Modified responses
- Last-Modified + If-Modified-Since — 304 Not Modified responses
- Content-Type detection — MIME type inference for common extensions
- Cache-Control headers — Configurable
max-age - WSGI-compatible — Works with
wsgiref, Gunicorn, uWSGI, etc.
from tools.static_server import StaticMiddleware
def app(environ, start_response): start_response("200 OK", [("Content-Type", "text/plain")]) return [b"hello"]
wrapped = StaticMiddleware( app, root_dir="public", # Directory to serve from url_prefix="/static", # URL prefix to intercept max_age=3600, # Cache-Control max-age (seconds))Path Security Model
Section titled “Path Security Model”The middleware resolves all requested paths through _is_safe_path():
- Leading slashes are stripped
..segments cause immediate rejection- The resolved path must be under
root_dir - Only regular files are served (directories fall through to the app)
Rejected Patterns
Section titled “Rejected Patterns”| Path | Reason |
|---|---|
../etc/passwd | Contains .. |
sub/../../secret | Contains .. |
/etc/passwd | Absolute path |
sub/other_dir/file | Outside root |
Caching Strategy
Section titled “Caching Strategy”ETag (If-None-Match)
Section titled “ETag (If-None-Match)”ETag is SHA-256 of size-mtime_ns (first 16 hex chars):
ETag: "a1b2c3d4e5f6g7h8"Last-Modified
Section titled “Last-Modified”Derived from file st_mtime, formatted as RFC 7231:
Last-Modified: Sat, 20 Jun 2026 12:00:00 GMTCache Flow
Section titled “Cache Flow”Request → Check If-None-Match (ETag) → 304 if match → Check If-Modified-Since → 304 if not modified → 200 OK + full content + headersContent-Type Detection
Section titled “Content-Type Detection”Uses mimetypes.MimeTypes with additional types:
| Extension | MIME Type |
|---|---|
.js | application/javascript |
.json | application/json |
.svg | image/svg+xml |
.md | text/markdown |
.css | text/css |
.html | text/html |
.* | application/octet-stream |
Running Tests
Section titled “Running Tests”# Unit testspython3 -m pytest tools/test_static_server.py -v
# Property-based testspython3 -m pytest tools/test_static_server_properties.py -v
# All testspython3 -m pytest tools/test_static_server.py tools/test_static_server_properties.py -vDemo Server
Section titled “Demo Server”# Start demo serverpython3 tools/serve_demo.py
# In another terminal:curl -i http://localhost:8000/static/index.htmlcurl -i http://localhost:8000/curl -i http://localhost:8000/static/../etc/passwd # Falls through to apptools/static_server.py— Middleware implementationtools/test_static_server.py— Unit tests (12 tests)tools/test_static_server_properties.py— Hypothesis property teststools/serve_demo.py— Demo WSGI server