Information Disclosure in Fastapi with Api Keys
Information Disclosure in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
Information Disclosure occurs when an API unintentionally exposes sensitive data to an unauthorized party. In FastAPI applications that rely on API keys for access control, this risk can emerge from a combination of implementation choices and missing safeguards. Even when keys are treated as secrets, they can be exposed through insecure logging, misconfigured error messages, or improper handling of request and response bodies.
FastAPI’s dependency injection system simplifies key extraction from headers, query parameters, or cookies, but if the key is logged, echoed in error responses, or reflected in metadata, the confidentiality of the key and any data it protects is compromised. For example, keys may appear in application logs or APM traces, and if those logs are aggregated or searchable, an attacker who gains access to the logging system can harvest valid keys.
Another common vector is verbose error handling. FastAPI’s default exception handlers can include request details, and if a developer accidentally includes the key in a debug message or validation exception, the key may be returned to the client in an error response. This can happen when custom exception handlers or validation logic inadvertently serialize the key into the response payload or headers.
Additionally, if the API key is transmitted over unencrypted channels (non-HTTPS), an attacker performing network interception can capture the key. Even when HTTPS is used, failing to enforce strict transport security or using weak cipher suites may weaken the protection of the key in transit. The server-side storage and routing of keys also matter: hardcoding keys in source files or configuration files that are checked into version control can lead to accidental disclosure through repository exposure.
The interaction with OpenAPI spec generation can further amplify disclosure risk. If the API key is defined as a security scheme in the OpenAPI document but the spec or generated documentation inadvertently exposes example keys or metadata, external consumers of the documentation might infer the structure or even discover test keys. Tools like middleBrick that perform OpenAPI/Swagger spec analysis with full $ref resolution can surface such risky examples or inconsistencies between declared security schemes and runtime behavior during unauthenticated scans.
In an unauthenticated scan, middleBrick tests endpoints that do not require a key to verify whether sensitive data is returned without authentication. When API keys are involved, the scanner evaluates whether endpoints that should be protected are inadvertently accessible, and whether error messages or metadata disclose the presence or format of keys. This helps identify endpoints where information disclosure might occur through misconfigured authentication or improper exception handling in FastAPI.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
To mitigate Information Disclosure when using API keys in FastAPI, adopt strict handling practices across request processing, error management, and documentation. The goal is to ensure keys are never logged, echoed, or serialized into responses, and that transport and storage remain secure.
Secure key extraction and validation
Extract keys using FastAPI dependencies without leaking them into logs or responses. Avoid printing or logging the key value at any point.
from fastapi import Depends, FastAPI, Header, HTTPException, status
from fastapi.security import APIKeyHeader
app = FastAPI()
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
def get_api_key(key: str = Header(...)):
if not key:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Missing API key",
)
# Do NOT log the key
if key != "expected_key_value":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid API key",
)
return key
@app.get("/secure-endpoint")
async def secure_data(key: str = Depends(get_api_key)):
return {"message": "Authorized access"}
Safe error handling
Customize exception handlers to avoid returning sensitive data. Do not include the key or its format in error bodies or headers.
from fastapi import Request
from fastapi.responses import JSONResponse
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
# Avoid echoing key values or stack details that may contain keys
return JSONContent(
status_code=exc.status_code,
content={"detail": exc.detail},
)
Transport and documentation safeguards
Enforce HTTPS and limit documentation exposure. Define the security scheme without example keys, and avoid including real keys in the OpenAPI spec.
from fastapi.openapi.utils import get_openapi
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="Secure API",
version="1.0.0",
routes=app.routes,
)
# Remove or redact any example keys in securitySchemes
security_schemes = openapi_schema.get("components", {}).get("securitySchemes", {})
if "api_key" in security_schemes:
security_schemes["api_key"]["example"] = None
openapi_schema["components"]["securitySchemes"] = security_schemes
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
Operational practices
- Store keys in environment variables or secret managers; never hardcode them in source files.
- Ensure all endpoints that require keys are behind HTTPS and use HTTP Strict Transport Security (HSTS).
- Audit logs to ensure key values are not present; mask or omit keys in any structured logging.
- Rotate keys regularly and revoke compromised keys immediately.
By combining these code-level practices with periodic scans using tools like middleBrick, you can identify endpoints where information disclosure may occur and verify that API key handling aligns with security expectations.