GuardAPI Logo
GuardAPI
GuardAPI Logo GuardAPI

Fix SQL Injection (Legacy & Modern) in Actix Web

SQLi in Actix Web is a critical failure. Whether you're using legacy synchronous drivers or modern async crates like sqlx, concatenating user-controlled strings into raw SQL allows attackers to hijack the query logic, leak the entire database, or escalate to RCE. We fix this by enforcing a strict separation between the SQL command and the data via prepared statements and compile-time checked macros.

The Vulnerable Pattern

use actix_web::{get, web, Responder};
use sqlx::PgPool;

#[get(“/user/{username}”)] async fn get_user_vulnerable(pool: web::Data, name: web::Path) -> impl Responder { // DANGER: String interpolation creates a raw query string. // Payload: ’ OR ‘1’=‘1 let query = format!(“SELECT * FROM users WHERE username = ’{}’”, name); let row = sqlx::query(&query).fetch_one(pool.get_ref()).await; match row { Ok() => “User found”, Err() => “Error” } }

The Secure Implementation

The vulnerable code uses 'format!' to build a SQL string, allowing an attacker to inject control characters (like single quotes) to alter the query's AST. The secure version uses 'sqlx::query!', which utilizes prepared statements ($1, $2, etc.). In this model, the database engine compiles the SQL template first and treats the user input strictly as a literal value, never as executable code. Furthermore, the sqlx macro validates the query against your live database schema at compile-time, providing both security and type safety.

use actix_web::{get, web, Responder};
use sqlx::PgPool;

#[get(“/user/{username}”)] async fn get_user_secure(pool: web::Data, name: web::Path) -> impl Responder { // SECURE: Use parameterized queries. Data is sent separately from the command. // For modern sqlx, use the query! macro for compile-time syntax and type checking. let row = sqlx::query!(“SELECT username FROM users WHERE username = $1”, name.into_inner()) .fetch_one(pool.get_ref()) .await;

match row {
    Ok(_) => "User found",
    Err(_) => "Error"
}

}

System Alert • ID: 4759
Target: Actix Web API
Potential Vulnerability

Your Actix Web API might be exposed to SQL Injection (Legacy & Modern)

74% of Actix Web apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.