How to fix SQL Injection (Legacy & Modern)
in Vapor (Swift)
Executive Summary
SQL Injection in Vapor isn't dead; it just hides in poorly implemented raw queries. If you're concatenating strings into your SQL execution context, you're handing over your database keys. While Vapor's Fluent ORM provides a secure layer by default, developers often drop down to raw SQL for performance or complex joins, inadvertently reintroducing classic injection vectors via Swift's string interpolation.
The Vulnerable Pattern
app.get("user") { req -> EventLoopFuture<[User]> in
let username = req.query["name"] ?? ""
// CRITICAL VULNERABILITY: Direct string interpolation into raw SQL
return req.db.raw("SELECT * FROM users WHERE username = '\(username)'")
.all(decoding: User.self)
}
The Secure Implementation
The vulnerability exists because Swift's string interpolation executes before the SQL engine sees the query, allowing an attacker to break the SQL syntax with payloads like "' OR '1'='1". The fix is twofold: 1. Use Fluent's QueryBuilder, which abstracts the SQL generation and uses prepared statements automatically. 2. If raw SQL is required, use SQLKit's `SQLQueryString` with the `bind` interpolation. This ensures the database driver treats the input as a bound parameter (data) rather than executable code, effectively neutralizing the injection vector.
// Option 1: Modern Fluent (Recommended) User.query(on: req.db) .filter(\.$username == username) .all()
// Option 2: Secure Raw SQL (SQLKit Parameterization) req.db.raw(SQLQueryString(“SELECT * FROM users WHERE username = (bind: username)”)) .all(decoding: User.self)
Your Vapor (Swift) API
might be exposed to SQL Injection (Legacy & Modern)
74% of Vapor (Swift) 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.