From 1a7096b2765af35af2aba6f6feb4027b0813ef3a Mon Sep 17 00:00:00 2001 From: Lukas Date: Mon, 6 Apr 2026 20:42:33 +0200 Subject: [PATCH] Add environment-driven CORS settings and backend regression tests --- Docs/Tasks.md | 2 +- backend/.env.example | 4 +++ backend/app/config.py | 8 ++++++ backend/app/main.py | 20 ++++++++------- backend/tests/test_main.py | 50 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 74 insertions(+), 10 deletions(-) create mode 100644 backend/tests/test_main.py diff --git a/Docs/Tasks.md b/Docs/Tasks.md index 145dfc5..cc71973 100644 --- a/Docs/Tasks.md +++ b/Docs/Tasks.md @@ -53,7 +53,7 @@ Reference: `Docs/Refactoring.md` for full analysis of each issue. ### Backend Feature Work -- **Document and implement backend-safe environment-driven CORS.** +- **Document and implement backend-safe environment-driven CORS.** ✅ - Add support for production and local development origins through configuration. - Avoid a hardcoded Vite origin in the core app factory. diff --git a/backend/.env.example b/backend/.env.example index 9b663cc..e1932ed 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -20,3 +20,7 @@ BANGUI_TIMEZONE=UTC # Application log level: debug | info | warning | error | critical BANGUI_LOG_LEVEL=info + +# Comma-separated list of allowed CORS origins when the frontend is served +# from a different origin than the backend. +BANGUI_CORS_ALLOWED_ORIGINS=http://localhost:5173 diff --git a/backend/app/config.py b/backend/app/config.py index 0f73ce5..6ad8575 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -41,6 +41,14 @@ class Settings(BaseSettings): default="UTC", description="IANA timezone name used when displaying timestamps in the UI.", ) + cors_allowed_origins: list[str] = Field( + default_factory=lambda: ["http://localhost:5173"], + description=( + "Comma-separated list of allowed CORS origins when the frontend is " + "served from a different origin than the backend. " + "Leave empty to disable cross-origin requests in production." + ), + ) log_level: str = Field( default="info", description="Application log level: debug | info | warning | error | critical.", diff --git a/backend/app/main.py b/backend/app/main.py index a59be51..2ba771c 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -345,15 +345,17 @@ def create_app(settings: Settings | None = None) -> FastAPI: set_setup_complete_cache(app, False) # --- CORS --- - # In production the frontend is served by the same origin. - # CORS is intentionally permissive only in development. - app.add_middleware( - CORSMiddleware, - allow_origins=["http://localhost:5173"], # Vite dev server - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], - ) + # Allow origins configured by the runtime environment. In production, + # this should be explicitly set to the frontend origin(s) or left empty + # when the UI is served from the same origin as the API. + if resolved_settings.cors_allowed_origins: + app.add_middleware( + CORSMiddleware, + allow_origins=resolved_settings.cors_allowed_origins, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) # --- Middleware --- # Note: middleware is applied in reverse order of registration. diff --git a/backend/tests/test_main.py b/backend/tests/test_main.py new file mode 100644 index 0000000..b1453ad --- /dev/null +++ b/backend/tests/test_main.py @@ -0,0 +1,50 @@ +"""Unit tests for backend application startup and middleware configuration.""" + +from app.config import Settings +from app.main import CORSMiddleware, create_app + + +def test_create_app_configures_cors_from_settings() -> None: + """The FastAPI app registers CORS middleware with the configured origins.""" + settings = Settings( + database_path="/tmp/test.db", + fail2ban_socket="/tmp/fake_fail2ban.sock", + fail2ban_config_dir="/tmp/fail2ban", + session_secret="test-secret-key-do-not-use-in-production", + session_duration_minutes=60, + timezone="UTC", + log_level="debug", + cors_allowed_origins=["https://frontend.example.com"], + ) + + app = create_app(settings=settings) + cors_middleware = [ + middleware for middleware in app.user_middleware if middleware.cls is CORSMiddleware + ] + + assert len(cors_middleware) == 1 + assert cors_middleware[0].kwargs["allow_origins"] == ["https://frontend.example.com"] + assert cors_middleware[0].kwargs["allow_credentials"] is True + assert cors_middleware[0].kwargs["allow_methods"] == ["*"] + assert cors_middleware[0].kwargs["allow_headers"] == ["*"] + + +def test_create_app_skips_cors_when_no_origins_are_configured() -> None: + """The FastAPI app does not add CORS middleware when no origins are configured.""" + settings = Settings( + database_path="/tmp/test.db", + fail2ban_socket="/tmp/fake_fail2ban.sock", + fail2ban_config_dir="/tmp/fail2ban", + session_secret="test-secret-key-do-not-use-in-production", + session_duration_minutes=60, + timezone="UTC", + log_level="debug", + cors_allowed_origins=[], + ) + + app = create_app(settings=settings) + cors_middleware = [ + middleware for middleware in app.user_middleware if middleware.cls is CORSMiddleware + ] + + assert cors_middleware == []