HIGH use after freeaxumfirestore

Use After Free in Axum with Firestore

Use After Free in Axum with Firestore — how this specific combination creates or exposes the vulnerability

A Use After Free (UAF) occurs when memory is deallocated but remains referenced and subsequently accessed. In an Axum application that uses the Firebase Admin SDK to interact with Firestore, UAF can arise from unsafe handling of Firestore objects—such as DocumentReference, Query, and client handles—across asynchronous tasks or threads without proper ownership tracking.

Consider an Axum handler that creates a Firestore client, runs a query, and then drops or moves the client while an async operation is still in flight. Because Axum handlers are often async and may spawn tasks or use multi-threaded runtimes, a Firestore object captured by a closure can be dropped prematurely if the handler logic or shared state (e.g., an Arc) incorrectly manages lifetimes. When the runtime later attempts to read from or mutate that object, the memory may have been reallocated, leading to undefined behavior or data corruption.

For example, suppose a handler captures a Firestore DocumentReference by value inside a spawned Tokio task, but the handler’s surrounding state or the SDK’s internal references are dropped before the task completes. If the runtime does not guarantee that the Firestore object remains valid for the entire task lifetime, accessing it later may result in a UAF. This is particularly risky when using raw pointers or FFI boundaries between Rust and the Firestore C++ SDK under the hood.

Another scenario involves caching Firestore query results in application state without pinning the associated Firestore objects. If the cached entry outlives the original client or session and is later used to construct new operations, the underlying Firestore references may have been freed. Axum’s per-request state sharing via Data<Arc<...>> requires careful lifetime management to avoid such mismatches.

These issues map to the broader API security checks performed by middleBrick, which tests for unsafe consumption patterns and input validation weaknesses that could exacerbate memory safety risks. While middleBrick does not perform source code analysis, its runtime scans can detect anomalous behavior—such as unexpected crashes or malformed responses—that may indicate underlying memory safety problems when interacting with Firestore.

Additionally, because middleBrick includes checks for SSRF and Unsafe Consumption, it can help identify endpoints that improperly handle Firestore-bound requests, potentially triggering or worsening UAF conditions through malformed input or aggressive concurrency.

Firestore-Specific Remediation in Axum — concrete code fixes

To prevent Use After Free in Axum when working with Firestore, ensure that all Firestore objects have clear ownership and lifetime guarantees. Prefer sharing lightweight, thread-safe handles (e.g., Arc) and avoid capturing raw references across async boundaries unless you can guarantee the referenced object lives long enough.

1. Use Arc to share Firestore clients safely

Initialize the Firestore client once and wrap it in an Arc, then clone the Arc into each handler or spawned task. This ensures the client and its internal Firestore references remain valid for the entire application lifecycle.

use axum::{routing::get, Router};
use std::sync::Arc;
use firebase_admin_rs::Firestore;

struct AppState {
    db: Arc<Firestore>,
}

#[tokio::main]
async fn main() {
    let db = Arc::new(Firestore::new().expect("Failed to initialize Firestore"));
    let state = AppState { db };

    let app = Router::new()
        .route("/doc/:id", get(get_document))
        .with_state(Arc::new(state));

    axum::Server::bind(&("0.0.0.0:3000").parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn get_document(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
) -> String {
    let doc_ref = state.db.doc(&format!("items/{}", id));
    // Safe: doc_ref is tied to the long-lived Arc<Firestore>
    match doc_ref.get().await {
        Ok(doc) => format!("{:?}", doc),
        Err(e) => format!("Error: {}", e),
    }
}

2. Avoid moving Firestore objects into long-running tasks without synchronization

If you must spawn a background task, clone the Arc and move the clone into the task. Do not move raw Firestore objects or references that may be dropped prematurely.

use std::sync::Arc;
use tokio::spawn;

async fn schedule_task(db: Arc<Firestore>, doc_id: String) {
    let db_clone = Arc::clone(&db);
    spawn(async move {
        let doc_ref = db_clone.doc(&format!("logs/{}/", doc_id));
        let _ = doc_ref.set(&serde_json::json!({ "status": "done" })).await;
    });
}

3. Validate inputs before constructing Firestore references

Ensure that any user input used to build Firestore paths is sanitized and validated to prevent malformed references that could lead to unexpected behavior during object resolution.

use axum::extract::Query;
use serde::Deserialize;

#[derive(Deserialize)]
struct DocParams {
    id: String,
}

async fn safe_get_document(Query(params): Query<DocParams>) -> String {
    if params.id.contains("/") || params.id.is_empty() {
        return "Invalid document ID".to_string();
    }
    let db = Firestore::new().unwrap();
    let doc_ref = db.doc(&format!("items/{}", params.id));
    match doc_ref.get().await {
        Ok(doc) => format!("{:?}", doc),
        Err(e) => format!("Error: {}", e),
    }
}

By combining these patterns—proper lifetime management via Arc, careful task spawning, and input validation—you reduce the risk of Use After Free when integrating Axum with Firestore. These practices align with the runtime checks performed by middleBrick, such as Input Validation and Unsafe Consumption, helping ensure that API interactions remain stable and secure.

Frequently Asked Questions

How can I detect Use After Free vulnerabilities in my Axum + Firestore API without source code analysis?
Use runtime scanning tools like middleBrick, which tests endpoints for unsafe consumption patterns and input validation issues. Provide your API URL to receive a security risk score and prioritized findings, including indicators that may suggest memory safety problems when Firestore objects are mishandled across async contexts.
Does middleBrick help prevent Use After Free in Axum applications?
middleBrick detects and reports potential issues such as unsafe consumption and improper input validation that can contribute to Use After Free conditions. It does not fix or patch code; it provides findings with remediation guidance to help you address unsafe patterns in your Axum + Firestore integration.