Skip to content

Commit e958329

Browse files
committed
fix: describegpt more robust sql escaping to prevent SQL injection
1 parent 421be84 commit e958329

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

src/cmd/describegpt.rs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -347,10 +347,23 @@ static READ_CSV_AUTO_REGEX: std::sync::LazyLock<regex::Regex> = std::sync::LazyL
347347
regex::Regex::new("read_csv_auto\\([^)]*\\)").expect("Invalid regex pattern")
348348
});
349349

350-
/// Escapes single quotes in a string for safe use in SQL string literals.
351-
/// SQL standard: single quotes are escaped by doubling them: ' becomes ''
350+
/// Escape a string for safe usage as a SQL string literal.
351+
///
352+
/// This function ensures that common problematic characters (such as single quotes, backslashes,
353+
/// newlines, carriage returns, and null bytes) are properly escaped according to SQL string
354+
/// literal rules.
355+
///
356+
/// - Single quotes are escaped by doubling them (`'` → `''`), as per the SQL standard.
357+
/// - Backslashes are escaped by doubling (`\` → `\\`). Backslash escaping is non-standard SQL but
358+
/// prevents certain injection scenarios, and must come first in this implementation.
359+
/// - Newline (`\n`), carriage return (`\r`), and null byte (`\0`) are replaced by their C-like
360+
/// escape sequence representations (`\\n`, `\\r`, `\\0`).
352361
fn escape_sql_string(s: &str) -> String {
353-
s.replace('\'', "''")
362+
s.replace('\\', "\\\\") // Backslash must be first!
363+
.replace('\'', "''")
364+
.replace('\n', "\\n")
365+
.replace('\r', "\\r")
366+
.replace('\0', "\\0")
354367
}
355368

356369
static DEFAULT_REDIS_CONN_STRING: OnceLock<String> = OnceLock::new();

0 commit comments

Comments
 (0)