OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
fix: CORS misconfiguration: replace wildcard Access-Control-Allow-Origin with explicit origin allowlist (#2253)
Mike Fortmanb7108469cbdc
diff --git a/.env.example b/.env.exampleindex b874daac0..c1edb52f7 100644--- a/.env.example+++ b/.env.example@@ -61,6 +61,12 @@ OPENRAG_BACKEND_PORT=8000# if you need to override the auto-derived value (e.g., custom hostname).# OPENRAG_BACKEND_INTERNAL_URL=http://openrag-backend:8000+# --- CORS -------------------------------------------------------------------+# Comma-separated list of origins allowed to make cross-origin requests+# (e.g. "https://app.example.com,https://admin.example.com").+# Unset → defaults to http://localhost:3000. Set to "" to disable CORS entirely.+CORS_ALLOWED_ORIGINS=http://localhost:3000+# --- Backend ingestion-callback proxy router --------------------------------# When enabled, a tiny standalone uvicorn app is started in the same process as# the backend (its own port) that proxies ONLY the Langflow ingest callbackdiff --git a/docker-compose.yml b/docker-compose.ymlindex 25f6eb6c1..4413de1fa 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -124,6 +124,7 @@ services:- PLATFORM_AUTH_DEV_MODE=${PLATFORM_AUTH_DEV_MODE:-false}- DOCLING_SERVE_URL=${DOCLING_SERVE_URL:-http://host.docker.internal:5001}- DOCLING_SERVE_VERIFY_SSL=${DOCLING_SERVE_VERIFY_SSL:-true}+ - CORS_ALLOWED_ORIGINS=${CORS_ALLOWED_ORIGINS-http://localhost:3000}volumes:- ${OPENRAG_DOCUMENTS_PATH:-./openrag-documents}:/app/openrag-documents:U,z- ${OPENRAG_KEYS_PATH:-./keys}:/app/keys:U,zdiff --git a/kubernetes/helm/openrag/templates/backend/backend-dotenv.yaml b/kubernetes/helm/openrag/templates/backend/backend-dotenv.yamlindex a3a46684b..236b1452a 100644--- a/kubernetes/helm/openrag/templates/backend/backend-dotenv.yaml+++ b/kubernetes/helm/openrag/templates/backend/backend-dotenv.yaml@@ -214,6 +214,8 @@ stringData:{{- end }}# Langflow auth (OpenRag uses this to determine how to authenticate with Langflow)+ CORS_ALLOWED_ORIGINS={{ .Values.backend.cors.allowedOrigins | quote }}+LANGFLOW_AUTO_LOGIN={{ ternary "true" "false" .Values.langflow.auth.autoLogin }}# OpenRag / OAuth return URL (Included in OAuth State)diff --git a/kubernetes/helm/openrag/values.yaml b/kubernetes/helm/openrag/values.yamlindex 800bf8be3..f1033b343 100644--- a/kubernetes/helm/openrag/values.yaml+++ b/kubernetes/helm/openrag/values.yaml@@ -243,6 +243,9 @@ backend:repository: langflowai/openrag-backendtag: "" # Uses global.imageTag if empty+ cors:+ allowedOrigins: "" # Comma-separated origins; empty = CORS disabled+oauthBrokerUrl: "" # Public return URL for OAuth redirects# Single pod for vertical scalingdiff --git a/src/api/chat.py b/src/api/chat.pyindex c30f15289..de70808b3 100644--- a/src/api/chat.py+++ b/src/api/chat.py@@ -96,8 +96,6 @@ async def chat_endpoint(headers={"Cache-Control": "no-cache","Connection": "keep-alive",- "Access-Control-Allow-Origin": "*",- "Access-Control-Allow-Headers": "Cache-Control",},)else:@@ -159,8 +157,6 @@ async def langflow_endpoint(headers={"Cache-Control": "no-cache","Connection": "keep-alive",- "Access-Control-Allow-Origin": "*",- "Access-Control-Allow-Headers": "Cache-Control",},)else:diff --git a/src/app/factory.py b/src/app/factory.pyindex 1e8a4c1b1..b541c136b 100644--- a/src/app/factory.py+++ b/src/app/factory.py@@ -5,13 +5,14 @@ into a ready-to-serve FastAPI app."""from fastapi import FastAPI+from fastapi.middleware.cors import CORSMiddlewarefrom prometheus_fastapi_instrumentator import Instrumentatorfrom app.container import initialize_servicesfrom app.lifespan import run_shutdown, run_startupfrom app.middleware import RequestLoggingMiddlewarefrom app.routes import register_all_routes-from config.settings import FASTAPI_DEBUG+from config.settings import CORS_ALLOWED_ORIGINS, FASTAPI_DEBUGfrom utils.logging_config import get_loggerfrom utils.version_utils import OPENRAG_VERSION@@ -26,6 +27,15 @@ async def create_app():app.state.services = servicesapp.state.background_tasks = set()+ if CORS_ALLOWED_ORIGINS:+ app.add_middleware(+ CORSMiddleware,+ allow_origins=CORS_ALLOWED_ORIGINS,+ allow_credentials=False,+ allow_methods=["*"],+ allow_headers=["*"],+ )+# Wire up ASGI request logging middleware (pure ASGI, not BaseHTTPMiddleware)app.add_middleware(RequestLoggingMiddleware)diff --git a/src/config/settings.py b/src/config/settings.pyindex 75730cbab..6b1d15e96 100644--- a/src/config/settings.py+++ b/src/config/settings.py@@ -108,6 +108,13 @@ LANGFLOW_URL_INGEST_FLOW_ID = (DEFAULT_CHUNK_SIZE = 1000DEFAULT_CHUNK_OVERLAP = 200OPENRAG_BACKEND_PORT = get_env_int("OPENRAG_BACKEND_PORT", 8000)++# CORS – comma-separated list of allowed origins (e.g. "https://app.example.com,https://admin.example.com").+# Unset → defaults to http://localhost:3000. Set to "" to disable CORS entirely.+_raw_cors_origins = os.getenv("CORS_ALLOWED_ORIGINS", "http://localhost:3000")+CORS_ALLOWED_ORIGINS: list[str] = [+ o.strip() for o in _raw_cors_origins.split(",") if o.strip() and o.strip() != "*"+]OPENRAG_BACKEND_INTERNAL_URL = os.getenv("OPENRAG_BACKEND_INTERNAL_URL",f"http://openrag-backend:{OPENRAG_BACKEND_PORT}",diff --git a/tests/unit/config/test_cors_allowed_origins.py b/tests/unit/config/test_cors_allowed_origins.pynew file mode 100644index 000000000..2496ca2ce--- /dev/null+++ b/tests/unit/config/test_cors_allowed_origins.py@@ -0,0 +1,126 @@+"""Tests for CORS_ALLOWED_ORIGINS parsing and middleware wiring."""++import os+import subprocess+import sys+from pathlib import Path+from unittest.mock import AsyncMock, patch++import pytest+from fastapi.middleware.cors import CORSMiddleware++ROOT = Path(__file__).resolve().parent.parent.parent.parent+SRC = ROOT / "src"++PRINT_ORIGINS = (+ "from config.settings import CORS_ALLOWED_ORIGINS; "+ "import json; print(json.dumps(CORS_ALLOWED_ORIGINS))"+)+++def _python_env(env: dict[str, str]) -> dict[str, str]:+ merged = os.environ.copy()+ merged.update(env)+ return merged+++def _run_settings(extra_env: dict[str, str]) -> list[str]:+ env = _python_env({"PYTHONPATH": str(SRC), **extra_env})+ env.pop("CORS_ALLOWED_ORIGINS", None)+ env.update(extra_env)+ result = subprocess.run(+ [sys.executable, "-c", PRINT_ORIGINS],+ capture_output=True,+ text=True,+ check=True,+ env=env,+ cwd=str(ROOT),+ )+ import json++ return json.loads(result.stdout.splitlines()[-1])+++def test_parses_comma_separated_origins():+ origins = _run_settings({"CORS_ALLOWED_ORIGINS": "https://a.com,https://b.com"})+ assert origins == ["https://a.com", "https://b.com"]+++def test_trims_whitespace():+ origins = _run_settings({"CORS_ALLOWED_ORIGINS": " https://a.com , https://b.com "})+ assert origins == ["https://a.com", "https://b.com"]+++def test_filters_empty_entries():+ origins = _run_settings({"CORS_ALLOWED_ORIGINS": "https://a.com,,https://b.com,"})+ assert origins == ["https://a.com", "https://b.com"]+++def test_empty_string_yields_empty_list():+ origins = _run_settings({"CORS_ALLOWED_ORIGINS": ""})+ assert origins == []+++def test_unset_defaults_to_localhost():+ env = _python_env({"PYTHONPATH": str(SRC)})+ env.pop("CORS_ALLOWED_ORIGINS", None)+ result = subprocess.run(+ [sys.executable, "-c", PRINT_ORIGINS],+ capture_output=True,+ text=True,+ check=True,+ env=env,+ cwd=str(ROOT),+ )+ import json++ origins = json.loads(result.stdout.splitlines()[-1])+ assert origins == ["http://localhost:3000"]+++# ---------------------------------------------------------------------------+# Factory middleware wiring+# ---------------------------------------------------------------------------+++def _get_cors_middleware(app):+ for mw in app.user_middleware:+ if mw.cls is CORSMiddleware:+ return mw+ return None+++async def test_factory_adds_cors_middleware_when_origins_set():+ with (+ patch("app.factory.CORS_ALLOWED_ORIGINS", ["https://app.example.com"]),+ patch("app.factory.initialize_services", new_callable=AsyncMock),+ ):+ from app.factory import create_app++ app = await create_app()+ mw = _get_cors_middleware(app)+ assert mw is not None+ assert mw.kwargs["allow_origins"] == ["https://app.example.com"]+++async def test_factory_skips_cors_middleware_when_origins_empty():+ with (+ patch("app.factory.CORS_ALLOWED_ORIGINS", []),+ patch("app.factory.initialize_services", new_callable=AsyncMock),+ ):+ from app.factory import create_app++ app = await create_app()+ assert _get_cors_middleware(app) is None+++def test_wildcard_origin_rejected():+ origins = _run_settings({"CORS_ALLOWED_ORIGINS": "*"})+ assert origins == []+++def test_wildcard_stripped_from_mixed_origins():+ origins = _run_settings({"CORS_ALLOWED_ORIGINS": "https://a.com,*,https://b.com"})+ assert origins == ["https://a.com", "https://b.com"]