Skip to content

Static Server

WSGI-compatible middleware for serving static files with full caching support.

  • 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)
)

The middleware resolves all requested paths through _is_safe_path():

  1. Leading slashes are stripped
  2. .. segments cause immediate rejection
  3. The resolved path must be under root_dir
  4. Only regular files are served (directories fall through to the app)
PathReason
../etc/passwdContains ..
sub/../../secretContains ..
/etc/passwdAbsolute path
sub/other_dir/fileOutside root

ETag is SHA-256 of size-mtime_ns (first 16 hex chars):

ETag: "a1b2c3d4e5f6g7h8"

Derived from file st_mtime, formatted as RFC 7231:

Last-Modified: Sat, 20 Jun 2026 12:00:00 GMT
Request → Check If-None-Match (ETag) → 304 if match
→ Check If-Modified-Since → 304 if not modified
→ 200 OK + full content + headers

Uses mimetypes.MimeTypes with additional types:

ExtensionMIME Type
.jsapplication/javascript
.jsonapplication/json
.svgimage/svg+xml
.mdtext/markdown
.csstext/css
.htmltext/html
.*application/octet-stream
Terminal window
# Unit tests
python3 -m pytest tools/test_static_server.py -v
# Property-based tests
python3 -m pytest tools/test_static_server_properties.py -v
# All tests
python3 -m pytest tools/test_static_server.py tools/test_static_server_properties.py -v
Terminal window
# Start demo server
python3 tools/serve_demo.py
# In another terminal:
curl -i http://localhost:8000/static/index.html
curl -i http://localhost:8000/
curl -i http://localhost:8000/static/../etc/passwd # Falls through to app
  • tools/static_server.py — Middleware implementation
  • tools/test_static_server.py — Unit tests (12 tests)
  • tools/test_static_server_properties.py — Hypothesis property tests
  • tools/serve_demo.py — Demo WSGI server