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")
|
data_dir: Path = Path("/data")
|
||||||
static_dir: Path = Path("/app/static")
|
static_dir: Path = Path("/app/static")
|
||||||
log_level: str = "info"
|
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
|
# Comma-separated list of origins allowed for state-changing requests and WebSockets
|
||||||
allowed_origins: str = "https://clip.webbildhauer.com"
|
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.api import admin, auth, health
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.db import _session_factory
|
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.auth import delete_old_login_attempts
|
||||||
from app.services.sessions import delete_expired_sessions
|
from app.services.sessions import delete_expired_sessions
|
||||||
from app.services.users import UserError, bootstrap_initial_admin
|
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()
|
candidate = (root / path).resolve()
|
||||||
if path and candidate.is_relative_to(root) and candidate.is_file():
|
if path and candidate.is_relative_to(root) and candidate.is_file():
|
||||||
return FileResponse(candidate)
|
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"})
|
return FileResponse(index_file, headers={"Cache-Control": "no-cache"})
|
||||||
|
|
||||||
|
|
||||||
@@ -90,12 +98,15 @@ def create_app() -> FastAPI:
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="LAN-Clipboard",
|
title="LAN-Clipboard",
|
||||||
version=__version__,
|
version=__version__,
|
||||||
docs_url="/api/docs",
|
docs_url="/api/docs" if settings.enable_api_docs else None,
|
||||||
openapi_url="/api/openapi.json",
|
openapi_url="/api/openapi.json" if settings.enable_api_docs else None,
|
||||||
redoc_url=None,
|
redoc_url=None,
|
||||||
lifespan=lifespan,
|
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(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(health.router, prefix="/api")
|
||||||
app.include_router(auth.router, prefix="/api")
|
app.include_router(auth.router, prefix="/api")
|
||||||
app.include_router(admin.router, prefix="/api")
|
app.include_router(admin.router, prefix="/api")
|
||||||
|
|||||||
+101
-1
@@ -1,6 +1,6 @@
|
|||||||
from starlette.datastructures import Headers
|
from starlette.datastructures import Headers
|
||||||
from starlette.responses import JSONResponse
|
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"})
|
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||||||
|
|
||||||
@@ -24,3 +24,103 @@ class OriginCheckMiddleware:
|
|||||||
await response(scope, receive, send)
|
await response(scope, receive, send)
|
||||||
return
|
return
|
||||||
await self.app(scope, receive, send)
|
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)
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def spa(static_dir):
|
||||||
|
(static_dir / "index.html").write_text("<html>spa</html>")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"path", ["/.env", "/root/.env", "/wp-login.php", "/config.json", "/.git/config"]
|
||||||
|
)
|
||||||
|
def test_file_like_paths_return_404(spa, client, path):
|
||||||
|
response = client.get(path)
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert "spa" not in response.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_app_routes_still_fall_back_to_index(spa, client):
|
||||||
|
assert client.get("/clips/42").status_code == 200
|
||||||
|
assert client.get("/admin/users").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_security_headers_on_api_and_spa(spa, client):
|
||||||
|
for path in ("/api/health", "/", "/does-not-exist.php"):
|
||||||
|
headers = client.get(path).headers
|
||||||
|
assert "default-src 'self'" in headers["content-security-policy"]
|
||||||
|
assert "frame-ancestors 'none'" in headers["content-security-policy"]
|
||||||
|
assert headers["x-content-type-options"] == "nosniff"
|
||||||
|
assert headers["x-frame-options"] == "DENY"
|
||||||
|
assert headers["referrer-policy"] == "same-origin"
|
||||||
|
|
||||||
|
|
||||||
|
def test_hsts_only_over_https(client, app_env):
|
||||||
|
assert client.get("/api/health").headers["strict-transport-security"] == "max-age=31536000"
|
||||||
|
|
||||||
|
with TestClient(client.app, base_url="http://testserver") as plain:
|
||||||
|
assert "strict-transport-security" not in plain.get("/api/health").headers
|
||||||
|
|
||||||
|
|
||||||
|
def test_security_headers_on_rejected_requests(client):
|
||||||
|
response = client.post("/api/auth/logout", headers={"Origin": "https://evil.example"})
|
||||||
|
assert response.status_code == 403
|
||||||
|
assert "content-security-policy" in response.headers
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_docs_disabled_by_default(client):
|
||||||
|
assert client.get("/api/docs").status_code == 404
|
||||||
|
assert client.get("/api/openapi.json").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_docs_can_be_enabled(app_env, monkeypatch):
|
||||||
|
monkeypatch.setenv("ENABLE_API_DOCS", "true")
|
||||||
|
get_settings.cache_clear()
|
||||||
|
from app.main import create_app
|
||||||
|
|
||||||
|
with TestClient(create_app(), base_url="https://testserver") as client:
|
||||||
|
assert client.get("/api/openapi.json").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_oversized_request_is_rejected(client):
|
||||||
|
body = b'{"username": "' + b"a" * (1024 * 1024) + b'", "password": "x"}'
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/login", content=body, headers={"Content-Type": "application/json"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 413
|
||||||
|
|
||||||
|
|
||||||
|
def test_oversized_chunked_request_is_rejected(client):
|
||||||
|
def chunks():
|
||||||
|
for _ in range(20):
|
||||||
|
yield b"a" * 100_000
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/login", content=chunks(), headers={"Content-Type": "application/json"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 413
|
||||||
|
|
||||||
|
|
||||||
|
def test_normal_requests_pass_size_limit(client):
|
||||||
|
response = client.post("/api/auth/login", json={"username": "x", "password": "y"})
|
||||||
|
assert response.status_code == 401
|
||||||
Reference in new issue
Block a user