Files
PacketStation/server/packetstation/security.py
T
spencermandClaude Opus 5.5 6e820ba0a5 Version banner, File locations section, final CSP (no unsafe-inline styles, frame-src none, object-src none)
The MTR viewer draws PDFs with pdf.js instead of an iframe the server's frame-ancestors refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 17:50:05 -06:00

118 lines
4.3 KiB
Python

"""Security headers, CSP and the JSON request log."""
from __future__ import annotations
import logging
import time
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
def _policy(object_src: str) -> str:
return "; ".join(
[
"default-src 'self'",
# The built bundle only: Vite emits no inline script, and pdf.js 6 needs no eval (wasm stays off).
"script-src 'self'",
# No 'unsafe-inline'. React style props and pdf.js set CSSOM properties, which CSP allows. The print
# rules live in theme.css; pdf.js adds fonts through the FontFace API, not a <style> element.
"style-src 'self'",
# blob: for the page images printPdf.ts draws before it opens the print dialog. No data: images.
"img-src 'self' blob:",
"font-src 'self'",
"connect-src 'self'",
# The pdf.js worker is a same-origin file from the build, so it needs no blob: wrapper.
"worker-src 'self'",
# No frames: PDFs draw on a canvas through pdf.js, and "Open in new tab" is a top-level page.
"frame-src 'none'",
f"object-src {object_src}",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
]
)
CSP = _policy("'none'")
# A PDF opened in its own tab is a plugin document: Chrome checks the PDF's own URL against object-src, so 'none'
# would leave the tab blank. The PDF runs none of our script, so 'self' there costs nothing.
PDF_CSP = _policy("'self'")
HEADERS: dict[str, str] = {
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
# Not no-referrer: under it Firefox sends Origin: null on same-origin POSTs and the Origin check refuses them.
"Referrer-Policy": "same-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
"Cross-Origin-Opener-Policy": "same-origin",
"Content-Security-Policy": CSP,
}
access_log = logging.getLogger("packetstation.access")
class SecurityHeadersMiddleware:
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
is_api = scope.get("path", "").startswith("/api")
async def wrapped(message: Message) -> None:
if message["type"] == "http.response.start":
headers = MutableHeaders(scope=message)
for k, v in HEADERS.items():
headers[k] = v
if headers.get("content-type", "").lower().startswith("application/pdf"):
headers["Content-Security-Policy"] = PDF_CSP
if is_api:
headers["Cache-Control"] = "no-store"
await send(message)
await self.app(scope, receive, wrapped)
class RequestLogMiddleware:
"""One JSON line per request: method, path, status, ms, ip, build. Never bodies or query strings."""
def __init__(self, app: ASGIApp, build: str):
self.app = app
self.build = build
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
start = time.perf_counter()
status = 500
async def wrapped(message: Message) -> None:
nonlocal status
if message["type"] == "http.response.start":
status = message["status"]
await send(message)
try:
await self.app(scope, receive, wrapped)
finally:
client = scope.get("client")
access_log.info(
"request",
extra={
"ps": {
"method": scope.get("method"),
"path": scope.get("path"),
"status": status,
"ms": round((time.perf_counter() - start) * 1000, 1),
"ip": client[0] if client else None,
"build": self.build,
}
},
)