HIGH path traversalactixmongodb

Path Traversal in Actix with Mongodb

Path Traversal in Actix with Mongodb — how this specific combination creates or exposes the vulnerability

Path Traversal in an Actix web service that uses Mongodb as a backend can occur when user-controlled path segments are used to build filesystem paths or to construct query filters that indirectly reference stored files or metadata. In this stack, the typical pattern is for an Actix handler to receive a filename or key, look up a document in Mongodb that stores file metadata or a gridfs identifier, and then serve or manipulate the associated resource. If the handler directly concatenates user input into filesystem operations or into tightly coupled query logic without validation, an attacker can traverse directories (e.g., ../../../etc/passwd) or escape intended namespace boundaries in the database references.

For example, consider an endpoint like /files/{name} where the Actix handler looks up a Mongodb collection to retrieve a document by a filename field. If the application uses the raw name to build a filesystem path for reading a file from disk (e.g., joining with a base directory), an attacker can supply ../../../secrets/config.yaml to read arbitrary files. Even if the handler queries Mongodb using the same input to find a document, insufficient sanitization can allow traversal-like behavior if the query relies on exact matches that assume a flat, trusted namespace, enabling confusion between logical paths and physical storage identifiers.

This combination is risky because Mongodb does not inherently understand filesystem path semantics; it stores whatever keys or references the application provides. If the Actix layer does not enforce strict path canonicalization and scope boundaries, an attacker can leverage directory traversal sequences to manipulate application logic, bypass intended access controls, or probe internal data structures. Moreover, if the handler mixes user input between database queries and filesystem operations (e.g., using a database field value as a local path), the risk compounds, because an attacker might indirectly influence filesystem reads/writes via crafted database content.

To detect such issues, scanning tools can examine the Actix route definitions and associated Mongodb query patterns, looking for direct concatenation of user input into filesystem APIs or into database filters that mirror path-like identifiers. They also check whether input validation and normalization are applied consistently. Remediation guidance focuses on strict input validation, path sanitization, scoping document access by user context, and avoiding any filesystem path assembly from untrusted data.

Mongodb-Specific Remediation in Actix — concrete code fixes

Remediation for Path Traversal in Actix with Mongodb centers on decoupling user input from internal paths and enforcing strict scoping for database operations. Do not use raw user input to build filesystem paths; instead, use a controlled mapping from logical identifiers to filesystem locations. When interacting with Mongodb, scope queries with tenant or user identifiers and validate that requested resources belong to the authenticated context.

Below is a secure example in Actix using the official MongoDB Rust driver (mongodb crate). The handler resolves a file by an integer ID rather than a raw filename, preventing path traversal via directory sequences. It also scopes the query to the current user to avoid confused deputy issues:

use actix_web::{web, HttpResponse};
use mongodb::{bson::{doc, oid::ObjectId}, Collection};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
struct FileRecord {
    #[serde(rename = "_id")]
    id: ObjectId,
    user_id: String,
    logical_name: String,
    // other metadata
}

async fn get_file_by_id(
    file_id: web::Path,
    user_info: web::ReqData, // authenticated user id
    files_collection: web::Data>,
) -> HttpResponse {
    let id = match ObjectId::parse_str(&file_id) {
        Ok(oid) => oid,
        Err(_) => return HttpResponse::BadRequest().body("invalid id"),
    };
    let owner = user_info.into_inner();
    let filter = doc! {
        "_id": &id,
        "user_id": owner,
    };
    match files_collection.find_one(filter, None).await {
        Ok(Some(doc)) => HttpResponse::Ok().json(doc),
        Ok(None) => HttpResponse::NotFound().body("not found"),
        Err(_) => HttpResponse::InternalServerError().body("db error"),
    }
}

If you must reference files by a name, map the name to a deterministic, safe location using a whitelist or a hash-based directory structure. For example, store files under user-scoped directories derived from a salted hash of the user ID, and validate that the resolved path stays within the expected base directory:

use std::path::{Path, PathBuf};

fn safe_path(base: &Path, user_id: &str, requested_name: &str) -> Option<PathBuf> {
    // Whitelist approach: accept only alphanumeric names
    if !requested_name.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-') {
        return None;
    }
    let mut dir = PathBuf::from(base);
    // Use user-specific subdirectory to scope storage
    dir.push(user_id);
    if !dir.exists() {
        std::fs::create_dir_all(&dir).ok()?;
    }
    dir.push(requested_name);
    // Ensure the canonicalized path remains within base
    dir.canonicalize().ok().filter(|p| p.starts_with(base))
}

For Mongodb, avoid storing or querying by raw filesystem paths. If you store a key that maps to a file, keep the mapping in a separate collection with proper ownership fields and always join on the database side using user-scoped filters. Never construct queries by string interpolation of user input, and prefer typed queries that enforce schema constraints.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Can middleBrick detect Path Traversal risks in Actix applications that use Mongodb?
Yes. middleBrick scans unauthenticated attack surfaces and includes checks that can identify risky patterns such as concatenating user input into filesystem operations or loosely scoped database queries, helping you find Path Traversal concerns in Actix services that interact with Mongodb.
What remediation does middleBrick recommend for Path Traversal in Actix with Mongodb?
middleBrick reports prioritize findings with severity and remediation guidance, such as using typed IDs instead of raw filenames, scoping Mongodb queries with user context, validating and sanitizing paths, and avoiding constructing filesystem paths from untrusted input. Refer to the scanner output for step-by-step remediation steps aligned with frameworks like OWASP API Top 10.