From 4fdaa2e45bbdd1bd4414f50ca365f628d6efc0e6 Mon Sep 17 00:00:00 2001 From: Mirko Stamm Date: Tue, 20 Oct 2026 14:13:01 +0100 Subject: [PATCH 1/2] fix(http): wire rate limiter and harden CORS origins - Register app.state.limiter and the RateLimitExceeded handler so over-limit requests return 429 instead of an unhandled 500 - Remove the invalid "*" origin combined with allow_credentials=True and pin CORS to the demo frontend origin (http://localhost:5173, no trailing slash) - Add tests covering the CORS preflight and the 429 rate-limit response --- main.py | 15 ++++------ test/test_routers/test_cors.py | 38 +++++++++++++++++++++++++ test/test_routers/test_rate_limit.py | 42 ++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 9 deletions(-) create mode 100644 test/test_routers/test_cors.py create mode 100644 test/test_routers/test_rate_limit.py diff --git a/main.py b/main.py index 0cca7dd..5854167 100644 --- a/main.py +++ b/main.py @@ -1,6 +1,7 @@ from contextvars import ContextVar from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware +from slowapi.errors import RateLimitExceeded from api.v1.routers import group, project, task, user, auth, ws, comment from db.database import create_db_and_tables from core.logger import logger, register_exceptions_handlers @@ -12,6 +13,8 @@ from time import time import structlog import uuid +from core.limiter import limiter +from slowapi import _rate_limit_exceeded_handler scheduler = AsyncIOScheduler() @@ -37,13 +40,7 @@ async def lifespan(app: FastAPI): register_exceptions_handlers(app) origins = [ - "http://localhost", - "http://localhost:8000", - "http://localhost:8080", - "*", - "http://127.0.0.1:8080", - "http://127.0.0.1:5500", - "http://localhost:5500", + "http://localhost:5173" ] app.add_middleware( @@ -54,8 +51,8 @@ async def lifespan(app: FastAPI): allow_headers=["*"], ) -# app.state.limiter = limiter -# app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) +app.state.limiter = limiter +app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) app.include_router(group.router) app.include_router(project.router) diff --git a/test/test_routers/test_cors.py b/test/test_routers/test_cors.py new file mode 100644 index 0000000..f6a9374 --- /dev/null +++ b/test/test_routers/test_cors.py @@ -0,0 +1,38 @@ +from main import app + +DEMO_ORIGIN = "http://localhost:5173" + + +def _preflight(client, origin): + return client.options( + "/login", + headers={ + "Origin": origin, + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "content-type", + }, + ) + + +def test_cors_preflight_allows_demo_frontend(client): + response = _preflight(client, DEMO_ORIGIN) + + assert response.status_code == 200 + assert response.headers["access-control-allow-origin"] == DEMO_ORIGIN + assert response.headers["access-control-allow-credentials"] == "true" + + +def test_cors_preflight_rejects_unknown_origin(client): + response = _preflight(client, "http://evil.example.com") + + assert "access-control-allow-origin" not in response.headers + + +def test_cors_does_not_use_wildcard_with_credentials(client): + allowed_origins = next( + m.kwargs["allow_origins"] + for m in app.user_middleware + if m.cls.__name__ == "CORSMiddleware" + ) + + assert "*" not in allowed_origins diff --git a/test/test_routers/test_rate_limit.py b/test/test_routers/test_rate_limit.py new file mode 100644 index 0000000..afac555 --- /dev/null +++ b/test/test_routers/test_rate_limit.py @@ -0,0 +1,42 @@ +import pytest +from main import app +from core.limiter import limiter + + +@pytest.fixture(autouse=True) +def reset_rate_limits(): + """Keep counters isolated so parallel/ordered tests never bleed into each other.""" + limiter.reset() + yield + limiter.reset() + + +def test_rate_limit_returns_429_when_exceeded(client): + payload = {"refresh": "invalid-token-for-rate-limit-test"} + + responses = [ + client.post("/refresh", json=payload) for _ in range(11) + ] + + statuses = [response.status_code for response in responses] + + assert statuses.count(429) >= 1, ( + f"Expected at least one 429 after exceeding 10/minute, got {statuses}" + ) + assert 500 not in statuses, ( + f"Rate limit must not surface as a 500, got {statuses}" + ) + + +def test_rate_limit_response_reports_retry_after(client): + payload = {"refresh": "invalid-token-for-rate-limit-test"} + response = None + + for _ in range(12): + response = client.post("/refresh", json=payload) + if response.status_code == 429: + break + + assert response is not None + assert response.status_code == 429 + assert response.json().get("error", "").startswith("Rate limit exceeded") From 1ab67da0cc78333405cd61a40752603d628dd375 Mon Sep 17 00:00:00 2001 From: Mirko Stamm Date: Tue, 20 Oct 2026 14:13:14 +0100 Subject: [PATCH 2/2] fix(auth): point Swagger Authorize to the real login route The OAuth2PasswordBearer tokenUrl was "token", but no /token route exists; Swagger's Authorize button failed with 404. Point it at /login. --- api/v1/routers/auth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/v1/routers/auth.py b/api/v1/routers/auth.py index 22f93b8..f66d79b 100644 --- a/api/v1/routers/auth.py +++ b/api/v1/routers/auth.py @@ -24,7 +24,7 @@ crypt = CryptContext(schemes=["bcrypt"]) -oauth2 = OAuth2PasswordBearer(tokenUrl="token", scheme_name="Bearer") +oauth2 = OAuth2PasswordBearer(tokenUrl="/login", scheme_name="Bearer") # @limiter.limit("10/minute")