Clickjacking in Fastapi with Cockroachdb
Clickjacking in Fastapi with Cockroachdb — how this specific combination creates or exposes the vulnerability
Clickjacking is a client-side UI security issue where an attacker tricks a user into interacting with a hidden or disguised element inside an invisible or disguised iframe. In a Fastapi application backed by Cockroachdb, the vulnerability typically arises when responses do not enforce frame-embedding restrictions, allowing an attacker to embed sensitive pages (for example, a change-email or confirm-action view) inside a malicious site. Even though Cockroachdb is a distributed SQL database and does not directly enforce UI policies, the way application endpoints are designed and how Fastapi serves responses determines whether clickjacking is possible.
Consider a Fastapi route that reads user settings from Cockroachdb and renders an HTML page without setting Content-Security-Policy frame-ancestors or X-Frame-Options. An attacker can embed this page in an iframe and overlay invisible controls, capturing user consent or credentials without their awareness. Cockroachdb does not introduce clickjacking by itself; however, if connection handling, session management, or data retrieval endpoints expose user-specific actions without CSRF-like UI protections, the risk is compounded because the UI relies on database state that may be assumed to be safe simply because the database enforces strong ACID guarantees.
Middleware that sets security headers is essential. Fastapi applications should explicitly prevent framing regardless of the database backend. Failing to set frame-ancestors 'none' (or specific trusted origins) means any page that renders dynamic data from Cockroachdb—such as a user profile or transaction confirmation—can be weaponized in a clickjacking attack. The database stores the truth, but the application layer must enforce safe embedding rules; otherwise, an attacker can exploit UI trust even when backend data integrity is strong.
Cockroachdb-Specific Remediation in Fastapi — concrete code fixes
Remediation focuses on HTTP headers and safe rendering practices. In Fastapi, you can set global security headers and ensure each response that renders UI includes strict frame controls. Below are concrete examples showing how to integrate Cockroachdb safely while preventing clickjacking.
1. Security middleware with frame protections
Use middleware to set X-Frame-Options and Content-Security-Policy for all responses, including those that fetch data from Cockroachdb.
from fastapi import Fastapi, Request
from fastapi.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
response.headers['X-Frame-Options'] = 'DENY'
response.headers['Content-Security-Policy'] = "frame-ancestors 'none'"
return response
app = Fastapi(middleware=[Middleware(SecurityHeadersMiddleware)])
2. Example Cockroachdb-dependent route with safe headers
When rendering dynamic pages that depend on Cockroachdb, explicitly apply frame protection in the route and ensure CSP is not overridden.
from fastapi import Fastapi, Depends, HTTPException
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, async_sessionmaker
DATABASE_URL = "cockroachdb://username:password@host:26257/dbname?sslmode=require"
engine = create_async_engine(DATABASE_URL, echo=False)
async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_db():
async with async_session() as session:
yield session
@app.get("/user/settings")
async def get_user_settings(db: AsyncSession = Depends(get_db)):
result = await db.execute(text("SELECT id, display_name FROM users WHERE id = $1"), [1])
row = result.fetchone()
if row is None:
raise HTTPException(status_code=404, detail="User not found")
# Render or return data; ensure frontend sets CSP frame-ancestors as well
return {"id": row[0], "display_name": row[1]}
3. Frontend integration guidance
Even with backend headers, single-page applications that embed their own UI must set CSP frame-ancestors on the document. If your Fastapi app serves HTML templates, ensure each template includes the CSP header or meta tag. For APIs consumed by external clients, use the same middleware so that no page can be framed regardless of the Cockroachdb-driven data source.