File size: 8,141 Bytes
348eedc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | """Request IDs + structured JSON access logs + security headers (CSP, frame/sniff/referrer policies, HSTS on https)."""
from __future__ import annotations
import json
import logging
import re
import secrets
import sys
import time
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
CSP_APP = ("default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; "
"font-src 'self' data:; connect-src 'self'; frame-src 'self'; frame-ancestors 'self'; object-src 'none'; "
"base-uri 'self'; form-action 'self'")
# Swagger UI (/api/docs) loads its assets from jsDelivr; relaxed only on the docs pages.
CSP_DOCS = ("default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' "
"https://cdn.jsdelivr.net; img-src 'self' data: https://fastapi.tiangolo.com; connect-src 'self'; frame-ancestors 'self'")
# Reports are generated by generate_report.py with inline styles; served sandboxed inside the app.
CSP_REPORT = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'self'; sandbox"
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
d = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created)) + "Z", "level": record.levelname,
"logger": record.name, "msg": record.getMessage()}
for k in ("request_id", "method", "path", "status", "ms", "user"):
if hasattr(record, k):
d[k] = getattr(record, k)
if record.exc_info:
d["exc"] = self.formatException(record.exc_info)[-2000:]
return json.dumps(d, default=str)
class _HideTokens(logging.Filter):
"""Personal access tokens (pwt_...) never reach a log line, whatever logged them."""
_RE = re.compile(r"pwt_[A-Za-z0-9_-]{8,}")
def filter(self, record: logging.LogRecord) -> bool:
if isinstance(record.msg, str) and "pwt_" in record.msg:
record.msg = self._RE.sub("pwt_(hidden)", record.msg)
if record.args:
args = record.args if isinstance(record.args, tuple) else (record.args,)
if any(isinstance(x, str) and "pwt_" in x for x in args):
record.args = tuple(self._RE.sub("pwt_(hidden)", x) if isinstance(x, str) else x for x in args)
return True
def setup_logging(level: str = "INFO", logfile=None) -> None:
root = logging.getLogger()
if getattr(root, "_fpt_configured", False):
return
h = logging.StreamHandler(sys.stderr)
h.setFormatter(JsonFormatter())
h.addFilter(_HideTokens())
root.handlers = [h]
if logfile:
# rotated: 10 MB per file, 5 kept (the log volume is part of the saved state on hosts without a disk)
from logging.handlers import RotatingFileHandler
fh = RotatingFileHandler(logfile, maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8")
fh.setFormatter(JsonFormatter())
fh.addFilter(_HideTokens())
root.addHandler(fh)
root.setLevel(level)
root._fpt_configured = True # type: ignore[attr-defined]
access = logging.getLogger("fpt.access")
class _TooLarge(Exception):
pass
class BodyLimit:
"""Refuses a request body over `limit` bytes with 413: at once from Content-Length, or while streaming when the sender
gives no length (chunked), so nothing buffers an endless body. Plain ASGI so it sees the raw stream. 0 = no limit."""
def __init__(self, app, limit: int):
self.app, self.limit = app, limit
async def __call__(self, scope, receive, send):
if scope["type"] != "http" or self.limit <= 0:
return await self.app(scope, receive, send)
try:
declared = int(dict(scope["headers"]).get(b"content-length") or 0)
except ValueError:
declared = 0
started, seen, exceeded = False, 0, False
def refusal() -> tuple[dict, dict]:
body = json.dumps({"detail": f"the request is larger than the {self.limit:,} bytes this server accepts", "code": "TOO_LARGE"}).encode()
return ({"type": "http.response.start", "status": 413, "headers": [
(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode()), (b"connection", b"close")]},
{"type": "http.response.body", "body": body})
async def wrapped_send(msg):
nonlocal started
if exceeded: # whatever the app made of the cut-off body (a 400 for "could not parse it") becomes the 413
if msg["type"] == "http.response.start" and not started:
started = True
for m in refusal():
await send(m)
return
started = started or msg["type"] == "http.response.start"
await send(msg)
async def wrapped_receive():
nonlocal seen, exceeded
msg = await receive()
if msg["type"] == "http.request":
seen += len(msg.get("body") or b"")
if seen > self.limit:
exceeded = True
raise _TooLarge
return msg
if declared > self.limit:
for m in refusal():
await send(m)
return
try:
await self.app(scope, wrapped_receive, wrapped_send)
except _TooLarge:
if not started:
for m in refusal():
await send(m)
class RequestContext(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
rid = request.headers.get("x-request-id", "")[:64] or secrets.token_hex(8)
request.state.request_id = rid
t0 = time.time()
resp = await call_next(request)
path = request.url.path
resp.headers["X-Request-ID"] = rid
resp.headers["X-Content-Type-Options"] = "nosniff"
resp.headers["Referrer-Policy"] = "no-referrer"
resp.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"
resp.headers["Cross-Origin-Opener-Policy"] = "same-origin"
if "/report/" in path and path.endswith(("/html", "/bundle")):
resp.headers["Content-Security-Policy"] = CSP_REPORT
resp.headers["X-Frame-Options"] = "SAMEORIGIN"
elif path.startswith("/api/docs") or path.startswith("/api/redoc"):
resp.headers["Content-Security-Policy"] = CSP_DOCS
resp.headers["X-Frame-Options"] = "DENY"
else:
resp.headers.setdefault("Content-Security-Policy", CSP_APP)
resp.headers.setdefault("X-Frame-Options", "SAMEORIGIN")
svc = getattr(request.app.state, "svc", None)
embed = svc.cfg.embed_origin if svc is not None else ""
if embed and not path.startswith(("/api/docs", "/api/redoc")):
# shown inside the configured site's page: that site joins the allowed frame ancestors
resp.headers["Content-Security-Policy"] = resp.headers["Content-Security-Policy"].replace(
"frame-ancestors 'self'", f"frame-ancestors 'self' {embed}")
del resp.headers["X-Frame-Options"]
# https as the browser sees it: directly, or through a trusted proxy (FPT_TRUST_PROXY), or a server that always
# uses secure cookies (FPT_COOKIE_SECURE=always, which only makes sense behind https)
if request.url.scheme == "https" or (svc is not None and svc.cfg.cookie_secure == "always"):
resp.headers["Strict-Transport-Security"] = "max-age=31536000"
if path.startswith("/api/"):
resp.headers.setdefault("Cache-Control", "no-store")
user = getattr(getattr(request.state, "user", None), "username", None)
if not path.endswith("/stream"):
access.info("request", extra={"request_id": rid, "method": request.method, "path": path,
"status": resp.status_code, "ms": int((time.time() - t0) * 1000), "user": user})
return resp
|