Cross Site Request Forgery in Firestore
How Cross Site Request Forgery Manifests in Firestore
Cross Site Request Forgery (CSRF) in Firestore environments exploits the trust that Firestore has in authenticated requests from the client's browser. Unlike traditional web applications where CSRF often targets session-based authentication, Firestore's client-side SDKs present unique attack vectors that developers frequently overlook.
The most common Firestore CSRF scenario occurs when developers initialize the Firebase Admin SDK on the client side or use client-side authentication without proper anti-CSRF measures. An attacker can craft a malicious page that, when visited by an authenticated user, triggers Firestore operations without their knowledge or consent.
// Vulnerable Firestore code - no CSRF protection
const firebaseConfig = {
apiKey: 'AIza...',
authDomain: 'your-app.firebaseapp.com',
projectId: 'your-app'
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
// This endpoint is vulnerable to CSRF
app.post('/updateProfile', async (req, res) => {
await db.collection('users').doc(req.user.uid).update({
email: req.body.email
});
res.send('Profile updated');
});In this pattern, an attacker can create a hidden form or JavaScript that automatically submits requests to the Firestore backend. Since the victim's browser automatically includes their Firebase authentication token with any request to your domain, the malicious request executes with the victim's privileges.
Firestore-specific CSRF attacks often target:
- Document writes that escalate user privileges or modify sensitive data
- Collection deletions that destroy user data
- Security rule bypasses through crafted requests
- Storage operations that upload malicious content
- Real-time listeners that exfiltrate data
The attack becomes particularly dangerous when combined with Firestore's security rules. If rules allow write access based on client-side conditions that can be manipulated, CSRF can bypass intended restrictions entirely.
Firestore-Specific Detection
Detecting CSRF vulnerabilities in Firestore requires examining both the client-side initialization patterns and server-side request handling. middleBrick's black-box scanning approach is particularly effective for identifying these issues without requiring source code access.
Key detection patterns for Firestore CSRF include:
- Client-side Firebase initialization with API keys exposed in frontend code
- Missing anti-CSRF tokens in state-changing Firestore operations
- Authentication flows that don't verify request origin
- Security rules that rely on client-side data without server-side validation
- Real-time listeners that can be hijacked through malicious requests
middleBrick scans for these patterns by analyzing the unauthenticated attack surface of your Firestore endpoints. The scanner tests for common CSRF vectors including form submissions, AJAX requests, and real-time connection hijacking attempts.
// middleBrick scan output example
{
"csrf_vulnerabilities": [
{
"endpoint": "/api/updateUser",
"severity": "high",
"description": "Missing anti-CSRF token in state-changing request",
"remediation": "Implement double-submit cookie pattern or SameSite cookies",
"affected_rules": ["OWASP API Top 10: A10 - Insufficient Logging & Monitoring"]
}
]
}The scanner also examines your Firestore security rules configuration to identify patterns that could be exploited through CSRF attacks. Rules that allow writes based on client-provided data or that don't properly validate request context are flagged as high-risk.
For comprehensive protection, middleBrick's continuous monitoring (Pro plan) can detect when new CSRF vulnerabilities are introduced through code changes, automatically scanning your staging environment before deployment.
Firestore-Specific Remediation
Securing Firestore against CSRF requires a multi-layered approach that combines proper Firebase configuration, server-side validation, and anti-CSRF mechanisms. The most effective strategy depends on your application architecture and authentication patterns.
For client-side Firebase applications, implement these Firestore-specific protections:
// Secure Firestore initialization
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: 'your-app.firebaseapp.com',
projectId: 'your-app'
};
// Initialize only after authentication
firebase.initializeApp(firebaseConfig);
// Implement anti-CSRF token validation
function generateCSRFToken() {
return crypto.randomBytes(32).toString('hex');
}
// Store token in httpOnly cookie and provide to client
app.post('/generateCSRF', (req, res) => {
const csrfToken = generateCSRFToken();
res.cookie('csrfToken', csrfToken, {
httpOnly: true,
secure: true,
sameSite: 'strict'
});
res.json({ csrfToken });
});For server-side Firestore operations, use Firebase Admin SDK with proper authentication context:
// Secure server-side Firestore operations
const admin = require('firebase-admin');
admin.initializeApp();
// Validate anti-CSRF token before any write operation
app.post('/updateProfile', async (req, res) => {
// Verify CSRF token
if (req.cookies.csrfToken !== req.body.csrfToken) {
return res.status(403).send('CSRF validation failed');
}
// Verify user identity and permissions
const user = await admin.auth().verifyIdToken(req.headers.authorization);
// Use server-side context for Firestore operations
const db = admin.firestore();
// Validate request data before write
if (!isValidProfileUpdate(req.body)) {
return res.status(400).send('Invalid data');
}
await db.collection('users').doc(user.uid).update({
email: req.body.email
});
res.send('Profile updated');
});Additional Firestore-specific security measures include:
- Using Firebase Authentication's session cookies with SameSite attributes
- Implementing custom claims for granular permission control
- Using Firestore security rules that validate request context and data integrity
- Rate limiting write operations to prevent automated CSRF attacks
- Implementing audit logging for all state-changing operations
middleBrick's CLI tool can help validate your remediation efforts by scanning your API endpoints after implementing these protections, ensuring no CSRF vulnerabilities remain.