Fix SQL Injection (Legacy & Modern) in Axum
Axum's performance profile is elite, but memory safety doesn't protect you from logical vulnerabilities like SQL Injection. If you are concatenating strings to build queries, you are handing over your database keys to any script kiddie with a single quote. In Rust, we leverage type-safe drivers like sqlx to neutralize this threat at the source.
The Vulnerable Pattern
async fn get_user_vulnerable(Path(id): Path, State(pool): State) -> impl IntoResponse {
// DANGER: String interpolation is an instant injection vector
let query = format!("SELECT username, email FROM users WHERE id = '{}'", id);
let row = sqlx::query(&query).fetch_one(&pool).await.unwrap();
Json(row)
}
The Secure Implementation
The vulnerable example uses 'format!' to build a query string, allowing an attacker to break out of the quote and execute arbitrary SQL (e.g., id = "' OR '1'='1"). The secure version uses prepared statements via the '$1' placeholder. This ensures the database driver treats the input strictly as data, not executable code. By using the 'sqlx::query!' macro, you also get the 'Modern' benefit of compile-time SQL checking, where the compiler validates your query syntax and types against your actual database schema during the build process.
async fn get_user_secure(Path(id): Path, State(pool): State ) -> Result , StatusCode> { // MODERN: Using the sqlx macro for compile-time verified, parameterized queries let user = sqlx::query_as!(User, "SELECT username, email FROM users WHERE id = $1", id) .fetch_one(&pool) .await .map_err(|_| StatusCode::NOT_FOUND)?; Ok(Json(user))
}
Your Axum API
might be exposed to SQL Injection (Legacy & Modern)
74% of Axum apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.