Skip to content

Commit 4f05e3b

Browse files
authored
Merge pull request #7 from mahendra-dhakal/validateSQL
Replace the regex based SQL validation with sqlparse
2 parents 93c6388 + 06bb2e1 commit 4f05e3b

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

src/routes.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
from starlette.responses import PlainTextResponse
1313
from src.database import DatabaseManager
1414
from src.llm import generate_sql_from_llm
15+
import sqlparse
16+
from sqlparse.sql import Identifier, IdentifierList
17+
from sqlparse.tokens import Keyword
1518

1619
logger = logging.getLogger(__name__)
1720

@@ -27,12 +30,19 @@ def postprocess_llm_pipeline_data(response: object) -> str:
2730

2831
def validate_sql_before_execute(sql_query: str) -> bool:
2932
"""Validates the SQL query to ensure it does not contain any potentially dangerous statements."""
30-
dangerous_patterns = [r'\bDROP\b', r'\bDELETE\b', r'\bTRUNCATE\b', r'\bALTER\b',
31-
r'\bUPDATE\b', r'\bCREATE\b', r'\bGRANT\b', r'\bREVOKE\b']
32-
for pattern in dangerous_patterns:
33-
if re.search(pattern, sql_query, re.IGNORECASE):
34-
logger.warning("Dangerous SQL keyword found! Preventing execution.")
35-
raise ValueError("The SQL query contains a potentially dangerous statement and cannot be executed.")
33+
dangerous_keywords = {"DROP", "DELETE", "TRUNCATE", "ALTER", "UPDATE", "CREATE", "GRANT", "REVOKE"}
34+
35+
try:
36+
parsed = sqlparse.parse(sql_query)
37+
for statement in parsed:
38+
for token in statement.tokens:
39+
if token.ttype == Keyword and token.value.upper() in dangerous_keywords:
40+
logger.warning(f"Dangerous SQL keyword '{token.value}' found! Preventing execution.")
41+
raise ValueError(f"The SQL query contains a potentially dangerous statement: '{token.value}'")
42+
except Exception as e:
43+
logger.error(f"Error during SQL validation: {e}")
44+
raise ValueError("Invalid SQL query.")
45+
3646
return True
3747

3848
def sanitize_query(input_text: str) -> str:

0 commit comments

Comments
 (0)