Header Injection in Fastapi with Firestore
Header Injection in Fastapi with Firestore — how this specific combination creates or exposes the vulnerability
Header Injection occurs when user-controlled data is reflected into HTTP response headers without validation or encoding. In a Fastapi application that integrates with Google Cloud Firestore, this typically happens when request headers (e.g., X-Custom-Name, Referer, or X-Forwarded-For) are read and then used to construct Firestore document fields or response headers. Because Fastapi relies on Starlette for request handling, headers are accessible via Request.headers, and if these values are passed directly to Firestore without sanitization, they can manipulate response headers or metadata stored in Firestore, leading to security issues such as response splitting or data poisoning.
When Firestore documents are built from header content, injection can affect data integrity. For example, a header value containing newline characters could allow an attacker to inject additional headers or metadata when the document is later rendered or exported. Although Fastapi does not directly expose headers to Firestore operations, developers may inadvertently use header values in fields such as user_agent, source_ip, or referrer that are stored in Firestore. If those documents are later used in responses or logs, the injected content can affect downstream systems.
The combination of Fastapi’s dynamic routing and Firestore’s flexible schema amplifies the risk. Firestore documents often mirror request context for observability, such as storing request.headers for debugging. If header values are stored as-is and later used in admin interfaces or API responses without escaping, attackers can exploit this to inject malicious content. While this does not directly compromise Firestore’s access controls, it can lead to cross-site scripting (XSS) when data is rendered in web UIs or used in logs viewed by administrators.
Real-world impact includes response splitting if header-injected data is reflected back in HTTP responses, or data manipulation in Firestore documents that corrupts audit trails. For instance, an attacker might send a request with X-Forwarded-For: 127.0.0.1\r\nSet-Cookie: session=stolen. If the application writes this header value into a Firestore document and later includes it in a response, the injected Set-Cookie line could be interpreted as a new header, leading to session fixation or other client-side attacks.
middleBrick detects Header Injection risks by analyzing how header values are handled across the API surface. The scanner checks whether headers are validated, encoded, or sanitized before being used in Firestore document fields or response construction. Findings include severity ratings and guidance to ensure headers are treated as untrusted input, aligning with OWASP API Top 10 categories such as API1:2023 – Broken Object Level Authorization when header data influences document access patterns.
Firestore-Specific Remediation in Fastapi — concrete code fixes
To prevent Header Injection when using Fastapi with Firestore, always treat header values as untrusted input. Validate and sanitize headers before using them in Firestore document fields or response generation. Below are concrete code examples demonstrating secure practices.
First, define a utility function to sanitize header values by removing or encoding characters that could enable injection, such as newlines and carriage returns:
import re
from starlette.requests import Request
def sanitize_header(value: str) -> str:
# Remove carriage return and newline characters to prevent response splitting
return re.sub(r'[\r\n]', '', value)
Next, when creating Firestore documents from request headers, apply sanitization and avoid storing raw header values. Here is an example using the Google Cloud Firestore client for Python:
from fastapi import FastAPI, Request
from google.cloud import firestore
import uuid
app = FastAPI()
db = firestore.Client()
@app.post('/events/')
async def create_event(request: Request):
user_agent = request.headers.get('User-Agent', '')
referer = request.headers.get('Referer', '')
# Sanitize headers before storing
safe_user_agent = sanitize_header(user_agent)
safe_referer = sanitize_header(referer)
doc_ref = db.collection('events').document(str(uuid.uuid4()))
doc_ref.set({
'user_agent': safe_user_agent,
'referer': safe_referer,
'event_type': 'page_view'
})
return {'id': doc_ref.id, 'status': 'recorded'}
When returning data that originated from headers, ensure that any dynamic content is properly escaped before being included in response headers. For example, if you need to echo a sanitized header value in a custom response header, use Fastapi’s response utilities to enforce safe formatting:
from fastapi.responses import JSONResponse
@app.get('/report/{event_id}')
async def get_report(event_id: str):
doc = db.collection('events').document(event_id).get()
if not doc.exists:
return JSONResponse({'error': 'Not found'}, status_code=404)
data = doc.to_dict()
# Echo sanitized header value in a custom header safely
response = JSONResponse(content=data)
response.headers['X-Event-Source'] = data.get('referer', 'unknown')
return response
For applications using the middleBrick CLI to monitor security posture, you can integrate scans into your workflow with: middlebrick scan <url>. The dashboard and Pro plan continuous monitoring can help track changes in security scores over time, ensuring that header handling remains compliant with frameworks like OWASP API Top 10 and GDPR. The GitHub Action can fail builds if risk scores degrade, while the MCP Server allows scanning directly from AI coding assistants to catch issues early.
Additionally, enforce strict schema validation for Firestore documents to reject unexpected header-derived fields. Use Pydantic models in Fastapi to define allowed fields and types, ensuring that even if headers are sanitized, they conform to expected structures before being written to Firestore.
Frequently Asked Questions
How can I test if my Fastapi + Firestore app is vulnerable to Header Injection?
X-Custom: value\r\nSet-Cookie: test=1) and inspect Firestore documents and responses. If headers are stored raw or reflected without sanitization, the app is vulnerable.