Missing Tls in Fastapi with Api Keys
Missing Tls in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
Transport Layer Security (TLS) ensures confidentiality and integrity in transit. When an API built with Fastapi relies on API keys for authorization but does not enforce TLS, keys can be captured in cleartext. This combination exposes a critical confidentiality breach: API keys travel as HTTP headers, and without TLS they are visible to anyone able to observe the network path, for example through shared Wi‑Fi, compromised routers, or workplace monitoring.
Consider the attack pattern where an attacker performs passive sniffing on a network segment. Without TLS, an API key in a header such as X-API-Key can be intercepted. Even if the API validates the key, the exposure alone can lead to unauthorized access across services that trust that key. Additionally, missing TLS enables active interception and modification in‑flight requests or responses, opening the door to tampering or injection. In regulated environments, transmitting credentials without encryption also conflicts with controls in frameworks such as OWASP API Security Top 10, PCI‑DSS, and GDPR.
Fastapi does not enforce transport security by itself; it relies on the deployment environment to provide TLS. If TLS is missing and API keys are used, the security boundary is effectively absent. MiddleBrick’s scans detect unencrypted transport alongside API key usage, flagging the risk of exposure and providing remediation guidance such as enforcing HTTPS and using secure key storage.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
To secure Fastapi APIs that use API keys, enforce TLS at the infrastructure level and validate keys securely within the application. Below are concrete practices and code examples.
1. Enforce HTTPS in Fastapi
Use middleware to reject HTTP requests when TLS is required. This does not replace TLS termination at the load balancer or reverse proxy, but it provides defense in depth.
from fastapi import FastAPI, Request, HTTPException
app = FastAPI()
@app.middleware("http")
async def enforce_https(request: Request, call_next):
if not request.url.scheme == "https":
raise HTTPException(status_code=403, detail="HTTPS is required")
response = await call_next(request)
return response
2. Secure API key handling with dependencies
Define a dependency that extracts and validates the API key, and apply it to routes that require protection. Avoid logging keys and ensure they are compared using a constant-time routine where possible.
from fastapi import Depends, FastAPI, Header, HTTPException, status
from secrets import compare_digest
app = FastAPI()
API_KEYS = {"my-secret-key-12345"} # ideally loaded from a secure vault
async def get_api_key(x_api_key: str = Header(None)):
if x_api_key is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing API key",
headers={"WWW-Authenticate": "ApiKey"},
)
if not any(compare_digest(x_api_key, valid) for valid in API_KEYS):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid API key",
)
return x_api_key
@app.get("/secure-data")
async def read_secure_data(api_key: str = Depends(get_api_key)):
return {"message": "Authorized", "key_present": bool(api_key)}
3. Infrastructure and operational practices
- Terminate TLS at the ingress (load balancer, reverse proxy, or container orchestration) and ensure strong ciphers and modern protocols (TLS 1.2+).
- Store API keys in a secrets manager and inject them into the application at runtime; avoid hardcoding them in source or configuration files.
- Rotate keys regularly and scope them by environment and consumer to limit blast radius.
- Use HTTP security headers (e.g., Strict-Transport-Security) and monitor for unusual access patterns that may indicate credential misuse.
MiddleBrick can help identify missing TLS alongside API key usage, highlighting findings with severity and remediation steps. For teams using CI/CD, the middlebrick GitHub Action can enforce a minimum security score before deployment, while the CLI allows local scans with middlebrick scan <url>.
Related CWEs: encryption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-319 | Cleartext Transmission of Sensitive Information | HIGH |
| CWE-295 | Improper Certificate Validation | HIGH |
| CWE-326 | Inadequate Encryption Strength | HIGH |
| CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | HIGH |
| CWE-328 | Use of Weak Hash | HIGH |
| CWE-330 | Use of Insufficiently Random Values | HIGH |
| CWE-338 | Use of Cryptographically Weak PRNG | MEDIUM |
| CWE-693 | Protection Mechanism Failure | MEDIUM |
| CWE-757 | Selection of Less-Secure Algorithm During Negotiation | HIGH |
| CWE-261 | Weak Encoding for Password | HIGH |