feat(api): add configurable CORS middleware

The web UI is multi-instance and can connect to the backend at a
different origin (the direct :8000 port, a LAN IP, 127.0.0.1 vs
localhost), which the browser blocks without CORS headers. Adds
CORSMiddleware driven by a new cors_allow_origins setting (default "*",
safe here: bearer-token auth with allow_credentials=False). Accepts a
comma-separated string in .env.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Цвылев Александр Вадимович
2026-07-28 14:33:24 +03:00
parent a263272935
commit c47242aa3a
2 changed files with 34 additions and 0 deletions
+14
View File
@@ -4,6 +4,7 @@ from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI, WebSocket
from fastapi.middleware.cors import CORSMiddleware
from app.api.errors import register_exception_handlers
from app.api.health import router as health_router
@@ -40,6 +41,19 @@ def create_app() -> FastAPI:
)
app.add_middleware(CorrelationIdMiddleware)
# CORS added last → outermost, so browser preflight (OPTIONS) is answered
# before anything else. The web UI can connect cross-origin (direct :8000,
# a LAN IP, 127.0.0.1 vs localhost), which needs these headers. Bearer-token
# auth (no cookies) → wildcard origins are safe with allow_credentials=False.
if settings.cors_allow_origins:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_allow_origins,
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["Content-Range", "Accept-Ranges", "Content-Length"],
)
register_exception_handlers(app)
app.include_router(health_router)