Regex Dos in Actix with Firestore
Regex Dos in Actix with Firestore — how this specific combination creates or exposes the vulnerability
A Regex Denial-of-Service (ReDoS) occurs when a regular expression has overlapping or nested quantifiers that cause catastrophic backtracking on certain inputs. In an Actix web service that uses Firestore, this typically arises when developers validate user-supplied strings (such as document IDs, query parameters, or Firestore path segments) with poorly constructed regex patterns. Actix routes often define path or query extractors that apply regex constraints; if those regexes are vulnerable, an attacker can send a carefully crafted payload that causes the runtime to consume excessive CPU for seconds, leading to a spike in latency or thread starvation.
When Firestore is involved, the interaction adds specific risk patterns. For example, a developer might validate a document ID with a regex to ensure it does not contain disallowed characters, while also constructing a Firestore path dynamically by concatenating user input. If the regex is vulnerable, the attacker can cause the Actix handler to hang during validation, and the subsequent Firestore read or write may still be attempted after the regex passes, increasing the overall impact. Common real-world CVEs affecting regex libraries (such as CVE-2022-42567 in some regex crates) illustrate how pathological inputs can stall servers. In an Actix + Firestore stack, the vulnerability surface includes both the route-level regex checks and any custom validation logic applied before issuing Firestore operations like get or set.
Because middleBrick scans the unauthenticated attack surface and includes checks for Input Validation, a scan can flag vulnerable regex patterns in Actix handlers that interact with Firestore. Findings will highlight the specific regex-related risks and provide remediation guidance. Note that middleBrick detects and reports these issues but does not fix or block requests; it supplies actionable remediation steps so developers can harden their routes and validation logic.
Firestore-Specific Remediation in Actix — concrete code fixes
To mitigate Regex Dos in Actix when working with Firestore, focus on simplifying and bounding regex complexity, avoiding nested quantifiers, and validating inputs with safer primitives before using them in Firestore operations. Below are concrete examples using the Firestore client for Rust (google-cloud-rust or a comparable Firestore SDK) integrated into an Actix handler.
1. Use bounded, non-backtracking patterns or simple prefix checks
Instead of a complex character-class regex, prefer simple length and prefix checks. For document IDs, Firestore allows a limited set of characters; you can enforce rules with straightforward conditions.
use actix_web::{get, web, HttpResponse};
use google_cloud_firestore::client::Client;
/// Safely validate document ID: only alphanumeric, underscore, dash, and dot,
/// with length between 1 and 1024 characters. No nested quantifiers.
fn is_valid_doc_id(id: &str) -> bool {
if id.is_empty() || id.len() > 1024 {
return false;
}
// Simple byte-level check avoids catastrophic backtracking.
id.bytes().all(|b| matches!(b, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-' | b'.'))
}
#[get("/doc/{doc_id}")]
async fn get_doc(
path: web::Path,
client: web::Data,
) -> HttpResponse {
let doc_id = path.into_inner();
if !is_valid_doc_id(&doc_id) {
return HttpResponse::BadRequest().body("Invalid document ID");
}
// Safe Firestore get using the validated ID.
let doc_path = format!("projects/PROJECT_ID/databases/(default)/documents/collection/{}", doc_id);
// Example Firestore get (pseudo-code, adapt to SDK):
// let doc = client.get_document(&doc_path).await;
HttpResponse::Ok().body(format!("Would fetch document: {}", doc_path))
}
2. Avoid regex for path segments; use split and explicit checks
When validating multi-segment paths, split the input and validate each segment individually rather than using a single complex regex that can backtrack.
/// Validate each segment of a Firestore path segment list.
fn validate_segments(segments: &[String]) -> bool {
segments.iter().all(|seg| {
if seg.is_empty() || seg.len() > 256 {
return false;
}
// Allow alphanumeric and a few safe characters.
seg.bytes().all(|b| matches!(b, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-'))
})
}
#[post("/batch")]
async fn batch_write(
payload: web::Json>,
client: web::Data,
) -> HttpResponse {
if !validate_segments(&payload) {
return HttpResponse::BadRequest().body("Invalid segment in path");
}
// Proceed with batched Firestore writes.
HttpResponse::Accepted().body("Batch accepted")
}
3. Sanitize input before concatenating into Firestore paths
Never directly interpolate user input into Firestore resource paths without validation. Use a whitelist approach for collection names and strictly validate document IDs to prevent path traversal or unexpected resource access.
use actix_web::web;
/// Build a Firestore document reference safely.
fn build_doc_ref(collection: &str, doc_id: &str) -> Option {
// Whitelist allowed collections.
const ALLOWED_COLLECTIONS: &[&str] = &["users", "products", "orders"];
if !ALLOWED_COLLECTIONS.contains(&collection) {
return None;
}
if !is_valid_doc_id(doc_id) {
return None;
}
Some(format!("projects/PROJECT_ID/databases/(default)/documents/{}/{}", collection, doc_id))
}
#[get("/item/{collection}/{doc_id}")]
async fn get_item(
path: web::Path<(String, String)>,
client: web::Data,
) -> HttpResponse {
let (collection, doc_id) = path.into_inner();
match build_doc_ref(&collection, &doc_id) {
Some(path) => HttpResponse::Ok().body(format!("Fetching: {}", path)),
None => HttpResponse::BadRequest().body("Invalid collection or document ID"),
}
}
General recommendations
- Prefer length limits and simple character checks over complex regexes.
- Do not rely solely on client-side validation; enforce security rules in Firestore as well.
- Use middleBrick to scan your endpoints and identify regex-related input validation findings; treat its remediation guidance as a starting point for code fixes.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |