from starlette.datastructures import Headers from starlette.responses import JSONResponse from starlette.types import ASGIApp, Message, Receive, Scope, Send SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"}) class OriginCheckMiddleware: """Reject state-changing requests whose Origin header is not an allowed origin. Browsers always send Origin on cross-site POST/PUT/PATCH/DELETE. Requests without the header come from non-browser clients and are left to the authentication layer. """ def __init__(self, app: ASGIApp, allowed_origins: list[str]) -> None: self.app = app self.allowed_origins = frozenset(allowed_origins) async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] == "http" and scope["method"] not in SAFE_METHODS: origin = Headers(scope=scope).get("origin") if origin is not None and origin.rstrip("/") not in self.allowed_origins: response = JSONResponse({"detail": "Ungültige Herkunft (Origin)."}, 403) await response(scope, receive, send) return await self.app(scope, receive, send) def build_csp(allowed_origins: list[str]) -> str: # Older Safari does not match ws/wss against 'self', so list the socket origins explicitly ws_origins = [ o.replace("https://", "wss://", 1) for o in allowed_origins if o.startswith("https://") ] return "; ".join( [ "default-src 'self'", "script-src 'self'", "style-src 'self'", "img-src 'self' data:", " ".join(["connect-src 'self'", *ws_origins]), "frame-ancestors 'none'", "base-uri 'self'", "form-action 'self'", ] ) SECURITY_HEADERS = [ (b"x-content-type-options", b"nosniff"), (b"referrer-policy", b"same-origin"), (b"x-frame-options", b"DENY"), (b"permissions-policy", b"camera=(), microphone=(), geolocation=(), payment=()"), ] # No includeSubDomains: other subdomains of the domain are not under our control HSTS_HEADER = (b"strict-transport-security", b"max-age=31536000") class SecurityHeadersMiddleware: """Add security headers to every HTTP response; HSTS only for HTTPS requests.""" def __init__(self, app: ASGIApp, allowed_origins: list[str]) -> None: self.app = app self.csp_header = (b"content-security-policy", build_csp(allowed_origins).encode()) async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http": await self.app(scope, receive, send) return extra = [self.csp_header, *SECURITY_HEADERS] if scope.get("scheme") == "https": extra.append(HSTS_HEADER) async def send_with_headers(message: Message) -> None: if message["type"] == "http.response.start": existing = {name.lower() for name, _ in message.get("headers", [])} headers = list(message.get("headers", [])) headers.extend((n, v) for n, v in extra if n not in existing) message["headers"] = headers await send(message) await self.app(scope, receive, send_with_headers) class BodySizeLimitMiddleware: """Reject API request bodies above a size limit with 413. Checks Content-Length up front and counts streamed bytes for chunked requests. When a stream exceeds the limit, the 413 is sent here and the app sees a disconnect. """ def __init__(self, app: ASGIApp, max_bytes: int, path_prefix: str = "/api/") -> None: self.app = app self.max_bytes = max_bytes self.path_prefix = path_prefix async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http" or not scope["path"].startswith(self.path_prefix): await self.app(scope, receive, send) return too_large = JSONResponse({"detail": "Anfrage ist zu groß."}, 413) content_length = Headers(scope=scope).get("content-length") if content_length and content_length.isdigit() and int(content_length) > self.max_bytes: await too_large(scope, receive, send) return received = 0 response_started = False rejected = False async def limited_receive() -> Message: nonlocal received, rejected message = await receive() if message["type"] == "http.request": received += len(message.get("body", b"")) if received > self.max_bytes and not response_started: rejected = True await too_large(scope, receive, send) return {"type": "http.disconnect"} return message async def guarded_send(message: Message) -> None: nonlocal response_started if rejected: return # 413 already sent if message["type"] == "http.response.start": response_started = True await send(message) await self.app(scope, limited_receive, guarded_send)