Cors Wildcard in Fastapi with Cockroachdb
Cors Wildcard in Fastapi with Cockroachdb — how this specific combination creates or exposes the vulnerability
A CORS wildcard (Access-Control-Allow-Origin: *) in Fastapi permits any origin to read responses from your API. When the backend uses CockroachDB as its database, responses may include sensitive data or tokens that the frontend should not access. Because the browser enforces the same-origin policy based on the Origin header, a wildcard allows any site to make authenticated requests (carrying cookies or authorization headers) and read the results if credentials are included. This can expose user-specific data stored in CockroachDB, such as profile details or session-related rows, to malicious origins.
In Fastapi, using CORSMiddleware with allow_origins=["*"] while also allowing credentials or exposed endpoints that return CockroachDB-derived resources creates a cross-origin data exposure path. Even if CockroachDB enforces its own authentication and row-level security, the API layer can inadvertently return data that should remain restricted. An attacker who controls a webpage can script cross-origin requests, leveraging the wildcard to harvest information that would otherwise be protected by CockroachDB’s access controls.
The risk is compounded when preflight requests are handled permissively or when allow_methods includes unsafe verbs and allow_headers exposes authorization headers. Because the API does not validate the origin, any domain can participate in the interaction and read responses containing data queried from CockroachDB. This does not imply a CockroachDB misconfiguration, but rather an API configuration issue that removes the browser-enforced boundary between origins.
Cockroachdb-Specific Remediation in Fastapi — concrete code fixes
To remediate, explicitly define allowed origins and avoid wildcards when credentials or sensitive CockroachDB data are involved. Configure CORS to reflect the requesting origin only when it is trusted, and scope methods and headers to what your frontend actually needs.
from fastapi import Fastapi
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "cockroachdb://username:password@host:26257/dbname?sslmode=require"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
app = Fastapi()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.yourdomain.com", "https://staging.yourdomain.com"],
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["Authorization", "Content-Type"],
expose_headers=["X-Total-Count"],
max_age=86400,
)
@app.get("/users/me")
def read_current_user(x_token: str):
db = SessionLocal()
try:
# Use parameterized queries to avoid injection
result = db.execute(text("SELECT id, email, name FROM users WHERE token = :token"), {"token": x_token})
row = result.fetchone()
if row is None:
return {"error": "not found"}
return {"id": row[0], "email": row[1], "name": row[2]}
finally:
db.close()
@app.get("/org/{org_id}/members")
def list_members(org_id: int, x_token: str):
db = SessionLocal()
try:
result = db.execute(
text("SELECT id, username FROM members WHERE org_id = :org_id AND role != 'hidden'"),
{"org_id": org_id},
)
members = [{"id": r[0], "username": r[1]} for r in result]
return {"members": members}
finally:
db.close()
If you must use a wildcard during development, restrict it to non-sensitive endpoints and ensure responses do not include authentication tokens or CockroachDB-specific identifiers. In production, prefer explicit origins and enforce authentication checks within your route logic, validating tokens against the user records stored in CockroachDB before returning any data.
Additionally, enable row-level security in CockroachDB so that even if the API is misconfigured, tenants cannot read rows belonging to others. Combine this with parameterized SQL from Fastapi to prevent injection, and audit CORS settings regularly using the middleBrick CLI to detect accidental wildcards in deployed configurations.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |
Frequently Asked Questions
Does using a CORS wildcard with CockroachDB always lead to data exposure?
Is it safe to allow credentials with a wildcard origin in Fastapi?
Access-Control-Allow-Origin is a wildcard. To use credentials, specify exact origins in Fastapi’s CORS middleware instead of using "*".