Skip to content
Open
Show file tree
Hide file tree
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
14 changes: 11 additions & 3 deletions backend/apps/db/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -1296,14 +1296,22 @@ def check_sql_read(sql: str, ds: CoreDatasource | AssistantOutDsSchema) -> tuple
write_types = (
exp.Insert, exp.Update, exp.Delete,
exp.Create, exp.Drop, exp.Alter,
exp.Merge, exp.Copy
exp.Merge, exp.Copy, exp.TruncateTable,
exp.Set, exp.Grant, exp.Revoke, exp.Into
)

for stmt in statements:
if stmt is None:
continue
if isinstance(stmt, write_types):
return False, f"SQL contains write operation: {type(stmt).__name__}"
# 递归检查,CTE 中的写操作和 SELECT ... INTO 也会被拦截
write_node = stmt.find(*write_types)
if write_node is not None:
return False, f"SQL contains write operation: {type(write_node).__name__}"
# sqlglot 无法解析的语句会退化为 Command(如 CALL),按其关键字检查
if isinstance(stmt, exp.Command):
command = str(stmt.this).upper()
if command not in allowed_read_commands:
return False, f"SQL command '{command}' is not allowed"

if first_keyword not in allowed_read_commands:
return False, f"SQL command '{first_keyword}' is not allowed. Only SELECT and WITH are permitted"
Expand Down
58 changes: 58 additions & 0 deletions backend/tests/test_check_sql_read_writes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Regression coverage for write statements slipping through `check_sql_read` (issue 1542).

The write check only looked at the type of each top-level statement, and the
keyword check only at the first word of the whole SQL. Writes nested in a CTE,
`SELECT ... INTO`, and a write placed after a harmless first statement were all
accepted as read-only.
"""

from types import SimpleNamespace

import pytest
import sqlbot_xpack # noqa: F401 # Initialize the published wheel before app imports.

from apps.db.constant import DB
from apps.db.db import check_sql_read, settings


def _ds(db: DB) -> SimpleNamespace:
return SimpleNamespace(type=db.type)


@pytest.mark.parametrize(
"db, sql",
[
(DB.pg, "WITH d AS (DELETE FROM orders WHERE id = 1 RETURNING id) SELECT * FROM d"),
(DB.pg, "WITH u AS (UPDATE orders SET amount = 0 RETURNING id) SELECT * FROM u"),
(DB.pg, "WITH i AS (INSERT INTO orders (id) VALUES (1) RETURNING id) SELECT * FROM i"),
(DB.pg, "SELECT id INTO leaked_copy FROM orders"),
(DB.pg, "SELECT 1; TRUNCATE TABLE orders"),
(DB.pg, "SELECT 1; SET default_transaction_read_only = off"),
(DB.pg, "SELECT 1; GRANT ALL ON orders TO public"),
(DB.pg, "SELECT 1; REVOKE ALL ON orders FROM public"),
(DB.mysql, "SELECT 1; CALL sp_mutator()"),
],
)
def test_nested_and_trailing_writes_are_rejected(db, sql):
is_safe, _ = check_sql_read(sql, _ds(db))
assert not is_safe


@pytest.mark.parametrize(
"db, sql",
[
(DB.pg, "WITH t AS (SELECT id FROM orders) SELECT * FROM t"),
(DB.pg, "SELECT * FROM orders WHERE id IN (SELECT id FROM refunds)"),
(DB.mysql, "SELECT id FROM orders; SELECT id FROM refunds"),
],
)
def test_plain_reads_are_still_allowed(db, sql):
is_safe, reason = check_sql_read(sql, _ds(db))
assert is_safe, reason


def test_metadata_commands_still_follow_the_setting(monkeypatch):
monkeypatch.setattr(settings, "SQLBOT_ALLOW_METADATA_QUERIES", True)
assert check_sql_read("SHOW TABLES", _ds(DB.mysql))[0]
assert check_sql_read("EXPLAIN SELECT 1", _ds(DB.pg))[0]
assert not check_sql_read("SELECT 1; CALL sp_mutator()", _ds(DB.mysql))[0]
Loading