Man In The Middle in Fastapi with Cockroachdb
Man In The Middle in Fastapi with Cockroachdb — how this specific combination creates or exposes the vulnerability
A Man In The Middle (MitM) risk arises in a Fastapi + Cockroachdb deployment when communication between the application and the database is not strictly enforced to be encrypted and authenticated. Cockroachdb is a distributed SQL database that supports TLS for client connections. If Fastapi connects to Cockroachdb without enforcing TLS or without proper certificate validation, an attacker on the network path can intercept and manipulate traffic. This is especially relevant in cloud and containerized environments where traffic traverses shared networks and service meshes.
Fastapi itself does not manage database connections; it relies on the underlying driver and connection settings. If the Cockroachdb connection string omits secure parameters (e.g., sslmode=verify-full) or uses insecure defaults (e.g., sslmode=disable or sslmode=require without verifying server identity), credentials, query patterns, or session tokens may be exposed. For example, an attacker who can position themselves between the Fastapi service and the Cockroachdb cluster could capture database credentials or alter queries in transit, leading to authentication bypass or data tampering.
The risk is compounded when Fastapi applications run in environments with multiple network hops, such as Kubernetes services, load balancers, or serverless platforms, where traffic might be routed through internal meshes that do not enforce encryption by default. Cockroachdb’s certificate-based authentication and TLS termination must be correctly configured on the client side. Without verifying the server certificate chain (ca_cert, cert, key), Fastapi can unknowingly communicate with a malicious node that presents a valid-looking certificate but is controlled by an attacker.
In practice, a misconfigured async database driver in Fastapi (e.g., using asyncpg or a Cockroachdb-compatible driver) with weak sslmode allows plaintext or weakly encrypted packets to traverse the network. Observability tools that log query parameters or stack traces might inadvertently expose sensitive data if logs are transmitted without encryption, creating a secondary MitM vector via log aggregation pipelines.
MitM attacks against Fastapi + Cockroachdb align with common OWASP API Security Top 10 risks such as broken object level authorization when session tokens are intercepted, and security misconfiguration when transport security is not enforced. Real-world attack patterns include session hijacking, credential theft, and query manipulation, which can lead to unauthorized data access or privilege escalation.
Cockroachdb-Specific Remediation in Fastapi — concrete code fixes
Remediation centers on enforcing TLS with strict certificate validation for every Cockroachdb client connection from Fastapi. Below are concrete, working examples using a Cockroachdb-compatible async driver in Fastapi. These examples assume you have a Cockroachdb cluster with TLS certificates generated (ca.crt, client.crt, client.key).
from fastapi import Fastapi, Depends, HTTPException
import asyncpg
import ssl
import os
app = Fastapi()
# Build a secure SSL context that enforces server certificate verification
ssl_ctx = ssl.create_default_context(cafile=os.getenv("COCKROACH_CA_CERT"))
ssl_ctx.load_cert_chain(
certfile=os.getenv("CLIENT_CERT"),
keyfile=os.getenv("CLIENT_KEY")
)
ssl_ctx.verify_mode = ssl.CERT_REQUIRED
# Ensure the driver uses the strictest available mode
# sslmode=verify-full requires server hostname verification via cert
conn_str = (
"postgresql://{{user}}:{{password}}@{{host}}:{{port}}/{{dbname}}"
"?sslmode=verify-full"
"&sslrootcert=" + os.getenv("COCKROACH_CA_CERT")
"&sslcert=" + os.getenv("CLIENT_CERT")
"&sslkey=" + os.getenv("CLIENT_KEY")
)
@app.on_event("startup")
async def startup():
try:
app.state.pool = await asyncpg.create_pool(
dsn=conn_str,
ssl=ssl_ctx,
min_size=1,
max_size=3
)
except Exception as e:
raise RuntimeError(f"Failed to connect to Cockroachdb securely: {e}")
@app.get("/widgets/{widget_id}")
async def get_widget(
widget_id: int,
pool: asyncpg.Pool = Depends(lambda: app.state.pool)
):
async with pool.acquire() as conn:
row = await conn.fetchrow(
"SELECT id, name, metadata FROM widgets WHERE id = $1",
widget_id
)
if row is None:
raise HTTPException(status_code=404, detail="Widget not found")
return {"id": row[0], "name": row[1], "metadata": row[2]}
@app.on_event("shutdown")
async def shutdown():
if hasattr(app.state, "pool"):
app.state.pool.close()
Key points in the code:
sslmode=verify-fullensures both encryption and server identity verification against the Common Name or Subject Alternative Name in the server certificate.- The SSL context explicitly loads the CA certificate and client certificate/key for mutual TLS, which Cockroachdb supports for strong client authentication.
- Environment variables are used to manage secrets, avoiding hardcoded paths or credentials in source code.
- The driver receives the SSL context object, ensuring that the underlying TLS handshake validates the server chain against the provided CA.
Operational practices to complement the code:
- Rotate Cockroachdb client certificates regularly and revoke compromised certificates via the cluster’s certificate authority.
- Use network policies to restrict which IP ranges or service accounts can reach the Cockroachdb endpoints, reducing the attack surface even if encryption is terminated incorrectly.
- Instrument connection errors to detect downgrade attempts or missing certificate validation, which may indicate misconfiguration or active probing.
By combining strict TLS settings in the connection string with proper certificate management in Fastapi, the risk of MitM between the API layer and Cockroachdb is materially reduced. This approach aligns with secure-by-default guidance for distributed databases and helps meet compliance expectations around data-in-transit protection.