Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[flake8-bandit] Detect patterns from multi line SQL statements (S608) #13574

Merged
merged 21 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 48 additions & 6 deletions crates/ruff_linter/resources/test/fixtures/flake8_bandit/S608.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# single-line failures

var, table, val, var2, x = "", "", "", "", ""
query1 = "SELECT %s FROM table" % (var,) # bad
MichaReiser marked this conversation as resolved.
Show resolved Hide resolved
query2 = "SELECT var FROM " + table
query3 = "SELECT " + val + " FROM " + table
Expand Down Expand Up @@ -79,6 +81,7 @@ def query41():
f"WHERE var = {var}"
)

cursor = None
MichaReiser marked this conversation as resolved.
Show resolved Hide resolved
# # cursor-wrapped failures
query42 = cursor.execute("SELECT * FROM table WHERE var = %s" % var)
query43 = cursor.execute(f"SELECT * FROM table WHERE var = {var}")
Expand All @@ -95,18 +98,57 @@ def query41():
cursor.executemany('SELECT * FROM table WHERE id = %s', [var, var2])

# # INSERT without INTO (e.g. MySQL and derivatives)
query = "INSERT table VALUES (%s)" % (var,)
query46 = "INSERT table VALUES (%s)" % (var,)

# # REPLACE (e.g. MySQL and derivatives, SQLite)
query = "REPLACE INTO table VALUES (%s)" % (var,)
query = "REPLACE table VALUES (%s)" % (var,)
query47 = "REPLACE INTO table VALUES (%s)" % (var,)
query48 = "REPLACE table VALUES (%s)" % (var,)

query = "Deselect something that is not SQL even though it has a ' from ' somewhere in %s." % "there"
query49 = "Deselect something that is not SQL even though it has a ' from ' somewhere in %s." % "there"

# # pass
["select colA from tableA"] + ["select colB from tableB"]
"SELECT * FROM " + (["table1"] if x > 0 else ["table2"])

# # errors
"SELECT * FROM " + ("table1" if x > 0 else "table2")
"SELECT * FROM " + ("table1" if x > 0 else ["table2"])
"SELECT * FROM " + ("table1" if x > 0 else "table2") # query50
"SELECT * FROM " + ("table1" if x > 0 else ["table2"]) # query51

# test cases from #12044

def query52():
return f"""
SELECT {var}
FROM bar
"""

def query53():
return f"""
SELECT
{var}
FROM bar
"""

def query54():
return f"""
SELECT {var}
FROM
bar
"""

query55 = f"""SELECT * FROM
{var}.table
"""

query56 = f"""SELECT *
FROM {var}.table
"""

query57 = f"""
SELECT *
FROM {var}.table
"""

# to be handled seperately
# query58 = f"SELECT\
# * FROM {var}.table"
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
use once_cell::sync::Lazy;
use regex::Regex;
use ruff_python_ast::{self as ast, Expr, Operator};

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::str::raw_contents;
use ruff_python_ast::{self as ast, Expr, Operator};
use ruff_source_file::Locator;
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;

static SQL_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"(?i)\b(select\s.+\sfrom\s|delete\s+from\s|(insert|replace)\s.+\svalues\s|update\s.+\sset\s)")
.unwrap()
Regex::new(r"(?i)(select\s+.*\s+from\s|delete\s+from\s|(insert|replace)\s+.*\s+values\s|update\s+.*\s+set\s)")
.unwrap()
MichaReiser marked this conversation as resolved.
Show resolved Hide resolved
});

/// ## What it does
Expand Down Expand Up @@ -88,7 +87,6 @@ pub(crate) fn hardcoded_sql_expression(checker: &mut Checker, expr: &Expr) {
};
string.value.to_str().escape_default().to_string()
}
// f"select * from table where val = {val}"
MichaReiser marked this conversation as resolved.
Show resolved Hide resolved
Expr::FString(f_string) => concatenated_f_string(f_string, checker.locator()),
_ => return,
};
Expand All @@ -113,9 +111,7 @@ pub(crate) fn hardcoded_sql_expression(checker: &mut Checker, expr: &Expr) {
fn concatenated_f_string(expr: &ast::ExprFString, locator: &Locator) -> String {
expr.value
.iter()
.filter_map(|part| {
raw_contents(locator.slice(part)).map(|s| s.escape_default().to_string())
})
.filter_map(|part| raw_contents(locator.slice(part)))
.collect()
}

Expand Down
Loading
Loading