feat: härtung für den öffentlichen betrieb
- Security-Header (CSP, nosniff, X-Frame-Options, Referrer-/Permissions-Policy) - HSTS nur bei HTTPS und ohne includeSubDomains - echtes 404 für dateiartige Pfade wie /.env statt SPA-Fallback - API-Doku nur mit ENABLE_API_DOCS=true - API-Requests über 1 MiB werden mit 413 abgelehnt, auch bei Chunked-Upload Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dc4b804ccf
commit
66fe8feea4
4 files changed
+201
-4
No files matched your search
@@ -10,6 +10,8 @@ class Settings(BaseSettings):
|
||||
data_dir: Path = Path("/data")
|
||||
static_dir: Path = Path("/app/static")
|
||||
log_level: str = "info"
|
||||
enable_api_docs: bool = False
|
||||
max_request_bytes: int = 1024 * 1024
|
||||
|
||||
# Comma-separated list of origins allowed for state-changing requests and WebSockets
|
||||
allowed_origins: str = "https://clip.webbildhauer.com"
|
||||
|
||||
+14
-3
@@ -12,7 +12,11 @@ from app import __version__
|
||||
from app.api import admin, auth, health
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.middleware import OriginCheckMiddleware
|
||||
from app.middleware import (
|
||||
BodySizeLimitMiddleware,
|
||||
OriginCheckMiddleware,
|
||||
SecurityHeadersMiddleware,
|
||||
)
|
||||
from app.services.auth import delete_old_login_attempts
|
||||
from app.services.sessions import delete_expired_sessions
|
||||
from app.services.users import UserError, bootstrap_initial_admin
|
||||
@@ -82,6 +86,10 @@ def _register_frontend(app: FastAPI, static_dir: Path) -> None:
|
||||
candidate = (root / path).resolve()
|
||||
if path and candidate.is_relative_to(root) and candidate.is_file():
|
||||
return FileResponse(candidate)
|
||||
# Paths that look like files (/.env, /wp-login.php, /.git/config) are not app routes
|
||||
segments = path.split("/")
|
||||
if "." in segments[-1] or any(seg.startswith(".") for seg in segments):
|
||||
raise HTTPException(status_code=404)
|
||||
return FileResponse(index_file, headers={"Cache-Control": "no-cache"})
|
||||
|
||||
|
||||
@@ -90,12 +98,15 @@ def create_app() -> FastAPI:
|
||||
app = FastAPI(
|
||||
title="LAN-Clipboard",
|
||||
version=__version__,
|
||||
docs_url="/api/docs",
|
||||
openapi_url="/api/openapi.json",
|
||||
docs_url="/api/docs" if settings.enable_api_docs else None,
|
||||
openapi_url="/api/openapi.json" if settings.enable_api_docs else None,
|
||||
redoc_url=None,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
# Last added runs first: security headers wrap every response, including rejections
|
||||
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||
app.add_middleware(BodySizeLimitMiddleware, max_bytes=settings.max_request_bytes)
|
||||
app.add_middleware(SecurityHeadersMiddleware)
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(auth.router, prefix="/api")
|
||||
app.include_router(admin.router, prefix="/api")
|
||||
|
||||
+101
-1
@@ -1,6 +1,6 @@
|
||||
from starlette.datastructures import Headers
|
||||
from starlette.responses import JSONResponse
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||||
|
||||
@@ -24,3 +24,103 @@ class OriginCheckMiddleware:
|
||||
await response(scope, receive, send)
|
||||
return
|
||||
await self.app(scope, receive, send)
|
||||
|
||||
|
||||
CONTENT_SECURITY_POLICY = "; ".join(
|
||||
[
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'self' data:",
|
||||
"connect-src 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
]
|
||||
)
|
||||
|
||||
SECURITY_HEADERS = [
|
||||
(b"content-security-policy", CONTENT_SECURITY_POLICY.encode()),
|
||||
(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) -> None:
|
||||
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
|
||||
|
||||
extra = list(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)
|
||||
Reference in new issue
Block a user