FAQ - Help and questions

How do I build SQL with a variable sort column or an IN list without injection?

#security#sql#rusqlitepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Placeholders carry values, not column names, so map the user's sort choice onto a fixed list of column names with an enum and a match. For an IN list, build one placeholder per value and still bind every value. Unknown choices fall back to a default instead of reaching the SQL.

Checked with rustc 1.93.0, rusqlite 0.32.1 (bundled SQLite), Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.
src/main.rsrust
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(())
}
text
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#

  1. Represent each allowed choice as an enum variant.
  2. Parse the user's string into the enum (an unknown value gives the default or an error, your decision).
  3. Turn the enum into a literal column name in one place.
  4. Make the number of placeholders from the number of values, and refuse lists above a limit (databases have a maximum number of parameters).
  5. Use the same pattern for the direction (ASC or DESC): 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet