Skip to content

Commit e396806

Browse files
committed
restricted sql permissions to SELECT/PRAGMA queries only
1 parent 90c9af0 commit e396806

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/any_chatbot/tools.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,29 @@ def retrieve(
4040
return retrieve
4141

4242

43+
def is_safe_sql(query: str) -> bool:
44+
"""Filters out destructive sql queries"""
45+
forbidden = ["insert", "update", "delete", "drop", "alter", "create", "replace"]
46+
# Make sure to only block whole words (e.i., don't block 'updated_at')
47+
return not any(f" {word} " in f" {query.lower()} " for word in forbidden)
48+
49+
4350
def initialize_sql_toolkit(
4451
llm,
45-
db_path: Path = DATA / "csv_excel_to_db" / "my_data.duckdb",
52+
db_path: Path = DATA / "generated_db" / "csv_excel_to_db.duckdb",
4653
):
4754
db = SQLDatabase.from_uri(f"duckdb:///{db_path}")
55+
56+
# Monkey-path the run method to include safety filter
57+
original_run = db.run
58+
59+
def safe_run(query: str, *args, **kwargs):
60+
if not is_safe_sql(query):
61+
return "Query blocked: Only SELECT/PRAGMA queries are allowed."
62+
return original_run(query, *args, **kwargs)
63+
64+
db.run = safe_run
65+
4866
toolkit = SQLDatabaseToolkit(db=db, llm=llm)
4967
tools = toolkit.get_tools()
5068
return tools

0 commit comments

Comments
 (0)