Prototype Pollution in Fastapi with Cockroachdb
Prototype Pollution in Fastapi with Cockroachdb — how this specific combination creates or exposes the vulnerability
Prototype pollution in a FastAPI application that uses CockroachDB typically arises when user-controlled input is merged into configuration objects or query-building logic before data is stored or retrieved. CockroachDB, like other SQL databases, does not directly suffer from prototype pollution, but the surrounding Python code can introduce unsafe object manipulation that affects how data is parameterized, serialized, or interpreted by the application layer.
In FastAPI, route handlers often receive JSON payloads that are passed directly to helper functions or ORM mappers. If these handlers mutate shared objects—such as configuration dicts, query templates, or dynamically built SQL parameter maps—an attacker can inject properties that affect behavior for subsequent requests. For example, a handler that does data = {**default_query, **request_body} may allow an attacker to add or override keys like __proto__, constructor, or other special properties that change how later code interprets the dictionary.
When the polluted object is used to construct SQL statements or parameter lists for CockroachDB, the injected properties may affect field mapping, filter conditions, or serialization formats. While CockroachDB safely handles parameterized queries, the pollution occurs earlier—in the construction of those parameters. A common pattern is building a WHERE clause from a dictionary that has been inadvertently modified, causing unexpected filtering logic or schema references that can lead to unauthorized data access or inconsistent state handling.
Additionally, if the application caches query templates or reuses base objects across requests, a single polluted template can affect multiple operations. This is particularly risky when the polluted data influences schema or table name resolution, as it may cause the application to reference unintended objects in CockroachDB. Because FastAPI relies on Python’s dynamic typing, these mutations are not always obvious during development, especially when utility functions are shared across modules.
To detect this specific combination, scanning should verify that incoming payloads do not modify shared configuration objects and that parameter construction for CockroachDB queries uses isolated, validated structures. The scanner checks for unsafe merge patterns, direct mutation of base dictionaries, and the presence of prototype pollution indicators in request handling code before data reaches the database layer.
Cockroachdb-Specific Remediation in Fastapi — concrete code fixes
Remediation focuses on isolating user input from shared objects and using strict parameter construction for CockroachDB interactions. Avoid merging user data into base configuration or query templates. Instead, validate and map fields individually before constructing SQL parameters.
Below are concrete code examples demonstrating safe patterns for FastAPI with CockroachDB.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import psycopg2
from psycopg2 import sql
app = FastAPI()
class QueryParams(BaseModel):
user_id: int
limit: int = 10
# Safe: isolated parameter construction
def build_safe_query(params: QueryParams):
query = sql.SQL("SELECT * FROM users WHERE user_id = {id} LIMIT {limit}").format(
id=sql.Literal(params.user_id),
limit=sql.Literal(params.limit)
)
return query
@app.get("/users")
async def get_users(user_id: int, limit: int = 10):
params = QueryParams(user_id=user_id, limit=limit)
query = build_safe_query(params)
conn = psycopg2.connect(
host="your-cockroachdb-host",
port=26257,
user="your-user",
password="your-password",
database="your-db"
)
try:
with conn.cursor() as cur:
cur.execute(query.as_string(conn))
rows = cur.fetchall()
return {"data": rows}
finally:
conn.close()
Key practices:
- Use Pydantic models to validate and isolate incoming data.
- Construct SQL with
psycopg2.sqlmodule to safely inject literals and identifiers. - Never merge request bodies into shared or global objects.
- Ensure that query-building logic does not reference mutable default arguments.
These steps prevent prototype pollution from affecting CockroachDB parameterization and ensure that user input is treated strictly as data, not as code-influencing properties.