Dns Rebinding in Fastapi with Firestore
Dns Rebinding in Fastapi with Firestore — how this specific combination creates or exposes the vulnerability
DNS Rebinding is an application-layer attack where an attacker forces a victim’s browser to resolve a domain to an internal IP address that the application trusts. In a Fastapi service that integrates with Firestore, this can bypass source-IP based restrictions and allow an authenticated browser session to interact with internal or restricted Firestore endpoints that are normally considered private.
Consider a Fastapi endpoint that uses the Firestore client to read or write data based on user-supplied document paths. If the endpoint trusts the request origin only by session or token, but does not enforce strict host or network validation, an attacker can craft a malicious page that causes the browser to send requests to the Fastapi service. The service, running in a cloud environment with access to Firestore service accounts, may propagate those requests to Firestore without additional network checks.
For example, an internal Firestore rule or IAM binding that allows the service account full access is leveraged by the Fastapi backend. The attacker does not need to compromise Firestore directly; they abuse the Fastapi service as a proxy. The browser’s same-origin policy can be bypassed via rebinding because the victim is authenticated to Fastapi (e.g., via session cookie or bearer token). The Fastapi app then executes Firestore operations with the app’s elevated privileges, leading to unauthorized reads or writes, enumeration of collections, or data exfiltration.
With OpenAPI/Swagger analysis, middleBrick correlates the unauthenticated attack surface with runtime behavior. Even without credentials, scanning can reveal endpoints that accept resource identifiers and forward them to Firestore. If those endpoints do not validate or sanitize host references, DNS Rebinding becomes a viable vector to pivot from the public API surface to internal data stores. The scanner checks input validation and property authorization to highlight where user-controlled identifiers can influence backend Firestore calls, emphasizing the need for explicit allowlists and origin verification.
Firestore-Specific Remediation in Fastapi — concrete code fixes
To mitigate DNS Rebinding in a Fastapi application that uses Firestore, enforce strict validation of all identifiers that influence Firestore operations. Never trust hostnames, Referrer headers, or origin headers for access control. Instead, validate resource ownership and use parameterized queries with strict allowlists.
Below is a secure Fastapi pattern using the Firestore Python client. The example validates a document ID against a strict regex, ensures the requesting user has permission to access the document, and uses explicit parameterization rather than string concatenation to build document references.
from fastapi import Fastapi, Depends, HTTPException, Header
from google.cloud import firestore
import re
app = Fastapi()
db = firestore.Client()
def get_current_user_token(x_api_key: str = Header(...)):
# Replace with real auth logic (e.g., verify session or JWT)
if x_api_key != "VALID_API_KEY":
raise HTTPException(status_code=401, detail="Invalid token")
return {"uid": "test_user"}
def is_valid_document_id(doc_id: str) -> bool:
# Allow only alphanumeric and underscores, 1–64 chars
return re.fullmatch(r"[A-Za-z0-9_]{1,64}", doc_id) is not None
@app.get("/documents/{doc_id}")
def read_document(
doc_id: str,
user: dict = Depends(get_current_user_token)
):
if not is_valid_document_id(doc_id):
raise HTTPException(status_code=400, detail="Invalid document ID")
# Use parameterization; never build paths via string formatting with user input
doc_ref = db.collection("user_data").document(doc_id)
doc = doc_ref.get()
if not doc.exists:
raise HTTPException(status_code=404, detail="Document not found")
# Ensure the document belongs to the requesting user
if doc.get("user_id") != user["uid"]:
raise HTTPException(status_code=403, detail="Access denied")
return {"id": doc.id, "data": doc.to_dict()}
Key remediation points specific to Fastapi and Firestore:
- Validate all path and query parameters with strict allowlists before using them in Firestore document references.
- Use Firestore’s native document IDs or parameterized collection/document paths; avoid concatenating user input into resource paths.
- Enforce per-request authorization checks in Fastapi dependencies to confirm the authenticated user has access to the target document, even when the service account has broad Firestore permissions.
- Set Firestore security rules to enforce ownership and least privilege; do not rely solely on Fastapi-side checks.
- For endpoints that expose Firestore data via queries, reject requests with unexpected Host headers and prefer explicit resource identifiers over inferred paths.
middleBrick’s scanning approach includes checks for input validation and property authorization. By correlating OpenAPI specs with runtime findings, it highlights endpoints where user-controlled data can affect Firestore calls, helping you identify places where DNS Rebinding or similar injection techniques could be leveraged.