Path Traversal in Actix with Cockroachdb
Path Traversal in Actix with Cockroachdb — how this specific combination creates or exposes the vulnerability
Path Traversal occurs when an API endpoint uses user-supplied input to construct file paths or database queries without proper validation, allowing an attacker to access unauthorized resources. In an Actix web service that uses Cockroachdb as the backend, this risk is amplified when dynamic path components (e.g., filenames, object keys, or tenant identifiers) are directly interpolated into SQL statements or filesystem operations.
Consider an endpoint that retrieves a user's document by ID: /documents/{file_id}. If the Actix handler constructs a Cockroachdb query by concatenating file_id into the SQL string without parameterization, an attacker can provide inputs like 1; -- or ../../../etc/passwd depending on how the application interprets the input. While Cockroachdb supports standard SQL syntax, improper handling of identifiers or string values can enable injection or path traversal when combined with unsafe Actix routing and deserialization logic.
In a typical Actix implementation, the handler might parse path parameters into a struct and then use those values in a SQLx or diesel query. If the developer mistakenly treats a logical identifier (such as a document slug) as a filesystem path—for example, to build a local file path for serving assets—unsanitized input can traverse directory boundaries. This becomes especially dangerous when the application runs with elevated filesystem permissions or when the database user has broader schema access than necessary.
Moreover, if the API exposes endpoint routes that mirror storage paths (e.g., /storage/{tenant}/{year}/{month}/{file}), and these segments are directly used in Cockroachdb queries without normalization, attackers can exploit directory traversal sequences to reference other tenants' data. Even when using parameterized queries, incorrect usage of identifiers (such as table or column names) via string concatenation can bypass prepared statement protections, enabling unauthorized data access or schema enumeration.
middleBrick detects such risks during black-box scanning by analyzing the OpenAPI spec for path definitions and correlating them with runtime behavior. It checks for missing input validation, improper use of identifiers, and patterns that could allow unauthorized access across logical boundaries. This is particularly relevant when integrating with LLM-related endpoints, where unchecked inputs may also expose system prompts or sensitive logic.
Cockroachdb-Specific Remediation in Actix — concrete code fixes
To mitigate Path Traversal in Actix applications using Cockroachdb, always treat user input as untrusted and enforce strict separation between identifiers and values. Use parameterized SQL queries with SQLx or diesel, and avoid constructing queries via string interpolation. Validate and sanitize path parameters before using them in any database or filesystem operation.
Below are concrete, safe patterns for handling file or record identifiers in Actix with Cockroachdb.
1. Parameterized SQL with SQLx
Use SQLx's compile-time verified queries to ensure that user input is never directly concatenated into SQL strings.
use actix_web::{web, HttpResponse};
use sqlx::PgPool;
async fn get_document(
pool: web::Data,
path: web::Path<(i32,)>,
) -> Result {
let (document_id,) = path.into_inner();
// Safe: parameter binding prevents injection and path traversal
let row = sqlx::query!(
"SELECT id, title, content FROM documents WHERE id = $1",
document_id
)
.fetch_one(pool.as_ref())
.await?;
Ok(HttpResponse::Ok().json(row))
} 2. Identifier Validation for Dynamic Schema or Table Names
If you must use dynamic identifiers (e.g., tenant-specific tables), validate them against a strict allowlist or regex before interpolation. Never pass raw user input into identifier positions.
use actix_web::{web, HttpResponse};
use sqlx::PgPool;
async fn get_tenant_data(
pool: web::Data,
web::Path(tenant_id): web::Path,
) -> Result {
// Validate tenant_id to prevent injection
if !tenant_id.chars().all(|c| c.is_alphanumeric() || c == '_') {
return Ok(HttpResponse::BadRequest().body("invalid tenant identifier"));
}
// Safe: identifier is validated, value is still parameterized
let table_name = format!("tenant_data_{}", tenant_id);
let rows = sqlx::query(&format!(
"SELECT data FROM {} WHERE deleted = $1",
table_name
))
.bind(false)
.fetch_all(pool.as_ref())
.await?;
Ok(HttpResponse::Ok().json(rows))
} 3. Filesystem Operations: Use Basename Extraction
If serving files based on database records, derive paths from database-stored locations rather than user input. When constructing paths, use Rust's std::path::Path to normalize and restrict traversal.
use actix_files::NamedFile;
use actix_web::web;
use std::path::Path;
async fn serve_file(path: web::Path) -> Result {
let requested = path.into_inner();
// Only allow alphanumeric filenames to prevent traversal
if !requested.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_') {
return Err(actix_web::error::ErrorBadRequest("invalid filename"));
}
let base = Path::new("/safe/uploads");
let full_path = base.join(requested);
// Ensure the resolved path remains within the base directory
if full_path.strip_prefix(base).is_err() {
return Err(actix_web::error::ErrorForbidden("access denied"));
}
NamedFile::open(full_path)
} These patterns ensure that user input never directly controls filesystem paths or SQL identifiers. By combining strict validation, parameterized queries, and safe path handling, you reduce the risk of Path Traversal and related injection attacks in Actix services backed by Cockroachdb.
middleBrick can help identify missing validations and unsafe patterns during scans, especially when OpenAPI specs include path templates that could be misused. For long-term security, consider integrating the CLI into development workflows or using the GitHub Action to enforce checks in CI/CD pipelines.
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 |