Repository navigation
Expand file tree
/
Copy pathtest_check_sql_read_writes.py
More file actions
58 lines (46 loc) · 2.16 KB
/
Copy pathtest_check_sql_read_writes.py
File metadata and controls
58 lines (46 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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]