From 5120645b567df0074639c0e104ebb83eac24fc4b Mon Sep 17 00:00:00 2001 From: yashvats Date: Tue, 6 Oct 2026 00:48:15 +0530 Subject: [PATCH] security: harden HTTP requests and responses --- apps/api/app/core/middleware.py | 88 +++++++++++++++++++++++++++ apps/api/app/main.py | 6 +- apps/api/tests/test_http_security.py | 91 ++++++++++++++++++++++++++++ 3 files changed, 184 insertions(+), 1 deletion(-) create mode 100644 apps/api/app/core/middleware.py create mode 100644 apps/api/tests/test_http_security.py diff --git a/apps/api/app/core/middleware.py b/apps/api/app/core/middleware.py new file mode 100644 index 0000000..66e07ce --- /dev/null +++ b/apps/api/app/core/middleware.py @@ -0,0 +1,88 @@ + +import typing +from starlette.types import ASGIApp, Receive, Scope, Send, Message + +MAX_REQUEST_BODY_BYTES = 1_000_000 # 1 MB + +class RequestBodyTooLargeError(Exception): + pass + +class SecurityAndBodyLimitMiddleware: + """ + Combined middleware for setting security headers and enforcing request body limits. + Done in a single ASGI middleware to minimize overhead. + """ + def __init__(self, app: ASGIApp, max_body_size: int = MAX_REQUEST_BODY_BYTES) -> None: + self.app = app + self.max_body_size = max_body_size + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + # 1. Check Content-Length upfront + content_length_header = next( + (v for k, v in scope["headers"] if k.lower() == b"content-length"), None + ) + if content_length_header is not None: + try: + if int(content_length_header) > self.max_body_size: + await self._send_413(send) + return + except ValueError: + pass # Ignore malformed Content-Length and let it fail downstream + + # 2. Track chunked or unspecified body size + total_bytes = 0 + + async def receive_wrapper() -> Message: + nonlocal total_bytes + message = await receive() + if message["type"] == "http.request": + body = message.get("body", b"") + total_bytes += len(body) + if total_bytes > self.max_body_size: + raise RequestBodyTooLargeError("REQUEST_BODY_TOO_LARGE") + return message + + is_secure = scope.get("scheme") == "https" + path = scope.get("path", "") + + async def send_wrapper(message: Message) -> None: + if message["type"] == "http.response.start": + headers = message.setdefault("headers", []) + + # Security Headers + headers.append((b"x-content-type-options", b"nosniff")) + headers.append((b"x-frame-options", b"DENY")) + headers.append((b"referrer-policy", b"strict-origin-when-cross-origin")) + headers.append((b"permissions-policy", b"camera=(), microphone=(), geolocation=()")) + + # No cache for auth + if path.startswith("/auth/"): + headers.append((b"cache-control", b"no-store")) + + # HSTS in production/https only + if is_secure: + headers.append((b"strict-transport-security", b"max-age=31536000; includeSubDomains")) + + await send(message) + + try: + await self.app(scope, receive_wrapper, send_wrapper) + except RequestBodyTooLargeError: + await self._send_413(send) + + async def _send_413(self, send: Send) -> None: + response_body = b'{"detail": "Request body too large.", "code": "REQUEST_BODY_TOO_LARGE"}' + headers = [ + (b"content-type", b"application/json"), + (b"content-length", str(len(response_body)).encode("ascii")), + (b"x-content-type-options", b"nosniff"), + (b"x-frame-options", b"DENY"), + (b"referrer-policy", b"strict-origin-when-cross-origin"), + ] + await send({"type": "http.response.start", "status": 413, "headers": headers}) + await send({"type": "http.response.body", "body": response_body}) + diff --git a/apps/api/app/main.py b/apps/api/app/main.py index 73c658e..be08203 100644 --- a/apps/api/app/main.py +++ b/apps/api/app/main.py @@ -3,6 +3,9 @@ from fastapi.middleware.cors import CORSMiddleware from sqlalchemy import text +from app.core.config import settings +from app.core.middleware import SecurityAndBodyLimitMiddleware + from app.api.routes import auth, repositories, pr_reviews, dashboard, ask from app.core.ai_errors import AIQuotaExceededError from app.core.rate_limit import RateLimitMiddleware @@ -32,7 +35,7 @@ def ai_quota_exception_handler(request: Request, exc: AIQuotaExceededError): app.add_middleware( CORSMiddleware, - allow_origins=["http://localhost:3000"], + allow_origins=[settings.frontend_url], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], @@ -41,6 +44,7 @@ def ai_quota_exception_handler(request: Request, exc: AIQuotaExceededError): # Rate limiting — added after CORS so 429 responses still carry CORS headers # for browser clients. app.add_middleware(RateLimitMiddleware) +app.add_middleware(SecurityAndBodyLimitMiddleware) app.include_router(auth.router) diff --git a/apps/api/tests/test_http_security.py b/apps/api/tests/test_http_security.py new file mode 100644 index 0000000..67c6abf --- /dev/null +++ b/apps/api/tests/test_http_security.py @@ -0,0 +1,91 @@ + +import pytest +from fastapi.testclient import TestClient +from app.main import app +from app.core.config import settings + +client = TestClient(app) + +def test_request_body_too_large(): + """Request body exceeding 1MB is rejected with 413.""" + large_payload = b"a" * (1_000_000 + 1) + response = client.post("/auth/login", content=large_payload, headers={"Content-Type": "application/json"}) + assert response.status_code == 413 + assert response.json()["code"] == "REQUEST_BODY_TOO_LARGE" + +def test_normal_request_under_limit(): + """Normal request under the limit works normally.""" + response = client.post("/auth/login", json={"email": "test@example.com", "password": "wrong"}) + assert response.status_code == 401 # Normal authentication failure, meaning body passed + +def test_security_headers_exist(): + """Security headers are present in responses.""" + response = client.get("/health") + assert response.status_code == 200 + assert response.headers.get("x-content-type-options") == "nosniff" + assert response.headers.get("x-frame-options") == "DENY" + assert response.headers.get("referrer-policy") == "strict-origin-when-cross-origin" + assert "camera=()" in response.headers.get("permissions-policy", "") + +def test_hsts_behavior_https_only(): + """HSTS is only included on secure (HTTPS) requests.""" + # HTTP request + http_client = TestClient(app, base_url="http://localhost") + response_http = http_client.get("/health") + assert "strict-transport-security" not in response_http.headers + + # HTTPS request + https_client = TestClient(app, base_url="https://codelens.app") + response_https = https_client.get("/health") + assert "strict-transport-security" in response_https.headers + assert "max-age=31536000" in response_https.headers.get("strict-transport-security") + +def test_cors_allowed_origin(): + """CORS allows the configured frontend origin.""" + origin = settings.frontend_url + response = client.options( + "/auth/login", + headers={ + "Origin": origin, + "Access-Control-Request-Method": "POST" + } + ) + assert response.status_code == 200 + assert response.headers.get("access-control-allow-origin") == origin + +def test_cors_rejected_origin(): + """CORS rejects arbitrary origins.""" + response = client.options( + "/auth/login", + headers={ + "Origin": "http://evil.com", + "Access-Control-Request-Method": "POST" + } + ) + assert response.status_code == 400 + assert "Disallowed CORS origin" in response.text or response.headers.get("access-control-allow-origin") is None + +def test_cors_no_wildcard_with_credentials(): + """Credentialed requests do not use wildcard origins.""" + origin = settings.frontend_url + response = client.options( + "/auth/login", + headers={ + "Origin": origin, + "Access-Control-Request-Method": "POST" + } + ) + assert response.headers.get("access-control-allow-origin") != "*" + assert response.headers.get("access-control-allow-credentials") == "true" + +def test_auth_cache_control(): + """Authentication endpoints set Cache-Control: no-store.""" + response = client.post("/auth/login", json={"email": "test@example.com", "password": "wrong"}) + assert response.headers.get("cache-control") == "no-store" + +def test_health_accessible(): + """Health endpoint remains accessible and lightweight.""" + response = client.get("/health") + assert response.status_code == 200 + assert response.json() == {"status": "ok", "service": "codelens"} +