HIGH prototype pollutionaxumfirestore

Prototype Pollution in Axum with Firestore

Prototype Pollution in Axum with Firestore — how this specific combination creates or exposes the vulnerability

Prototype pollution in an Axum application that interacts with Google Cloud Firestore occurs when user-controlled input is merged into objects that later influence behavior, property lookup, or data construction before being used with Firestore operations. Axum does not sanitize incoming JSON payloads by default; if route extractors or handlers directly merge user data into maps or structs that are later serialized or used to build Firestore document paths or field keys, an attacker can introduce properties such as __proto__, constructor.prototype, or other inherited properties that affect runtime behavior.

Because Firestore client libraries typically accept maps or dynamically built objects for document sets and updates, polluted prototypes can propagate into document field names, query constraints, or metadata. For example, if an Axum handler builds a Firestore document map from request JSON without deep copying or validation, an injected property could change field paths, affect upsert behavior, or cause unexpected type coercion when the document is written. This can lead to data integrity issues or unauthorized field manipulation. Additionally, Firestore security rules that rely on document field values may be bypassed if pollution affects how data is structured prior to rule evaluation.

The risk is compounded when Axum endpoints expose unauthenticated or weakly authenticated routes that accept POST/PUT/PATCH with JSON bodies. An attacker can chain prototype pollution attempts with Firestore-specific behaviors—such as map key interpretation or server-side timestamps—to achieve unintended document updates or metadata corruption. While Axum itself is not responsible for data correctness, the integration pattern of directly forwarding user input into Firestore document operations creates a conduit for prototype pollution to affect backend data handling.

In practice, this means an API tested by middleBrick might surface findings related to Input Validation and Property Authorization when pollution vectors are detected in endpoints that write to Firestore. The scanner does not fix the code, but it highlights where untrusted input reaches Firestore-bound structures, enabling developers to apply strict deserialization controls, schema validation, and deep cloning before any Firestore client call.

Firestore-Specific Remediation in Axum — concrete code fixes

To prevent prototype pollution when using Firestore with Axum, ensure all incoming data is validated, deeply cloned, and never directly merged into maps or objects that are passed to Firestore operations. Use strongly typed structures and avoid dynamic key assignment based on user input.

1. Use strongly typed structs and serde deserialization

Define explicit structs for incoming payloads and rely on serde to deserialize into these types. This prevents arbitrary keys from polluting object prototypes.

use axum::extract::Json;
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
struct CreateUser {
    email: String,
    display_name: String,
    // Do not allow arbitrary fields
}

async fn create_user(Json(payload): Json<CreateUser>) -> String {
    // Safe: payload is strictly typed
    format!("Creating user: {}", payload.email)
}

2. Deep clone and sanitize before Firestore operations

When you must work with dynamic maps, deep clone the data and remove or ignore prototype-sensitive keys before constructing Firestore documents.

use firestore::FirestoreDb;
use std::collections::HashMap;

fn sanitize_for_firestore(input: HashMap<String, serde_json::Value>) -> HashMap<String, serde_json::Value> {
    let mut clean = HashMap::new();
    for (k, v) in input {
        // Reject keys that could pollute prototypes
        if k == "__proto__" || k == "constructor" || k == "prototype" {
            continue;
        }
        clean.insert(k, v);
    }
    clean
}

// Example usage within an Axum handler
async fn update_document(
    db: Extension<FirestoreDb>,
    Json(body): Json<HashMap<String, serde_json::Value>>
) -> String {
    let clean_body = sanitize_for_firestore(body);
    db.create_doc("users", &clean_body).await.unwrap();
    "ok".to_string()
}

3. Validate field names and values explicitly for Firestore

Firestore has constraints on field names and value types. Validate keys against a denylist that includes prototype-related strings and ensure values conform to expected schemas.

fn validate_firestore_field_name(key: &str) -> bool {
    let denylist = ["__proto__", "constructor", "prototype", "__class__", "__lookupGetter__"];
    !denylist.contains(&key)
}

fn build_firestore_document(updates: HashMap<String, String>) -> Result<HashMap<String, String>, &'static str> {
    let mut doc = HashMap::new();
    for (k, v) in updates {
        if !validate_firestore_field_name(&k) {
            return Err("Invalid field name");
        }
        doc.insert(k, v);
    }
    Ok(doc)
}

These patterns ensure that user input never directly influences Firestore document structure in a way that could be abused through prototype pollution. Combine these practices with middleBrick’s checks for Input Validation and Property Authorization to confirm that your endpoints are resilient against such attacks.

Frequently Asked Questions

Can middleBucket detect prototype pollution in Axum endpoints that write to Firestore?
middleBucket scans unauthenticated attack surfaces and tests input handling; it can identify patterns consistent with prototype pollution in Axum routes that interact with Firestore, but it does not fix the code. You must apply strict deserialization and field-name validation as shown in the remediation examples.
Does Firestore itself prevent prototype pollution on the server side?
Firestore does not protect against prototype pollution introduced by client-side logic or API handlers. Pollution occurs in the application layer before data reaches Firestore, so validation and sanitization must be enforced in Axum handlers and data transformation code.