Log Injection in Fastapi with Cockroachdb
Log Injection in Fastapi with Cockroachdb — how this specific combination creates or exposes the vulnerability
Log Injection occurs when untrusted input is written directly into application logs without proper sanitization or formatting, allowing an attacker to forge log entries, inject newlines, or manipulate log metadata. In a Fastapi application using Cockroachdb as the backend datastore, the risk emerges from the interaction between request handling, database operations, and logging practices.
Fastapi does not inherently sanitize user-controlled data before it reaches application code. If a developer logs data from HTTP requests—such as query parameters, headers, or request bodies—and that data is later used in SQL statements against Cockroachdb, newline characters (\n, \r) or other control characters can alter the structure of log lines. For example, an attacker could provide a username containing a newline followed by arbitrary text; when the application logs this value, the forged line appears as a separate log entry, potentially misrepresenting authentication events or transaction flow.
With Cockroachdb, this becomes more impactful because the database logs and application logs are often correlated during incident investigation. A malicious actor might inject log entries that mimic successful transactions or administrative actions, obscuring real malicious activity. Consider a Fastapi route that logs the user_id before executing a Cockroachdb query. If the user_id includes a carriage return and a fabricated log message, the resulting log stream can appear coherent but misleading. Cockroachdb’s wire protocol and SQL interface do not prevent such injection because the vulnerability lies in how the application writes data to logs, not in the database itself.
Additionally, Fastapi’s dependency injection and middleware layers can inadvertently propagate unvalidated inputs into logging contexts. For instance, an authorization header that contains newline characters could be logged verbatim before being passed to a Cockroachdb connection pool. The database driver then executes parameterized queries safely, but the surrounding application code has already written tainted text to stdout or structured logs. This misalignment between secure database interactions and unsafe logging creates a blind spot that standard SQL injection protections do not address.
The OWASP API Security Top 10 category ‘Security Logging and Monitoring Failures’ directly applies here. Without structured logging and strict input validation on fields destined for logs, attackers can bypass audit trails and degrade forensic readiness. middleBrick’s LLM/AI Security checks and runtime analysis help detect anomalous patterns in logged outputs, supporting compliance with frameworks like SOC2 and PCI-DSS that require integrity in audit logging.
Cockroachdb-Specific Remediation in Fastapi — concrete code fixes
To mitigate Log Injection in Fastapi with Cockroachdb, focus on input validation, structured logging, and safe string handling before data reaches logs or database drivers. The following practices and code examples are tailored to this stack.
1. Validate and sanitize inputs before logging
Reject or transform inputs containing newline characters at the API boundary. Use Fastapi’s validation layer to enforce acceptable formats.
from fastapi import FastAPI, HTTPException, Query
import re
app = FastAPI()
NEWLINE_RE = re.compile(r'[\r\n]')
def safe_username(value: str) -> str:
if NEWLINE_RE.search(value):
raise ValueError('Username contains invalid characters')
return value.strip()
@app.get('/users/{user_id}')
def get_user(
user_id: str = Query(..., description='User identifier', min_length=1)
):
safe_id = safe_username(user_id)
# Proceed to Cockroachdb query using safe_id
return {'user_id': safe_id}
2. Use structured logging with explicit field separation
Log key events as structured objects rather than concatenated strings. This prevents injected newlines from corrupting log parsers and keeps audit trails machine-readable.
import logging
from fastapi import Fastapi
import json
app = Fastapi()
logger = logging.getLogger('api')
@app.post('/transactions')
def create_transaction(amount: float, user_id: str):
safe_user = safe_username(user_id)
# Structured log entry
logger.info(json.dumps({
'event': 'transaction_created',
'user_id': safe_user,
'amount': amount
}))
# Execute Cockroachdb statement safely
return {'status': 'ok'}
3. Parameterized queries with Cockroachdb driver
Always use parameterized statements to avoid SQL injection and ensure that data values are never interpreted as executable SQL or log artifacts. The Cockroachdb Python driver supports this via cursor.execute with placeholders.
import psycopg2
from fastapi import Depends
def get_db_connection():
# Connection parameters should be managed securely
conn = psycopg2.connect(
host='your-cockroachdb-host',
port=26257,
user='app_user',
password='secure_password',
database='app_db'
)
return conn
@app.get('/items/{item_id}')
def read_item(item_id: int, conn=Depends(get_db_connection)):
with conn.cursor() as cur:
cur.execute('SELECT name, price FROM items WHERE id = %s', (item_id,))
row = cur.fetchone()
return {'name': row[0], 'price': row[1]}
4. Middleware-level sanitization
Add a Fastapi middleware that scans incoming payloads and headers for newline characters before they reach route handlers. This centralizes protection across all endpoints interacting with Cockroachdb.
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
class LogInjectionMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# Inspect headers and body for newline characters
for header, values in request.headers.multi_items():
for v in values:
if '\n' in v or '\r' in v:
raise HTTPException(status_code=400, detail=f'Invalid header: {header}')
response = await call_next(request)
return response
app.add_middleware(LogInjectionMiddleware)
5. Align with compliance and monitoring
middleBrick scans can validate that your API disallows newline injection in key fields and that logs remain structured. Findings map to OWASP API Top 10 and PCI-DSS requirements for secure logging. For continuous assurance, the Pro plan enables scheduled scans and alerts when risky patterns appear in API behavior.