Api Key Exposure in Fastapi with Cockroachdb
Api Key Exposure in Fastapi with Cockroachdb — how this specific combination creates or exposes the vulnerability
In a Fastapi application that uses Cockroachdb, API key exposure often occurs when sensitive credentials are handled inconsistently between application logic and database access patterns. Fastapi’s dependency injection system can inadvertently expose keys through route handlers that pass credentials as parameters or store them in request state without adequate isolation. When Cockroachdb connection strings or query parameters containing API keys are constructed dynamically using string formatting, they may be logged, intercepted, or included in error messages returned to clients.
For example, constructing a Cockroachdb connection URI by concatenating user input directly enables leakage through SQL error messages or application logs:
from fastapi import FastAPI, Depends, HTTPException
import asyncpg
app = FastAPI()
# Vulnerable: API key embedded in connection string built from user input
def get_db_connection(api_key: str):
connection_string = f"postgresql://user:{api_key}@cockroachdb.example.com:26257/mydb?sslmode=require"
return asyncpg.connect(connection_string)
@app.get("/items/")
async def read_items(key: str = Depends(get_db_connection)):
conn = await get_db_connection(key)
# If the key is invalid, Cockroachdb may return detailed error messages
# that include the partial connection string or key fragments
...
Additionally, Cockroachdb’s wire protocol and default logging settings may expose query parameters containing API keys when debug or performance logging is enabled. Fastapi middleware that captures request and response bodies might also inadvertently log headers or cookies that carry authentication tokens used to authenticate to Cockroachdb. The combination of Fastapi’s flexibility in handling dependencies and Cockroachdb’s verbose error reporting increases the likelihood of keys being exposed through unauthenticated attack surfaces scanned by middleBrick.
During black-box scanning, middleBrick checks whether API keys appear in HTTP response data, server headers, or error payloads. If a Fastapi endpoint backed by Cockroachdb returns stack traces or database error details that reference authentication strings, middleBrick flags this as Data Exposure with guidance to sanitize outputs and use connection pooling with predefined credentials rather than runtime key assembly.
Cockroachdb-Specific Remediation in Fastapi — concrete code fixes
To prevent API key exposure when using Cockroachdb with Fastapi, store connection parameters outside of request handling and avoid constructing connection strings from untrusted input. Use environment variables or a secure secrets manager to provide credentials, and rely on connection pooling to reuse authenticated sessions without embedding keys in responses.
Secure Fastapi dependency that uses environment variables and asyncpg pool:
from fastapi import FastAPI, Depends
import asyncpg
import os
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
# Initialize connection pool at startup using credentials from environment
pool = await asyncpg.create_pool(
host=os.getenv("COCKROACH_HOST", "localhost"),
port=int(os.getenv("COCKROACH_PORT", 26257)),
user=os.getenv("COCKROACH_USER", "root"),
password=os.getenv("COCKROACH_PASSWORD", ""),
database=os.getenv("COCKROACH_DATABASE", "defaultdb"),
ssl=True,
min_size=1,
max_size=10
)
app.state.pool = pool
yield
await pool.close()
app = FastAPI(lifespan=lifespan)
async def get_db_pool():
return app.state.pool
@app.get("/items/")
async def read_items(pool: asyncpg.Pool = Depends(get_db_pool)):
async with pool.acquire() as conn:
# Use parameterized queries; API key never appears in logs or errors
rows = await conn.fetch("SELECT id, name FROM items WHERE category = $1", "electronics")
return [dict(row) for row in rows]
This approach ensures the Cockroachdb authentication credentials remain in the runtime environment and are never constructed from client-supplied data. By using a connection pool initialized during application startup, Fastapi avoids per-request key assembly that could lead to exposure in logs or error messages. middleBrick’s scans validate that no API keys are reflected in HTTP responses or server headers, and the remediation aligns with Data Exposure findings by enforcing strict separation between secrets and request handling.
For production deployments, enable Cockroachdb’s TLS settings consistently and configure Fastapi to reject insecure connections. Avoid printing or logging any part of the connection parameters, and ensure that database driver warnings or notices do not propagate to clients. middleBrick’s checks for Encryption and Data Exposure help confirm that credentials are not unintentionally surfaced through the API surface.