Cors Wildcard in Fastapi with Api Keys
Cors Wildcard in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
Using a CORS wildcard (origins=["*"]) together with API key authentication in FastAPI can unintentionally expose protected endpoints to any origin. When allow_credentials is enabled alongside a wildcard, browsers may allow cross-origin requests to include credentials such as cookies or authorization headers, which can make API key–based routes accessible from untrusted websites.
In FastAPI, developers sometimes apply a global CORS policy like this:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
If an endpoint relies on an API key passed via a header (e.g., x-api-key), the wildcard CORS configuration does not validate the source of the request. Any webpage hosted on a malicious domain can issue requests on behalf of users who possess a valid API key, especially when the key is stored in JavaScript or embedded in client-side code. This undermines the boundary between public and private consumers of the API.
middleBrick scans this attack surface during the BFLA/Privilege Escalation and CORS checks, flagging permissive origins when authentication mechanisms like API keys are in use. In a black-box scan, the tool can detect whether responses differ across origins or whether unauthorized origins can successfully include credentials.
An illustrative malicious origin scenario:
<script>
fetch('https://api.example.com/items', {
method: 'GET',
headers: { 'x-api-key': 'leaked-key-from-source-code' },
credentials: 'include'
}).then(r => r.json()).then(console.log);
</script>
Although the API key is expected to be confidential, a wildcard CORS policy with credentials enabled can allow such cross-origin usage if the key leaks into browser-executable code. The finding highlights the need to scope origins tightly when using static API keys.
middleBrick’s LLM/AI Security checks do not directly test CORS, but the scanner correlates authentication mechanisms with CORS settings to prioritize findings that could lead to unauthorized data exposure. The tool also maps findings to frameworks such as OWASP API Top 10 and PCI-DSS, helping teams justify remediation.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
To secure FastAPI endpoints that use API keys, restrict CORS origins to known, trusted domains and avoid enabling credentials for wildcard origins. Combine explicit origin lists with proper key validation and scope checks.
Recommended secure CORS setup with API keys:
from fastapi import FastAPI, Depends, Header, HTTPException
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://trusted-app.com", "https://admin.example.com"],
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["x-api-key", "content-type"],
)
API_KEYS = {"sk_live_abc123", "sk_test_xyz789"}
def get_api_key(x_api_key: str = Header(None)):
if x_api_key not in API_KEYS:
raise HTTPException(status_code=403, detail="Invalid API Key")
return x_api_key
@app.get("/items")
def read_items(x_api_key: str = Depends(get_api_key)):
return {"data": "protected resource"}
This configuration ensures that only requests from approved origins can include credentials, and API key validation occurs via a dependency that checks against a set of valid keys. For production, store keys in environment variables or a secrets manager rather than hardcoding them.
If you need broader origins for partners, avoid allow_credentials=True with the wildcard. Instead, use a specific origin list and validate the Origin header server-side when required. middleBrick’s Authentication and Property Authorization checks can verify that origins and credentials are correctly scoped during scans.
For continuous protection, the Pro plan enables scheduled scans and change detection so that a misconfigured wildcard CORS rule or an accidental allow_credentials: true with allow_origins=["*"] is caught before it reaches production. The GitHub Action can fail builds if the risk score drops below your defined threshold, providing automated guardrails.
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 |