Answer#
Two cases cannot use a plain placeholder: the name of the column to sort by, and a list of unknown length. Both are solved by assembling SQL from fixed pieces only, never from the user's text.
- Sort column: the user chooses a keyword; your code maps it to a column name with a
match. The text that enters the SQL is one of your own string literals. - IN list: build
?,?,?from the number of values, then bind each value.
use rusqlite::{params_from_iter, Connection};
#[derive(Clone, Copy)]
enum SortBy {
Name,
Created,
}
impl SortBy {
/// Parameters cannot name a column, so map the user's choice onto fixed SQL text.
fn from_user(s: &str) -> SortBy {
match s {
"created" => SortBy::Created,
_ => SortBy::Name, // unknown values fall back to a default, never into the query
}
}
fn column(self) -> &'static str {
match self {
SortBy::Name => "name",
SortBy::Created => "created",
}
}
}
fn main() -> rusqlite::Result<()> {
let db = Connection::open_in_memory()?;
db.execute("CREATE TABLE items (id INTEGER, name TEXT, created INTEGER)", [])?;
db.execute("INSERT INTO items VALUES (1,'pear',30),(2,'apple',20),(3,'fig',10),(4,'kiwi',40)", [])?;
let ids = [1, 3, 4];
// One "?" per value, joined; the values themselves are still bound parameters.
let marks = vec!["?"; ids.len()].join(",");
let sort = SortBy::from_user("created; DROP TABLE items");
let sql = format!("SELECT name FROM items WHERE id IN ({marks}) ORDER BY {}", sort.column());
println!("{sql}");
let mut stmt = db.prepare(&sql)?;
let names: Vec<String> = stmt.query_map(params_from_iter(ids), |r| r.get(0))?.collect::<Result<_, _>>()?;
println!("{names:?}");
Ok(())
}SELECT name FROM items WHERE id IN (?,?,?) ORDER BY name
["fig", "kiwi", "pear"]The input created; DROP TABLE items is the kind of text an attacker sends. It matched nothing in the match, so the default column name was used, and the table is untouched.
How to do it#
- Represent each allowed choice as an enum variant.
- Parse the user's string into the enum (an unknown value gives the default or an error, your decision).
- Turn the enum into a literal column name in one place.
- Make the number of placeholders from the number of values, and refuse lists above a limit (databases have a maximum number of parameters).
- Use the same pattern for the direction (
ASCorDESC): an enum, never the raw string.
Common mistakes#
- Quoting or "sanitising" the user's column name and inserting it. Use the allow-list.
- Building the placeholder list from user data other than its length.
- Forgetting that an empty list gives invalid SQL (
IN ()): handle it before the query.
Related questions#
What about a search with several optional filters?#
Add the fixed AND column = ? fragments you need, one per filter that is present, and bind the values in the same order. The SQL text is still made only of your own pieces.
Can I let users choose several sort columns?#
Yes: accept a list, map each entry through the enum, reject duplicates and limit the length of the list. The SQL still contains only your own column names.
Sources#
- OWASP SQL Injection Prevention Cheat Sheet, "Defense Option 3: Allow-list Input Validation": https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
rusqlitedocumentation,params_from_iter: https://docs.rs/rusqlite/0.32.1/rusqlite/fn.params_from_iter.html