Distributed Denial Of Service in Firestore
How Distributed Denial Of Service Manifests in Firestore
Distributed Denial of Service (DDoS) attacks on Firestore exploit the service's scalability and real-time capabilities to overwhelm your application's data layer. Unlike traditional web DDoS attacks that flood network connections, Firestore DDoS attacks target your database operations, query patterns, and resource consumption limits.
Firestore DDoS attacks typically manifest through several attack vectors:
- Query Flooding: Attackers send massive numbers of read queries that each trigger full collection scans or deep nested queries, consuming your quota and blocking legitimate requests
- Write Storms: Coordinated writes that trigger expensive Cloud Functions or batch operations, causing cascading resource exhaustion
- Document Enumeration: Sequential document ID guessing or wildcard queries that force Firestore to scan entire collections
- Real-time Connection Hijacking: Opening thousands of simultaneous real-time listeners that consume connection pool resources
- Recursive Data Traversal: Queries that follow references or subcollections recursively, causing exponential query growth
The most dangerous aspect of Firestore DDoS is that legitimate-looking requests can trigger massive backend costs. A single poorly designed query can consume thousands of document reads, and when scaled across multiple attackers, this becomes catastrophic.
Consider this vulnerable pattern:
const usersRef = db.collection('users');
const query = usersRef.where('lastLogin', '>', new Date());
const snapshot = await query.get();
If an attacker can manipulate the lastLogin timestamp or force this query to run frequently, each execution might scan millions of documents, consuming your entire daily quota in minutes.
Firestore-Specific Detection
Detecting DDoS attacks in Firestore requires monitoring both your application logs and Firestore's built-in metrics. The service provides detailed usage statistics through Cloud Monitoring, but you need to know what patterns indicate attack activity.
Key detection signals include:
| Metric | Normal Range | Attack Indicator |
|---|---|---|
| Document Reads | Steady baseline | Sudden spikes (10x+ baseline) |
| Document Writes | Predictable patterns | Unexplained write storms |
| Concurrent Connections | Within expected limits | Connection pool exhaustion |
| Query Latency | Consistent response times | Gradual degradation |
middleBrick's Firestore-specific scanning identifies DDoS vulnerabilities by analyzing your API endpoints' query patterns and authentication controls. The scanner tests for:
- Authentication bypass: Can unauthenticated users trigger expensive queries?
- Rate limiting gaps: Are there endpoints without request throttling?
- Query complexity: Do your endpoints allow potentially expensive operations?
- Input validation: Can attackers manipulate query parameters to cause denial of service?
The scanner executes black-box tests that simulate common DDoS patterns without requiring access to your Firestore configuration. For example, it tests whether your endpoints properly handle rapid sequential requests or whether query parameters can be manipulated to force full collection scans.
Real-time monitoring setup with Cloud Monitoring:
resources: [
{type: 'cloud_monitoring_alert_policy',
name: 'firestore-ddos-alert',
properties: {
combiner: 'OR',
conditions: [
{displayName: 'High read rate',
conditionThreshold: {
filter: 'metric.type="firestore.googleapis.com/reads"',
comparison: 'COMPARISON_GT',
thresholdValue: 1000,
duration: '60s'
}},
{displayName: 'High write rate',
conditionThreshold: {
filter: 'metric.type="firestore.googleapis.com/writes"',
comparison: 'COMPARISON_GT',
thresholdValue: 500,
duration: '60s'
}}
]
}}
]Firestore-Specific Remediation
Securing Firestore against DDoS attacks requires a defense-in-depth approach combining query optimization, authentication controls, rate limiting, and monitoring. The most effective strategy addresses vulnerabilities at multiple layers.
Query Optimization
Design your queries to minimize document reads and prevent full collection scans:
// BAD: Potential full collection scan
const users = await db.collection('users')
.where('status', '==', 'active')
.get();
// GOOD: Indexed query with limit
const users = await db.collection('users')
.where('status', '==', 'active')
.where('lastLogin', '>', thresholdDate)
.limit(100)
.get();
Authentication and Authorization
Implement proper access controls to prevent unauthenticated access to expensive operations:
const admin = require('firebase-admin');
const validateFirebaseIdToken = async (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({error: 'Unauthorized'});
}
try {
const decodedToken = await admin.auth().verifyIdToken(token);
req.user = decodedToken;
next();
} catch (error) {
return res.status(401).json({error: 'Invalid token'});
}
};
Rate Limiting Implementation
Apply rate limiting at the API gateway level to prevent request flooding:
const rateLimit = require('express-rate-limit');
const firestoreRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per window
message: 'Too many requests from this IP, please try again later.',
req.user?.uid || req.ip,
Query Cost Analysis
Estimate query costs before execution to prevent expensive operations:
async function safeQuery(collectionRef, queryOptions) {
const query = collectionRef.where(...queryOptions.where);
const estimatedCost = await query.estimateReadTime();
if (estimatedCost > 1000) { // 1000 document reads threshold
throw new Error('Query too expensive');
return await query.get();
}
Monitoring and Alerting
Set up automated alerts for unusual activity patterns:
const monitoring = require('@google-cloud/monitoring');
async function setupDdosAlerts() {
const client = new monitoring.MetricServiceClient();
// Alert if read operations exceed threshold
await client.createAlertPolicy({
name: 'projects/YOUR_PROJECT_ID',
alertPolicy: {
displayName: 'Firestore DDoS Alert',
conditions: [
{
displayName: 'High read rate',
conditionThreshold: {
filter: 'metric.type=