Allow for CORS Origin Setting (#2449)

* allow setting of CORS origin

* simplify

* add environment variable + rename

* slightly more efficient

* simplify so mypy doens't complain

* temp

* go back to my preferred formatting
This commit is contained in:
pablodanswer 2024-09-16 11:54:36 -07:00 committed by GitHub
parent 96b98fbc4a
commit df464fc54b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 21 additions and 2 deletions

View File

@ -125,10 +125,10 @@ from danswer.utils.telemetry import RecordType
from danswer.utils.variable_functionality import fetch_versioned_implementation
from danswer.utils.variable_functionality import global_version
from danswer.utils.variable_functionality import set_is_ee_based_on_env_variable
from shared_configs.configs import CORS_ALLOWED_ORIGIN
from shared_configs.configs import MODEL_SERVER_HOST
from shared_configs.configs import MODEL_SERVER_PORT
logger = setup_logger()
@ -591,7 +591,7 @@ def get_application() -> FastAPI:
application.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Change this to the list of allowed origins if needed
allow_origins=CORS_ALLOWED_ORIGIN, # Configurable via environment variable
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],

View File

@ -1,4 +1,5 @@
import os
from urllib.parse import urlparse
# Used for logging
SLACK_CHANNEL_ID = "channel_id"
@ -73,3 +74,18 @@ PRESERVED_SEARCH_FIELDS = [
"passage_prefix",
"query_prefix",
]
# CORS
def validate_cors_origin(origin: str) -> None:
parsed = urlparse(origin)
if parsed.scheme not in ["http", "https"] or not parsed.netloc:
raise ValueError(f"Invalid CORS origin: '{origin}'")
CORS_ALLOWED_ORIGIN = os.environ.get("CORS_ALLOWED_ORIGIN", "*").split(",") or ["*"]
# Validate non-wildcard origins
for origin in CORS_ALLOWED_ORIGIN:
if origin != "*" and (stripped_origin := origin.strip()):
validate_cors_origin(stripped_origin)

View File

@ -34,6 +34,7 @@ services:
- OAUTH_CLIENT_SECRET=${OAUTH_CLIENT_SECRET:-}
- OPENID_CONFIG_URL=${OPENID_CONFIG_URL:-}
- TRACK_EXTERNAL_IDP_EXPIRY=${TRACK_EXTERNAL_IDP_EXPIRY:-}
- CORS_ALLOWED_ORIGIN=${CORS_ALLOWED_ORIGIN:-}
# Gen AI Settings
- GEN_AI_MAX_TOKENS=${GEN_AI_MAX_TOKENS:-}
- QA_TIMEOUT=${QA_TIMEOUT:-}

View File

@ -31,6 +31,7 @@ services:
- SMTP_PASS=${SMTP_PASS:-}
- EMAIL_FROM=${EMAIL_FROM:-}
- TRACK_EXTERNAL_IDP_EXPIRY=${TRACK_EXTERNAL_IDP_EXPIRY:-}
- CORS_ALLOWED_ORIGIN=${CORS_ALLOWED_ORIGIN:-}
# Gen AI Settings
- GEN_AI_MAX_TOKENS=${GEN_AI_MAX_TOKENS:-}
- QA_TIMEOUT=${QA_TIMEOUT:-}

View File

@ -13,6 +13,7 @@ data:
SMTP_USER: "" # 'your-email@company.com'
SMTP_PASS: "" # 'your-gmail-password'
EMAIL_FROM: "" # 'your-email@company.com' SMTP_USER missing used instead
CORS_ALLOWED_ORIGIN: ""
# Gen AI Settings
GEN_AI_MAX_TOKENS: ""
QA_TIMEOUT: "60"