2026-10-15 23:08:47 -06:00
|
|
|
"""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
|
|
|
|
|
|
2026-10-30 17:50:05 -06:00
|
|
|
|
|
|
|
|
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'")
|
2026-10-15 23:08:47 -06:00
|
|
|
|
|
|
|
|
HEADERS: dict[str, str] = {
|
|
|
|
|
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
|
|
|
|
|
"X-Content-Type-Options": "nosniff",
|
|
|
|
|
"X-Frame-Options": "DENY",
|
2026-10-17 12:32:44 -06:00
|
|
|
# Not no-referrer: under it Firefox sends Origin: null on same-origin POSTs and the Origin check refuses them.
|
|
|
|
|
"Referrer-Policy": "same-origin",
|
2026-10-15 23:08:47 -06:00
|
|
|
"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
|
2026-10-30 17:50:05 -06:00
|
|
|
if headers.get("content-type", "").lower().startswith("application/pdf"):
|
|
|
|
|
headers["Content-Security-Policy"] = PDF_CSP
|
2026-10-15 23:08:47 -06:00
|
|
|
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,
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
)
|