#sql #postgresql #sql-injection

pg_escape

A Rust library to escape Postgres flavoured SQL

2 releases

0.1.1 Nov 1, 2024
0.1.0 Oct 31, 2024

#483 in Database interfaces

Download history 237/week @ 2024-12-07 267/week @ 2024-12-14 179/week @ 2024-12-21 253/week @ 2024-12-28 1133/week @ 2025-01-04 6330/week @ 2025-01-11 4040/week @ 2025-01-18 10547/week @ 2025-01-25 14575/week @ 2025-02-01 8697/week @ 2025-02-08 7409/week @ 2025-02-15 7425/week @ 2025-02-22 10231/week @ 2025-03-01 13929/week @ 2025-03-08 12364/week @ 2025-03-15 10734/week @ 2025-03-22

49,336 downloads per month
Used in 7 crates (via cql2)

MIT/Apache

22KB
517 lines

pg_escape

pg_escape is a Rust library to escape Postgres flavoured SQL.

To avoid SQL injection attacks it is necessary to properly escape user input. This library provides functions for that.

quote_identifier

Use quote_identifier to properly quote an identifier. An identifier names a database object. E.g. names of tables, columns, view etc. are identifiers. Inability to quote user supplied identifiers leads to SQL injection attacks. For example, if your system accepts a table name from a user and runs a select * from <table_name> query, it is vulnerable to SQL injection attacks if constructed like this:

let table_name = "users";//supplied by user
let query = format!("select * from {table_name}");

Instead, do this:

use pg_escape::quote_identifier;

let table_name = "users";//supplied by user
let quoted_table_name = quote_identifier(table_name);
let query = format!("select * from {quoted_table_name}");

quote_literal

Use quote_literal to properly quote a literal. A literal is a value which is written literally in a SQL expression. Similar to quote_identifier, ensure that user supplied literals are quoted. For example, don't do this:

let user = "john";//supplied by user
let query = format!("select * from users where username = {user}");

Do this instead:

use pg_escape::quote_literal;

let user = "john";//supplied by user
let quoted_user = quote_literal(user);
let query = format!("select * from users where username = {quoted_user}");

When not to use pg_escape

Many Postgres client libraries and clients provide an option to run prepared statements (aka parameterized queries). Use them if available. pg_escape is useful for those constrained environments where prepared statements are not available. One example of such an environment is if you are connected to Postgres over a replication connection. A replication connection only supports a simple query protocol as mentioned in the Postgres streaming replication protocol document.

Dependencies

~0.6–1MB
~23K SLoC