GuardAPI Logo
GuardAPI

Fix SQL Injection (Legacy & Modern) in Rocket

Rocket's memory safety doesn't protect you from logical failures. If you are concatenating raw strings into SQL queries, you're handing over your database to any script kiddie with a single quote. Even in Rust, SQL injection remains a critical vulnerability when developers bypass type-safe abstractions for 'convenience'.

The Vulnerable Pattern

#[get("/search?")]
async fn search(mut db: Connection, query: String) -> Option>> {
    // DANGER: String interpolation creates a classic SQLi vector
    let sql = format!("SELECT * FROM users WHERE username = '{}'", query);
    let users = sqlx::query_as::<_, User>(&sql)
        .fetch_all(&mut **db).await.ok()?;
    Some(Json(users))
}

The Secure Implementation

The legacy approach failed because it treated user input as part of the executable SQL command. By using 'format!', an attacker could input "' OR 1=1 --" to bypass authentication. The modern Rocket/sqlx approach uses prepared statements. By using the '$1' placeholder and the '.bind()' method, the SQL engine compiles the query structure first, then treats the input strictly as data. For maximum security, leverage Diesel's type-safe DSL or sqlx's compile-time macros (query!) which validate your SQL against the schema at build time.

#[get("/search?")]
async fn search(mut db: Connection, query: String) -> Option>> {
    // SECURE: Use parameterized queries. The driver handles escaping.
    let users = sqlx::query_as::<_, User>("SELECT * FROM users WHERE username = $1")
        .bind(query)
        .fetch_all(&mut **db).await.ok()?;
    Some(Json(users))
}
System Alert • ID: 7419
Target: Rocket API
Potential Vulnerability

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

74% of Rocket 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.