fix: harden CORS origin allow list

Fixes #322
This commit is contained in:
Abhishek Kumar 2026-05-27 15:36:48 +05:30
parent 6d78537297
commit 6f79bd67eb
5 changed files with 38 additions and 11 deletions

View file

@ -2,7 +2,12 @@
import sentry_sdk
from api.constants import DEPLOYMENT_MODE, ENABLE_TELEMETRY, SENTRY_DSN
from api.constants import (
CORS_ALLOWED_ORIGINS,
DEPLOYMENT_MODE,
ENABLE_TELEMETRY,
SENTRY_DSN,
)
from api.logging_config import ENVIRONMENT, setup_logging
# Set up logging and get the listener for cleanup
@ -83,13 +88,33 @@ app = FastAPI(
)
# Configure CORS
# Configure CORS.
# OSS is typically deployed with UI and API behind a single reverse proxy
# (same-origin, so CORS does not apply). Keep it permissive without
# credentials — wildcard + credentials is rejected by browsers and unsafe.
# SaaS deployments must set CORS_ALLOWED_ORIGINS to an explicit allowlist.
if DEPLOYMENT_MODE == "oss":
cors_origins: list[str] = ["*"]
cors_allow_credentials = False
else:
if not CORS_ALLOWED_ORIGINS:
raise RuntimeError(
"CORS_ALLOWED_ORIGINS must be set to an explicit origin allowlist "
"when DEPLOYMENT_MODE != 'oss'"
)
if "*" in CORS_ALLOWED_ORIGINS:
raise RuntimeError(
"CORS_ALLOWED_ORIGINS cannot contain '*' with credentialed requests"
)
cors_origins = CORS_ALLOWED_ORIGINS
cors_allow_credentials = True
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
allow_origins=cors_origins,
allow_credentials=cors_allow_credentials,
allow_methods=["*"],
allow_headers=["*"],
)
api_router = APIRouter()

View file

@ -26,6 +26,9 @@ DATABASE_URL = os.environ["DATABASE_URL"]
REDIS_URL = os.environ["REDIS_URL"]
DEPLOYMENT_MODE = os.getenv("DEPLOYMENT_MODE", "oss")
CORS_ALLOWED_ORIGINS = [
o.strip() for o in os.getenv("CORS_ALLOWED_ORIGINS", "").split(",") if o.strip()
]
AUTH_PROVIDER = os.getenv("AUTH_PROVIDER", "local")
DOGRAH_MPS_SECRET_KEY = os.getenv("DOGRAH_MPS_SECRET_KEY", None)
MPS_API_URL = os.getenv("MPS_API_URL", "https://services.dograh.com")

View file

@ -215,9 +215,7 @@ def test_runtime_blocks_elevenlabs_local_tts_base_url_in_saas(monkeypatch):
def test_embedding_service_blocks_private_base_url_in_saas(monkeypatch):
monkeypatch.setattr(
"api.utils.url_security.DEPLOYMENT_MODE", "saas"
)
monkeypatch.setattr("api.utils.url_security.DEPLOYMENT_MODE", "saas")
with pytest.raises(ValueError, match="public IP"):
OpenAIEmbeddingService(