From 3c854b384dcc6c4c7fe5c2a76e0aa7c84fb37a3c Mon Sep 17 00:00:00 2001 From: Raj Mandhare <96978537+Raj2604@users.noreply.github.com> Date: Sun, 20 Jul 2025 00:18:52 +0530 Subject: [PATCH] Added Flexible CORS Configuration via Environment Variableadded flexibility to cors (#1109) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Description Fixes #1086 This PR improves the security and flexibility of the Cognee API’s CORS (Cross-Origin Resource Sharing) configuration. It introduces a new environment variable, CORS_ALLOWED_ORIGINS, which allows explicit control over which origins are permitted to access the API. The API now reads allowed origins from the CORS_ALLOWED_ORIGINS environment variable (comma-separated). If the variable is not set, all cross-origin requests are blocked by default (secure by default). For local development, you can use: CORS_ALLOWED_ORIGINS="http://localhost:3000" Added a commented example to .env.example to guide users in configuring CORS origins. ## DCO Affirmation I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin. Signed-off-by: Raj2604 Co-authored-by: Vasilije <8619304+Vasilije1990@users.noreply.github.com> --- cognee/api/.env.example | 5 +++++ cognee/api/client.py | 11 ++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 cognee/api/.env.example diff --git a/cognee/api/.env.example b/cognee/api/.env.example new file mode 100644 index 000000000..1e06871df --- /dev/null +++ b/cognee/api/.env.example @@ -0,0 +1,5 @@ +# Comma-separated list of allowed origins for CORS (leave empty to block all cross-origin requests) +# Example: +# CORS_ALLOWED_ORIGINS="https://yourdomain.com,https://another.com" +# For local development, you might use: +# CORS_ALLOWED_ORIGINS="http://localhost:3000" \ No newline at end of file diff --git a/cognee/api/client.py b/cognee/api/client.py index c504690e4..960677f78 100644 --- a/cognee/api/client.py +++ b/cognee/api/client.py @@ -67,13 +67,22 @@ async def lifespan(app: FastAPI): app = FastAPI(debug=app_environment != "prod", lifespan=lifespan) +# Read allowed origins from environment variable (comma-separated) +CORS_ALLOWED_ORIGINS = os.getenv("CORS_ALLOWED_ORIGINS") +if CORS_ALLOWED_ORIGINS: + allowed_origins = [origin.strip() for origin in CORS_ALLOWED_ORIGINS.split(",") if origin.strip()] +else: + allowed_origins = [] # Block all except explicitly set origins + app.add_middleware( CORSMiddleware, - allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"], + allow_origins=allowed_origins, # Now controlled by env var allow_credentials=True, allow_methods=["OPTIONS", "GET", "POST", "DELETE"], allow_headers=["*"], ) +# To allow origins, set CORS_ALLOWED_ORIGINS env variable to a comma-separated list, e.g.: +# CORS_ALLOWED_ORIGINS="https://yourdomain.com,https://another.com" def custom_openapi():