Added Flexible CORS Configuration via Environment Variableadded flexibility to cors (#1109)

<!-- .github/pull_request_template.md -->

## 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.
<!-- Provide a clear description of the changes in this PR -->

## 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 <rajmandhare26@gmail.com>
Co-authored-by: Vasilije <8619304+Vasilije1990@users.noreply.github.com>
This commit is contained in:
Raj Mandhare 2025-07-20 00:18:52 +05:30 committed by GitHub
parent 02df4a79be
commit 3c854b384d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 15 additions and 1 deletions

5
cognee/api/.env.example Normal file
View file

@ -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"

View file

@ -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():