diff --git a/backend/app/config.py b/backend/app/config.py index 79fbc32..662d627 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -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" diff --git a/backend/app/main.py b/backend/app/main.py index 25fa67c..b2a7e02 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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") diff --git a/backend/app/middleware.py b/backend/app/middleware.py index 7dce0d5..9c3e2f0 100644 --- a/backend/app/middleware.py +++ b/backend/app/middleware.py @@ -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) diff --git a/backend/tests/test_hardening.py b/backend/tests/test_hardening.py new file mode 100644 index 0000000..151bc99 --- /dev/null +++ b/backend/tests/test_hardening.py @@ -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("spa") + + +@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