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

DH-4692/updating the SQL guards to use sqlparse #171

Merged
merged 1 commit into from
Sep 19, 2023
Merged
Changes from all commits
Commits
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
22 changes: 13 additions & 9 deletions dataherald/sql_database/base.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""SQL wrapper around SQLDatabase in langchain."""
import logging
import re
from typing import Any, List
from urllib.parse import unquote

import sqlparse
from langchain.sql_database import SQLDatabase as LangchainSQLDatabase
from sqlalchemy import MetaData, create_engine, text
from sqlalchemy.engine import Engine
Expand Down Expand Up @@ -119,14 +119,18 @@ def parser_to_filter_commands(cls, command: str) -> str:
"MERGE",
"EXECUTE",
]
pattern = (
r"\b(?:" + "|".join(re.escape(word) for word in sensitive_keywords) + r")\b"
)
match = re.search(pattern, command, re.IGNORECASE)
if match:
raise SQLInjectionError(
f"Sensitive SQL keyword '{match.group()}' detected in the query."
)
parsed_command = sqlparse.parse(command)

for stmt in parsed_command:
for token in stmt.tokens:
if (
isinstance(token, sqlparse.sql.Token)
and token.normalized in sensitive_keywords
):
raise SQLInjectionError(
f"Sensitive SQL keyword '{token.normalized}' detected in the query."
)

return command

def run_sql(self, command: str) -> tuple[str, dict]:
Expand Down